Compare commits

..
Author SHA1 Message Date
Connor Yoh 0fe5a1706e Merge remote-tracking branch 'origin/main' into unified-sign-tool 2026-03-30 15:29:45 +01:00
Connor YohandClaude Sonnet 4.6 e194fc7e36 fix(sign): prevent custom workbench auto-revert when opening sign editor
`unregisterCustomWorkbenchView` depended on `[actions]` from
NavigationContext. Because `actions` gets a new reference every time
`workbench` changes (setWorkbench captures state.workbench in its
closure), the registration effect in CombinedSign re-ran on each
workbench update, firing cleanup → clearCustomWorkbenchViewData →
auto-revert effect reverted the workbench back to default.

Fix: introduce `actionsRef` (updated each render, stable identity) and
use it in `unregisterCustomWorkbenchView` (now has empty dep array) and
the auto-revert effect (removes `actions` from deps). Also cleaned up
diagnostic console.log calls added during debugging.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 17:31:35 +00:00
Connor Yoh a651061554 feat(sign): merge cert-sign and wet-sign into a unified Sign tool
Combines the separate CertSign and Sign tools into a single "Sign"
entry that mirrors the shared-signing participant view. Users pick
wet sign, cert sign, or both from a segmented control at the top of
the full-screen editor.

New files:
- CombinedSignEditor.tsx — full-screen editor with mode selector,
  SignControlsStrip for wet/both modes, LocalEmbedPDFWithAnnotations,
  and CertificateConfigModal (with optional appearance settings)
- CombinedSign.tsx — tool entry point; registers editor as a custom
  workbench view (hideToolPanel: true) and opens it on demand
- useCombinedSignOperation.ts — submitCertSign (cert-sign endpoint)
  and submitWetOnly (sequential add-signature calls)

Modified files:
- CertificateConfigModal — adds showAppearanceSettings prop that
  renders SignatureSettingsInput and passes appearance data to onSign
- toolId.ts — removes certSign from CORE_REGULAR_TOOL_IDS
- useTranslatedToolRegistry — removes certSign entry; sign entry now
  uses CombinedSign with endpoints ["sign", "cert-sign"]
- urlMapping.ts — /cert-sign and /manage-signatures redirect to sign
- SignPopout.tsx — quick-access cert-sign button now selects sign
- creditCosts.ts — merges certSign credit cost into sign (LARGE)
- translation.toml — adds sign.editor.* and sign.mode.* keys
2026-03-27 15:47:44 +00:00
100 changed files with 1730 additions and 4298 deletions
+1 -1
View File
@@ -513,7 +513,7 @@ jobs:
echo "base_image=stirling-pdf-base:pr-test" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
else
echo "base_image=stirlingtools/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "base_image=ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64,linux/arm64/v8" >> $GITHUB_OUTPUT
fi
@@ -112,6 +112,8 @@ public class FileMonitor {
All files observed changes in the last iteration will be considered as staging files.
If those files are not modified in current iteration, they will be considered as ready for processing.
*/
stagingFiles = new HashSet<>(newlyDiscoveredFiles);
readyForProcessingFiles.clear();
if (path2KeyMapping.isEmpty()) {
log.warn("Not monitoring any directories; attempting to re-register root paths.");
@@ -127,17 +129,8 @@ public class FileMonitor {
}
}
// Skip expensive collection work when there is nothing to track
WatchKey firstKey = watchService.poll();
if (firstKey == null && newlyDiscoveredFiles.isEmpty() && readyForProcessingFiles.isEmpty()) {
return;
}
stagingFiles = new HashSet<>(newlyDiscoveredFiles);
readyForProcessingFiles.clear();
WatchKey key = firstKey;
while (key != null) {
WatchKey key;
while ((key = watchService.poll()) != null) {
final Path watchingDir = (Path) key.watchable();
key.pollEvents()
.forEach(
@@ -174,7 +167,6 @@ public class FileMonitor {
if (!isKeyValid) { // key is invalid when the directory itself is no longer exists
path2KeyMapping.remove((Path) key.watchable());
}
key = watchService.poll();
}
readyForProcessingFiles.addAll(stagingFiles);
}
@@ -1,22 +1,19 @@
package stirling.software.SPDF.controller.api.misc;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -24,7 +21,6 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
import com.google.zxing.*;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import io.github.pixee.security.Filenames;
@@ -39,6 +35,7 @@ import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
@@ -51,219 +48,61 @@ import stirling.software.common.util.WebResponseUtils;
public class AutoSplitPdfController {
private static final Set<String> VALID_QR_CONTENTS =
Set.of(
"https://github.com/Stirling-Tools/Stirling-PDF",
"https://github.com/Frooodle/Stirling-PDF",
"https://stirlingpdf.com");
private static final int MAX_IMAGES_FOR_DIRECT_EXTRACTION = 3;
// 150 DPI is sufficient for QR code detection — higher wastes memory and CPU
private static final int QR_DETECTION_DPI = 150;
// Max total pixels before we downscale to avoid OOM on getRGB() allocation
private static final long MAX_IMAGE_PIXELS = 100_000_000L; // ~10000x10000
// Number of evenly-spaced pixel samples used for the blank image check
private static final int BLANK_CHECK_SAMPLES = 20;
private static final Map<DecodeHintType, Object> DECODE_HINTS;
static {
DECODE_HINTS = new EnumMap<>(DecodeHintType.class);
DECODE_HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
DECODE_HINTS.put(DecodeHintType.ALSO_INVERTED, Boolean.TRUE);
DECODE_HINTS.put(DecodeHintType.POSSIBLE_FORMATS, List.of(BarcodeFormat.QR_CODE));
}
new HashSet<>(
Set.of(
"https://github.com/Stirling-Tools/Stirling-PDF",
"https://github.com/Frooodle/Stirling-PDF",
"https://stirlingpdf.com"));
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private final ApplicationProperties applicationProperties;
/**
* Downscale an image if it exceeds the maximum pixel count. Scales uniformly based on the
* pixel-count ratio so both portrait and landscape images are handled correctly.
*/
private static BufferedImage downscaleIfNeeded(BufferedImage image) {
long totalPixels = (long) image.getWidth() * image.getHeight();
if (totalPixels <= MAX_IMAGE_PIXELS) {
return image;
}
double scale = Math.sqrt((double) MAX_IMAGE_PIXELS / totalPixels);
int newWidth = Math.max(1, (int) (image.getWidth() * scale));
int newHeight = Math.max(1, (int) (image.getHeight() * scale));
log.debug(
"Downscaling image from {}x{} to {}x{} for QR detection",
image.getWidth(),
image.getHeight(),
newWidth,
newHeight);
BufferedImage scaled = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
return scaled;
}
/**
* Quick check whether an image appears to be blank (single solid colour). Samples pixels at
* evenly-spaced positions — if all samples match the first pixel the image is almost certainly
* blank (e.g. a masked image that returned solid white).
*/
private static boolean isBlankImage(int[] pixels) {
if (pixels.length == 0) return true;
int first = pixels[0];
int step = Math.max(1, pixels.length / BLANK_CHECK_SAMPLES);
for (int i = step; i < pixels.length; i += step) {
if (pixels[i] != first) {
return false;
}
}
return true;
}
/**
* Try to decode a QR code from pre-extracted RGB pixel data using multiple binarization
* strategies. Returns the decoded text or null.
*
* <p>Strategy 1: HybridBinarizer — good for variable brightness (digital PDFs).
*
* <p>Strategy 2: GlobalHistogramBinarizer — better for scanned/noisy images with uniform
* lighting, and for QR codes with embedded logos that confuse the hybrid approach.
*/
private static String tryDecodeQR(int[] pixels, int width, int height) {
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
MultiFormatReader reader = new MultiFormatReader();
// Strategy 1: HybridBinarizer — good for variable brightness (digital PDFs)
try {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap, DECODE_HINTS);
log.debug("QR detected via HybridBinarizer: '{}'", result.getText());
return result.getText();
} catch (NotFoundException e) {
// continue
}
// Strategy 2: GlobalHistogramBinarizer — better for scanned/noisy images
try {
BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Result result = reader.decode(bitmap, DECODE_HINTS);
log.debug("QR detected via GlobalHistogramBinarizer: '{}'", result.getText());
return result.getText();
} catch (NotFoundException e) {
return null;
}
}
/**
* Attempt to decode a QR code from a BufferedImage. Handles downscaling for oversized images
* and skips blank images early.
*/
private static String decodeQRCode(BufferedImage bufferedImage) {
bufferedImage = downscaleIfNeeded(bufferedImage);
LuminanceSource source;
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
int[] pixels = new int[width * height];
bufferedImage.getRGB(0, 0, width, height, pixels, 0, width);
// Skip blank images early (e.g. masked images that decode to solid white)
if (isBlankImage(pixels)) {
log.debug("Skipping blank {}x{} image", width, height);
return null;
}
return tryDecodeQR(pixels, width, height);
}
/** Count the number of images embedded in a page's resources. */
private static int countPageImages(PDPage page) {
if (page.getResources() == null || page.getResources().getXObjectNames() == null) {
return 0;
}
int count = 0;
for (COSName name : page.getResources().getXObjectNames()) {
if (page.getResources().isImageXObject(name)) {
count++;
if (bufferedImage.getRaster().getDataBuffer() instanceof DataBufferByte dataBufferByte) {
byte[] pixels = dataBufferByte.getData();
source =
new PlanarYUVLuminanceSource(
pixels,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
0,
0,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
false);
} else if (bufferedImage.getRaster().getDataBuffer()
instanceof DataBufferInt dataBufferInt) {
int[] pixels = dataBufferInt.getData();
byte[] newPixels = new byte[pixels.length];
for (int i = 0; i < pixels.length; i++) {
newPixels[i] = (byte) (pixels[i] & 0xff);
}
source =
new PlanarYUVLuminanceSource(
newPixels,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
0,
0,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
false);
} else {
throw new IllegalArgumentException(
"BufferedImage must have 8-bit gray scale, 24-bit RGB, 32-bit ARGB (packed"
+ " int), byte gray, or 3-byte/4-byte RGB image data");
}
return count;
}
/**
* Extract images directly from a page's resources and check each for a QR code. Returns the QR
* code text if found, null otherwise.
*/
private static String checkPageImagesDirect(PDPage page) throws IOException {
if (page.getResources() == null || page.getResources().getXObjectNames() == null) {
return null;
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (NotFoundException e) {
return null; // there is no QR code in the image
}
for (COSName name : page.getResources().getXObjectNames()) {
if (!page.getResources().isImageXObject(name)) {
continue;
}
PDImageXObject imageObject = (PDImageXObject) page.getResources().getXObject(name);
BufferedImage image;
try {
image = imageObject.getImage();
} catch (OutOfMemoryError e) {
log.warn(
"Skipping oversized embedded image '{}' ({}x{}) - out of memory",
name.getName(),
imageObject.getWidth(),
imageObject.getHeight());
continue;
}
String result = decodeQRCode(image);
if (result != null) {
return result;
}
}
return null;
}
/**
* Render the full page to an image and scan it for a QR code. Tries a low DPI first (fast, low
* memory) and only retries at the system's maxDPI if detection fails. The first rendered image
* is released before the retry to allow GC to reclaim it.
*/
private String checkPageByRendering(PDFRenderer pdfRenderer, int pageNum) throws IOException {
log.debug("Rendering page {} at {} DPI for QR detection", pageNum + 1, QR_DETECTION_DPI);
BufferedImage bim =
ExceptionUtils.handleOomRendering(
pageNum + 1,
QR_DETECTION_DPI,
() -> pdfRenderer.renderImageWithDPI(pageNum, QR_DETECTION_DPI));
String result = decodeQRCode(bim);
bim = null; // allow GC before potential high-DPI retry
if (result == null) {
int maxDpi = getSystemMaxDpi();
if (maxDpi > QR_DETECTION_DPI) {
log.debug(
"Retrying page {} at {} DPI (low-DPI detection failed)",
pageNum + 1,
maxDpi);
BufferedImage highRes =
ExceptionUtils.handleOomRendering(
pageNum + 1,
maxDpi,
() -> pdfRenderer.renderImageWithDPI(pageNum, maxDpi));
result = decodeQRCode(highRes);
}
}
return result;
}
private int getSystemMaxDpi() {
if (applicationProperties != null && applicationProperties.getSystem() != null) {
return applicationProperties.getSystem().getMaxDPI();
}
return QR_DETECTION_DPI;
}
@AutoJobPostMapping(value = "/auto-split-pdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@@ -272,56 +111,42 @@ public class AutoSplitPdfController {
summary = "Auto split PDF pages into separate documents",
description =
"This endpoint accepts a PDF file, scans each page for a specific QR code, and"
+ " splits the document at the QR code boundaries. The output is a zip"
+ " file containing each separate PDF document. Input:PDF Output:ZIP-PDF"
+ " splits the document at the QR code boundaries. The output is a zip file"
+ " containing each separate PDF document. Input:PDF Output:ZIP-PDF"
+ " Type:SISO")
public ResponseEntity<byte[]> autoSplitPdf(@ModelAttribute AutoSplitPdfRequest request)
throws IOException {
MultipartFile file = request.getFileInput();
boolean duplexMode = Boolean.TRUE.equals(request.getDuplexMode());
log.info(
"Auto-split starting: filename='{}', size={} bytes, duplexMode={}",
file.getOriginalFilename(),
file.getSize(),
duplexMode);
List<PDDocument> splitDocuments = new ArrayList<>();
try (TempFile outputTempFile = new TempFile(tempFileManager, ".zip");
PDDocument document = pdfDocumentFactory.load(file.getInputStream())) {
int totalPages = document.getNumberOfPages();
log.info("PDF loaded, totalPages={}", totalPages);
PDFRenderer pdfRenderer = new PDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (int page = 0; page < totalPages; ++page) {
PDPage pdPage = document.getPage(page);
int imageCount = countPageImages(pdPage);
for (int page = 0; page < document.getNumberOfPages(); ++page) {
BufferedImage bim;
String qrResult;
if (imageCount > 0 && imageCount <= MAX_IMAGES_FOR_DIRECT_EXTRACTION) {
// Try extracting images directly from the PDF (faster, avoids rendering)
qrResult = checkPageImagesDirect(pdPage);
if (qrResult == null) {
// Fall back to rendering — the image may use masking/compositing
// that getImage() doesn't resolve, or the QR may be vector-drawn
qrResult = checkPageByRendering(pdfRenderer, page);
}
} else {
// Too many images or no images — render the full page
qrResult = checkPageByRendering(pdfRenderer, page);
// Use global maximum DPI setting, fallback to 300 if not set
int renderDpi = 150; // Default fallback
ApplicationProperties properties =
ApplicationContextProvider.getBean(ApplicationProperties.class);
if (properties != null && properties.getSystem() != null) {
renderDpi = properties.getSystem().getMaxDPI();
}
final int dpi = renderDpi;
final int pageNum = page;
boolean isValidQrCode = qrResult != null && VALID_QR_CONTENTS.contains(qrResult);
if (isValidQrCode) {
log.info(
"Page {}/{} contains QR divider ('{}')",
page + 1,
totalPages,
qrResult);
}
bim =
ExceptionUtils.handleOomRendering(
pageNum + 1,
dpi,
() -> pdfRenderer.renderImageWithDPI(pageNum, dpi));
String result = decodeQRCode(bim);
boolean isValidQrCode = VALID_QR_CONTENTS.contains(result);
log.debug("detected qr code {}, code is vale={}", result, isValidQrCode);
if (isValidQrCode && page != 0) {
splitDocuments.add(new PDDocument());
}
@@ -334,25 +159,32 @@ public class AutoSplitPdfController {
splitDocuments.add(firstDocument);
}
// If duplexMode is true and current page is a divider, then skip next page
if (duplexMode && isValidQrCode) {
page++; // skip back of divider page
page++;
}
}
// Remove split documents that have no pages
splitDocuments.removeIf(pdDocument -> pdDocument.getNumberOfPages() == 0);
log.info("Split complete, {} output documents", splitDocuments.size());
String filename =
GeneralUtils.removeExtension(
Filenames.toSimpleFileName(file.getOriginalFilename()));
// Stream split documents directly into zip — avoids holding all PDFs in memory
try (OutputStream fileOut = Files.newOutputStream(outputTempFile.getPath());
ZipOutputStream zipOut = new ZipOutputStream(fileOut)) {
try (ZipOutputStream zipOut =
new ZipOutputStream(Files.newOutputStream(outputTempFile.getPath()))) {
for (int i = 0; i < splitDocuments.size(); i++) {
String fileName = filename + "_" + (i + 1) + ".pdf";
zipOut.putNextEntry(new ZipEntry(fileName));
splitDocuments.get(i).save(zipOut);
PDDocument splitDocument = splitDocuments.get(i);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
splitDocument.save(baos);
byte[] pdf = baos.toByteArray();
ZipEntry pdfEntry = new ZipEntry(fileName);
zipOut.putNextEntry(pdfEntry);
zipOut.write(pdf);
zipOut.closeEntry();
}
}
@@ -365,6 +197,7 @@ public class AutoSplitPdfController {
log.error("Error in auto split", e);
throw e;
} finally {
// Clean up split documents
for (PDDocument splitDoc : splitDocuments) {
try {
splitDoc.close();
@@ -47,7 +47,6 @@ import stirling.software.proprietary.security.model.dto.AdminUserSummary;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.MfaService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -72,7 +71,6 @@ public class ProprietaryUIDataController {
private final UserLicenseSettingsService licenseSettingsService;
private final PersistentAuditEventRepository auditRepository;
private final MfaService mfaService;
private final LoginAttemptService loginAttemptService;
public ProprietaryUIDataController(
ApplicationProperties applicationProperties,
@@ -86,8 +84,7 @@ public class ProprietaryUIDataController {
@Qualifier("runningEE") boolean runningEE,
UserLicenseSettingsService licenseSettingsService,
PersistentAuditEventRepository auditRepository,
MfaService mfaService,
LoginAttemptService loginAttemptService) {
MfaService mfaService) {
this.applicationProperties = applicationProperties;
this.auditConfig = auditConfig;
this.sessionPersistentRegistry = sessionPersistentRegistry;
@@ -100,7 +97,6 @@ public class ProprietaryUIDataController {
this.licenseSettingsService = licenseSettingsService;
this.auditRepository = auditRepository;
this.mfaService = mfaService;
this.loginAttemptService = loginAttemptService;
}
/**
@@ -391,7 +387,6 @@ public class ProprietaryUIDataController {
data.setPremiumEnabled(premiumEnabled);
data.setMailEnabled(applicationProperties.getMail().isEnabled());
data.setUserSettings(userSettings);
data.setLockedUsers(loginAttemptService.getAllBlockedUsers());
return ResponseEntity.ok(data);
}
@@ -610,7 +605,6 @@ public class ProprietaryUIDataController {
private boolean premiumEnabled;
private boolean mailEnabled;
private Map<String, Map<String, String>> userSettings;
private List<String> lockedUsers;
}
@Data
@@ -159,13 +159,10 @@ public class SecurityConfiguration {
firewall.setAllowedHeaderValues(
headerValue -> headerValue != null && allowedChars.matcher(headerValue).matches());
// Allow non-ASCII characters and newlines in parameter values.
Pattern allowedParamChars =
Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]\\r\\n]*");
// Apply the same rules to parameter values for consistency.
firewall.setAllowedParameterValues(
parameterValue ->
parameterValue != null
&& allowedParamChars.matcher(parameterValue).matches());
parameterValue != null && allowedChars.matcher(parameterValue).matches());
return firewall;
}
@@ -48,7 +48,6 @@ import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.SaveUserRequest;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
@@ -68,7 +67,6 @@ public class UserController {
private final UserRepository userRepository;
private final Optional<EmailService> emailService;
private final UserLicenseSettingsService licenseSettingsService;
private final LoginAttemptService loginAttemptService;
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/register")
@@ -777,14 +775,6 @@ public class UserController {
Map.of("message", "User " + (enabled ? "enabled" : "disabled") + " successfully"));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/unlockUser/{username}")
@Audited(type = AuditEventType.SETTINGS_CHANGED, level = AuditLevel.BASIC)
public ResponseEntity<?> unlockUser(@PathVariable("username") String username) {
loginAttemptService.resetAttempts(username);
return ResponseEntity.ok(Map.of("message", "User account unlocked successfully"));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/deleteUser/{username}")
@Audited(type = AuditEventType.USER_PROFILE_UPDATE, level = AuditLevel.BASIC)
@@ -1,11 +1,8 @@
package stirling.software.proprietary.security.service;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
@@ -82,28 +79,6 @@ public class LoginAttemptService {
return attemptCounter.getAttemptCount() >= MAX_ATTEMPT;
}
public void resetAttempts(String key) {
if (key == null || key.trim().isEmpty()) {
return;
}
String normalizedKey = key.toLowerCase(Locale.ROOT);
attemptsCache.remove(normalizedKey);
}
public boolean isBlockingEnabled() {
return isBlockedEnabled;
}
public List<String> getAllBlockedUsers() {
if (!isBlockedEnabled) {
return List.of();
}
return attemptsCache.entrySet().stream()
.filter(entry -> entry.getValue().getAttemptCount() >= MAX_ATTEMPT)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
public int getRemainingAttempts(String key) {
if (!isBlockedEnabled || key == null || key.trim().isEmpty()) {
// Arbitrarily high number if tracking is disabled
@@ -29,7 +29,6 @@ import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.MfaService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@@ -48,7 +47,6 @@ class ProprietaryUIDataControllerTest {
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private PersistentAuditEventRepository auditRepository;
@Mock private MfaService mfaService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private AuditConfigurationProperties auditConfig;
@@ -81,8 +79,7 @@ class ProprietaryUIDataControllerTest {
false,
licenseSettingsService,
auditRepository,
mfaService,
loginAttemptService);
mfaService);
}
@Test
@@ -28,7 +28,6 @@ import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -48,7 +47,6 @@ class UserControllerTest {
@Mock private UserRepository userRepository;
@Mock private EmailService emailService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private MockMvc mockMvc;
@@ -67,8 +65,7 @@ class UserControllerTest {
teamRepository,
userRepository,
Optional.of(emailService),
licenseSettingsService,
loginAttemptService);
licenseSettingsService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@@ -141,13 +138,4 @@ class UserControllerTest {
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error").value("User not found."));
}
@Test
void unlockUserCallsResetAttemptsAndReturnsOk() throws Exception {
mockMvc.perform(post("/api/v1/user/admin/unlockUser/lockeduser"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("User account unlocked successfully"));
verify(loginAttemptService).resetAttempts("lockeduser");
}
}
@@ -6,7 +6,6 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
@@ -237,145 +236,4 @@ class LoginAttemptServiceTest {
// If you later clamp to 0, update this assertion accordingly and add a new test.
assertEquals(expected, actual, "Current behavior returns negative values without clamping");
}
@Test
@DisplayName("resetAttempts(): removes entry from cache for given key")
void resetAttempts_shouldRemoveEntryFromCache() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
AttemptCounter counter = new AttemptCounter();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
ac.setInt(counter, 5);
attemptsCache.put("blockeduser", counter);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("resetAttempts", String.class);
method.invoke(svc, "BlockedUser"); // case-insensitive
assertFalse(
attemptsCache.containsKey("blockeduser"),
"resetAttempts should remove the user's entry from the cache");
}
@Test
@DisplayName("resetAttempts(): does nothing for null or blank key")
void resetAttempts_shouldDoNothingForNullOrBlankKey() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
attemptsCache.put("existing", new AttemptCounter());
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("resetAttempts", String.class);
method.invoke(svc, (Object) null);
method.invoke(svc, " ");
assertEquals(1, attemptsCache.size(), "Null or blank key should not modify the cache");
}
@Test
@DisplayName("isBlockingEnabled(): returns true when blocking is enabled")
void isBlockingEnabled_shouldReturnTrueWhenEnabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var method = svc.getClass().getMethod("isBlockingEnabled");
boolean result = (Boolean) method.invoke(svc);
assertTrue(result, "isBlockingEnabled should return true when isBlockedEnabled is true");
}
@Test
@DisplayName("isBlockingEnabled(): returns false when blocking is disabled")
void isBlockingEnabled_shouldReturnFalseWhenDisabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", false);
var method = svc.getClass().getMethod("isBlockingEnabled");
boolean result = (Boolean) method.invoke(svc);
assertFalse(result, "isBlockingEnabled should return false when isBlockedEnabled is false");
}
@Test
@DisplayName("getAllBlockedUsers(): returns empty list when blocking is disabled")
void getAllBlockedUsers_shouldReturnEmptyWhenDisabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", false);
setPrivate(svc, "attemptsCache", new ConcurrentHashMap<String, AttemptCounter>());
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertTrue(
result.isEmpty(),
"getAllBlockedUsers should return empty list when blocking is disabled");
}
@Test
@DisplayName("getAllBlockedUsers(): returns only users at or above MAX_ATTEMPT")
void getAllBlockedUsers_shouldReturnOnlyBlockedUsers() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
setPrivate(svc, "MAX_ATTEMPT", 3);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
// User with exactly MAX_ATTEMPT attempts (blocked)
AttemptCounter blocked1 = new AttemptCounter();
ac.setInt(blocked1, 3);
attemptsCache.put("blocked1", blocked1);
// User with more than MAX_ATTEMPT attempts (blocked)
AttemptCounter blocked2 = new AttemptCounter();
ac.setInt(blocked2, 5);
attemptsCache.put("blocked2", blocked2);
// User with fewer than MAX_ATTEMPT attempts (not blocked)
AttemptCounter notBlocked = new AttemptCounter();
ac.setInt(notBlocked, 2);
attemptsCache.put("safe", notBlocked);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertEquals(2, result.size(), "Should return exactly 2 blocked users");
assertTrue(result.contains("blocked1"), "Should contain blocked1");
assertTrue(result.contains("blocked2"), "Should contain blocked2");
assertFalse(result.contains("safe"), "Should not contain safe user");
}
@Test
@DisplayName("getAllBlockedUsers(): returns empty list when no users are blocked")
void getAllBlockedUsers_shouldReturnEmptyWhenNoUsersBlocked() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
setPrivate(svc, "MAX_ATTEMPT", 3);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
AttemptCounter notBlocked = new AttemptCounter();
ac.setInt(notBlocked, 1);
attemptsCache.put("user1", notBlocked);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertTrue(result.isEmpty(), "Should return empty list when no users exceed MAX_ATTEMPT");
}
}
+5 -47
View File
@@ -338,43 +338,7 @@ RUN mkdir -p /magick-export/usr/bin \
cp -a /usr/local/etc/ImageMagick-7 /magick-export/usr/local/etc/
# Stage 4: Build FFmpeg from source
FROM ubuntu:noble AS ffmpeg-build
ARG TARGETPLATFORM
ARG FFMPEG_VERSION=8.1
COPY ffmpeg-${FFMPEG_VERSION}.tar.gz.asc /tmp/ffmpeg-sig/
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/tmp/ffmpeg-build,id=ffmpeg-build-${TARGETPLATFORM:-local} \
apt-get update && apt-get install -y --no-install-recommends \
build-essential curl ca-certificates pkg-config nasm \
libx264-dev libvpx-dev gnupg && \
rm -rf /var/lib/apt/lists/* && \
cd /tmp/ffmpeg-build && \
rm -rf ffmpeg-* && \
# Download tarball and verify against locally-pinned GPG signature
curl -fsSL --max-time 300 --retry 3 --retry-delay 5 \
-o "ffmpeg-${FFMPEG_VERSION}.tar.gz" \
"https://www.ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys FCF986EA15E6E293A5644F10B4322F04D67658D8 && \
gpg --verify /tmp/ffmpeg-sig/ffmpeg-${FFMPEG_VERSION}.tar.gz.asc "ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
tar xzf "ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
cd "ffmpeg-${FFMPEG_VERSION}" && \
./configure \
--prefix=/usr/local \
--enable-gpl \
--enable-libx264 \
--enable-libvpx \
--disable-doc \
--disable-debug \
--disable-static \
--enable-shared && \
make -j"$(nproc)" && \
make install
# Stage 5: Build Python venv
# Stage 4: Build Python venv
FROM ubuntu:noble AS python-venv-build
ARG TARGETPLATFORM
ARG UNOSERVER_VERSION=3.6
@@ -421,8 +385,8 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
apt-get install -y --no-install-recommends \
# Core tools
ca-certificates tzdata tini bash fontconfig curl \
poppler-utils fontforge \
unpaper pngquant \
ffmpeg poppler-utils fontforge \
gosu unpaper pngquant \
# Fonts: full coverage for standard + fat variants
fonts-dejavu \
fonts-liberation2 \
@@ -632,13 +596,6 @@ COPY --link --from=pdf-tools-build /usr/local/bin/qpdf /usr/bin/qpdf
COPY --link --from=pdf-tools-build /magick-export/ /
COPY --link --from=gs-build /usr/local/bin/gs /usr/local/bin/gs
COPY --link --from=gs-build /usr/local/share/ghostscript /usr/local/share/ghostscript
COPY --link --from=ffmpeg-build /usr/local/bin/ff* /usr/local/bin/
COPY --link --from=ffmpeg-build /usr/local/lib/libav*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/local/lib/libsw*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/local/lib/libpostproc*.so* /usr/local/lib/
# ffmpeg runtime deps (libx264, libvpx) — copied from build stage instead of apt
COPY --link --from=ffmpeg-build /usr/lib/*/libx264*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/lib/*/libvpx*.so* /usr/local/lib/
# Python venv pre-built (no pip install at runtime, no build tools needed)
COPY --link --from=python-venv-build /opt/venv /opt/venv
@@ -665,7 +622,8 @@ RUN set -eux; \
-d /home/stirlingpdfuser -s /bin/bash stirlingpdfuser 2>/dev/null \
|| useradd -m -g stirlingpdfgroup \
-d /home/stirlingpdfuser -s /bin/bash stirlingpdfuser; \
fi
fi; \
ln -sf /usr/sbin/gosu /usr/local/bin/su-exec
# Application directories
RUN set -eux; \
-11
View File
@@ -1,11 +0,0 @@
-----BEGIN PGP SIGNATURE-----
iQFMBAABCgA2FiEE/PmG6hXm4pOlZE8QtDIvBNZ2WNgFAmm4UOEYHGZmbXBlZy1k
ZXZlbEBmZm1wZWcub3JnAAoJELQyLwTWdljY6kAH/3UjGSnwGV8As/SgtXEYgSz8
66GQlrLDiF4QVVqmkSN5WQTcne/x7s7AJ+z2YkO17zg4DQYcJrPdwEsT1EiUnF/N
+kZW4E7umBZgcVYc9Kv7cj6riqDnedN+3QjuH4KhT82AZ8sHppTPdF3EsGV5YYhf
J+nT4rAHiHX84hcS6X9UL8qptrWRAQaYU+P0hWZ57P1RfIlFScylKYZ68Sf5EeB7
j0KIpu+FEzcDah1bemgUhHX0lM1VhjsDicv+swqAFT43Gc3YRcx42V5rCpP3UXD7
rZ1t5T0HojEU4pmaOdRMqLB3W4B8YptMPLqyQHmI4fBPxdStVeJ05ZhlDXwc1bA=
=4Mgh
-----END PGP SIGNATURE-----
+2 -2
View File
@@ -1,8 +1,8 @@
# Stirling-PDF - Full version (embedded frontend)
# Uses pre-built base image for fast builds
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
FROM gradle:9.3.1-jdk25 AS app-build
+2 -2
View File
@@ -2,8 +2,8 @@
# Extra fonts for air-gapped environments
# Uses pre-built base image for fast builds
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
FROM gradle:9.3.1-jdk25 AS app-build
+1 -1
View File
@@ -93,7 +93,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
bash \
curl \
shadow \
util-linux && \
su-exec && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /tmp/stirling-pdf/heap_dumps && \
mkdir -p /usr/share/fonts/opentype/noto && \
# User permissions
-78
View File
@@ -45,84 +45,6 @@ export function f2() { /* ... */ } // Custom desktop implementation
Building with this pattern minimises the duplicated code in the system and greatly reduces the chances that changing the core app will break the desktop app.
### Naming extension modules
Extension modules and the functions/hooks they export should be named after **what they do**, not **which build overrides them**.
Core code must never reference build targets (desktop, saas, etc.) by name — it should simply call a generic extension point and remain unaware of which layer is providing the implementation.
```ts
// ✅ CORRECT - named after the behaviour, not the build
// core/useFrontendVersionInfo.ts
export function useFrontendVersionInfo() { /* stub */ }
// desktop/useFrontendVersionInfo.ts
export function useFrontendVersionInfo() { /* real Tauri implementation */ }
```
```ts
// ❌ WRONG - core code reveals knowledge of the desktop layer
// core/useDesktopVersionInfo.ts
export function useDesktopVersionInfo() { /* stub */ }
```
Similarly, core code should never contain conditionals that check which build is active (e.g. `if (isDesktop)`).
If behaviour needs to vary, that variation belongs in an extension module - the core simply calls it.
The same principle applies in reverse: code inside `desktop/` is guaranteed to be running in the Tauri environment, so `isTauri()` checks are never needed there either.
If you find yourself writing `if (isDesktop())` or `if (isTauri())` anywhere, that is a sign the extension point has not been modelled correctly - the build system is already doing that separation for you.
### List extensions
When a build needs to _add_ behaviour rather than _replace_ it, the extension module can return a list of items and let core manage the rendering.
Core defines the function to return an empty list; the extension build overrides it to return a populated one.
```ts
// core/toolbarExtensions.ts
export interface ToolbarButton {
label: string;
onClick: () => void;
}
export function getToolbarButtons(): ToolbarButton[] {
return [];
}
```
```ts
// desktop/toolbarExtensions.ts
import { type ToolbarButton } from '@core/toolbarExtensions';
export { type ToolbarButton };
export function getToolbarButtons(): ToolbarButton[] {
return [
{ label: 'Open folder', onClick: () => { /* ... */ } },
];
}
```
```tsx
// core/Toolbar.tsx
import { getToolbarButtons } from '@app/toolbarExtensions';
export function Toolbar() {
return (
<div>
<button onClick={() => { /* ... */ }}>Download</button>
<button onClick={() => { /* ... */ }}>Print</button>
{getToolbarButtons().map((button) => (
<button key={button.label} onClick={button.onClick}>
{button.label}
</button>
))}
</div>
);
}
```
This pattern works well for things like menu items or toolbar actions - anything where a build contributes additional entries to a well-defined set.
### Import aliases
In general, all imports for app code should come via `@app` because it allows for other builds of the app to override behaviour if necessary.
The only time that it is beneficial to import via a specific folder (e.g. `@core`) is when you want to reduce duplication **in the file you are overriding**. For example:
+5 -30
View File
@@ -13,11 +13,6 @@ const nodeGlobs = [
'*.config.{js,ts,mjs}',
];
const baseRestrictedImportPatterns = [
{ regex: '^\\.', message: "Use @app/* imports instead of relative imports." },
{ regex: '^src/', message: "Use @app/* imports instead of absolute src/ imports." },
];
export default defineConfig(
{
// Everything that contains 3rd party code that we don't want to lint
@@ -35,7 +30,10 @@ export default defineConfig(
'no-restricted-imports': [
'error',
{
patterns: baseRestrictedImportPatterns,
patterns: [
".*", // Disallow any relative imports (they should be '@app/x/y/z' or similar)
"src/*", // Disallow any absolute imports (they should be '@app/x/y/z' or similar)
],
},
],
'@typescript-eslint/no-empty-object-type': [
@@ -61,32 +59,9 @@ export default defineConfig(
],
},
},
// Desktop-only packages must not be imported from core or proprietary code.
// Use the stub/shadow pattern instead: define a stub in src/core/ and override in src/desktop/.
{
files: srcGlobs,
ignores: ['src/desktop/**'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
...baseRestrictedImportPatterns,
{
regex: '^@tauri-apps/',
message: "Tauri APIs are desktop-only. Review frontend/DeveloperGuide.md for structure advice.",
},
],
},
],
},
},
// Folders that have been cleaned up and are now conformant - stricter rules enforced here
{
files: [
'src/proprietary/**/*.{js,mjs,jsx,ts,tsx}',
'src/saas/**/*.{js,mjs,jsx,ts,tsx}',
],
files: ['src/saas/**/*.{js,mjs,jsx,ts,tsx}'],
languageOptions: {
parserOptions: {
project: true,
+16 -25
View File
@@ -4170,8 +4170,8 @@ tags = "javascript,code,script,show javascript,show JS,find javascript,detect ja
title = "Show Javascript"
[home.sign]
desc = "Adds signature to PDF by drawing, text or image"
tags = "signature,autograph,e-sign,electronic signature,digital signature,sign document,approval,signoff,authorize,endorse,ink signature,handwriting"
desc = "Sign PDFs with a wet signature, digital certificate, or both"
tags = "signature,autograph,e-sign,electronic signature,digital signature,sign document,approval,signoff,authorize,endorse,ink signature,handwriting,certificate sign,cert sign,wet sign"
title = "Sign"
[home.timestampPdf]
@@ -4856,7 +4856,7 @@ enableSepiaFilter = "Enable Sepia Filter"
firstPage = "First Page"
lastPage = "Last Page"
nextPage = "Next Page"
onlyPdfSupported = "This file format is not supported for preview."
onlyPdfSupported = "The viewer only supports PDF files. This file appears to be a different format."
previousPage = "Previous Page"
singlePageView = "Single Page View"
unknownFile = "Unknown file"
@@ -4864,21 +4864,6 @@ zoomIn = "Zoom In"
zoomOut = "Zoom Out"
resetZoom = "Reset zoom"
[viewer.nonPdf]
fileTypeBadge = "{{type}} File"
convertToPdf = "Convert to PDF"
loading = "Loading..."
emptyFile = "Empty file"
csvStats = "{{rows}} rows · {{columns}} columns · {{size}}"
sortedBy = "Sorted by: {{column}}"
columnDefault = "Column {{index}}"
htmlPreviewWarning = "HTML preview — external resources may not load · {{size}}"
htmlPreview = "HTML preview"
invalidJson = "Invalid JSON — showing raw content"
textStats = "{{lines}} lines · {{size}}"
lineNumbers = "Line numbers"
renderMarkdown = "Render markdown"
[rightRail]
closeSelected = "Close Selected Files"
selectAll = "Select All"
@@ -4896,7 +4881,6 @@ toggleAttachments = "Toggle Attachments"
toggleTheme = "Toggle Theme"
language = "Language"
toggleAnnotations = "Toggle Annotations Visibility"
toggleLayers = "Toggle Layers"
search = "Search PDF"
panMode = "Pan Mode"
applyRedactionsFirst = "Apply redactions first"
@@ -6945,11 +6929,24 @@ saved = "Select a saved signature above, then click anywhere on the PDF to place
text = "After entering your name above, click anywhere on the PDF to place your signature."
title = "How to add signature"
[sign.editor]
back = "Back to file selection"
hint = "Open the editor to place wet signatures, apply a digital certificate, or both."
noSignatures = "Place at least one signature on the PDF first."
open = "Open Sign Editor"
openStep = "Open Sign Editor"
signingFailed = "Signing failed. Please try again."
signDocument = "Sign Document"
title = "Sign Editor"
[sign.mode]
both = "Both"
cert = "Cert Sign"
move = "Move Signature"
pause = "Pause placement"
place = "Place Signature"
resume = "Resume placement"
wet = "Wet Sign"
[sign.results]
title = "Signature Results"
@@ -7994,7 +7991,6 @@ activeSession = "Active session"
addMembers = "Add Members"
admin = "Admin"
confirmDelete = "Are you sure you want to delete this user? This action cannot be undone."
confirmUnlock = "Are you sure you want to unlock this user account?"
deleteUser = "Delete User"
deleteUserError = "Failed to delete user"
deleteUserSuccess = "User deleted successfully"
@@ -8003,8 +7999,6 @@ disable = "Disable"
disabled = "Disabled"
editRole = "Edit Role"
enable = "Enable"
locked = "locked"
lockedBadge = "Locked"
loading = "Loading people..."
loginRequired = "Enable login mode first"
member = "Member"
@@ -8014,9 +8008,6 @@ searchMembers = "Search members..."
status = "Status"
team = "Team"
title = "People"
unlockAccount = "Unlock Account"
unlockUserError = "Failed to unlock user account"
unlockUserSuccess = "User account unlocked successfully"
user = "User"
[workspace.people.actions]
File diff suppressed because it is too large Load Diff
@@ -5,7 +5,6 @@ import {
import { Dropzone } from '@mantine/dropzone';
import { useFileSelection, useFileState, useFileManagement, useFileActions, useFileContext } from '@app/contexts/FileContext';
import { useNavigationActions } from '@app/contexts/NavigationContext';
import { useViewer } from '@app/contexts/ViewerContext';
import { zipFileService } from '@app/services/zipFileService';
import { detectFileExtension } from '@app/utils/fileUtils';
import FileEditorThumbnail from '@app/components/fileEditor/FileEditorThumbnail';
@@ -52,9 +51,6 @@ const FileEditor = ({
// Get navigation actions
const { actions: navActions } = useNavigationActions();
// Get viewer context for setting active file index
const { setActiveFileIndex } = useViewer();
// Get file selection context
const { setSelectedFiles } = useFileSelection();
@@ -349,14 +345,13 @@ const FileEditor = ({
}, [activeStirlingFileStubs, selectors, fileActions, removeFiles]);
const handleViewFile = useCallback((fileId: FileId) => {
const index = activeStirlingFileStubs.findIndex(r => r.id === fileId);
if (index !== -1) {
// Set the file as selected in context, sync the viewer index, and switch to viewer
const record = activeStirlingFileStubs.find(r => r.id === fileId);
if (record) {
// Set the file as selected in context and switch to viewer for preview
setSelectedFiles([fileId]);
setActiveFileIndex(index);
navActions.setWorkbench('viewer');
}
}, [activeStirlingFileStubs, setSelectedFiles, setActiveFileIndex, navActions.setWorkbench]);
}, [activeStirlingFileStubs, setSelectedFiles, navActions.setWorkbench]);
const handleLoadFromStorage = useCallback(async (selectedFiles: File[]) => {
if (selectedFiles.length === 0) return;
@@ -19,8 +19,6 @@ import AllToolsNavButton from '@app/components/shared/AllToolsNavButton';
import ActiveToolButton from "@app/components/shared/quickAccessBar/ActiveToolButton";
import AppConfigModal from '@app/components/shared/AppConfigModal';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useGroupSigningEnabled } from '@app/hooks/useGroupSigningEnabled';
import { useSharingEnabled } from '@app/hooks/useSharingEnabled';
import { useLicenseAlert } from "@app/hooks/useLicenseAlert";
import { requestStartTour } from '@app/constants/events';
import QuickAccessButton from '@app/components/shared/quickAccessBar/QuickAccessButton';
@@ -79,8 +77,9 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
const accessButtonRef = useRef<HTMLDivElement>(null);
const accessPopoverRef = useRef<HTMLDivElement>(null);
const [accessPopoverPosition, setAccessPopoverPosition] = useState({ top: 160, left: 84 });
const { sharingEnabled, shareLinksEnabled } = useSharingEnabled();
const groupSigningEnabled = useGroupSigningEnabled();
const sharingEnabled = config?.storageSharingEnabled === true;
const shareLinksEnabled = config?.storageShareLinksEnabled === true;
const groupSigningEnabled = config?.storageGroupSigningEnabled === true;
const isSignWorkbenchActive =
currentWorkbench === SIGN_REQUEST_WORKBENCH_TYPE ||
currentWorkbench === SESSION_DETAIL_WORKBENCH_TYPE;
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react";
import {
Paper,
Stack,
@@ -22,7 +22,8 @@ import type { ToolPanelMode } from "@app/constants/toolPanel";
import LocalIcon from "@app/components/shared/LocalIcon";
import { updateService, UpdateSummary } from "@app/services/updateService";
import UpdateModal from "@app/components/shared/UpdateModal";
import { useFrontendVersionInfo } from "@app/hooks/useFrontendVersionInfo";
import { getVersion } from "@tauri-apps/api/app";
import { isTauri } from "@tauri-apps/api/core";
const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;
const BANNER_DISMISSED_KEY = "stirlingpdf_features_banner_dismissed";
@@ -45,8 +46,10 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
const [updateSummary, setUpdateSummary] = useState<UpdateSummary | null>(null);
const [updateModalOpened, setUpdateModalOpened] = useState(false);
const [checkingUpdate, setCheckingUpdate] = useState(false);
const { appVersion, mismatchVersion } = useFrontendVersionInfo(config?.appVersion);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading..."); // null = loading, shown only when appVersion !== undefined
const [mismatchVersion, setMismatchVersion] = useState(false);
const isTauriApp = useMemo(() => isTauri(), []);
const [appVersion, setAppVersion] = useState<string | null>(null);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading...");
// Sync local state with preference changes
useEffect(() => {
@@ -88,6 +91,52 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
setCheckingUpdate(false);
};
useEffect(() => {
if (!isTauriApp) {
setMismatchVersion(false);
return;
}
let cancelled = false;
const fetchFrontendVersion = async () => {
try {
const frontendVersion = await getVersion();
if (!cancelled) {
setAppVersion(frontendVersion);
}
} catch (error) {
console.error("[GeneralSection] Failed to fetch frontend version:", error);
}
};
fetchFrontendVersion();
return () => {
cancelled = true;
};
}, [isTauriApp]);
useEffect(() => {
if (!isTauriApp) {
return;
}
if (!appVersion || !config?.appVersion) {
setMismatchVersion(false);
return;
}
if (appVersion !== config.appVersion) {
console.warn("[GeneralSection] Mismatch between Tauri version and AppConfig version:", {
backendVersion: config.appVersion,
frontendVersion: appVersion,
});
setMismatchVersion(true);
} else {
setMismatchVersion(false);
}
}, [isTauriApp, appVersion, config?.appVersion]);
// Check if login is disabled
const loginDisabled = !config?.enableLogin;
@@ -190,7 +239,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
)}
</Group>
</div>
{appVersion !== undefined && (
{isTauriApp && (
<Group justify="space-between" align="center">
<div>
<Text size="sm" c="dimmed">
@@ -335,7 +335,9 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
formData.append('workflowMetadata', workflowMetadata);
}
await apiClient.post('/api/v1/security/cert-sign/sessions', formData);
await apiClient.post('/api/v1/security/cert-sign/sessions', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
alert({
alertType: 'success',
@@ -491,7 +493,9 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
// Action handlers
const handleSign = async (sessionId: string, certificateData: FormData) => {
await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`, certificateData);
await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`, certificateData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
alert({
alertType: 'success',
title: t('success'),
@@ -673,11 +677,11 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
className="quick-access-popout__quick-sign-btn"
onClick={() => {
onClose();
handleToolSelect('certSign');
handleToolSelect('sign');
}}
>
<LocalIcon icon="workspace-premium-rounded" width="1rem" height="1rem" />
{t('quickAccess.certSign', 'Certificate Sign')}
<LocalIcon icon="signature-rounded" width="1rem" height="1rem" />
{t('quickAccess.sign', 'Sign')}
</button>
</div>
</div>
@@ -1,9 +1,10 @@
import { Modal, Stack, Group, Button, Text, Collapse, TextInput, Loader } from '@mantine/core';
import { Modal, Stack, Group, Button, Text, Collapse, TextInput, Divider, Loader } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useRef } from 'react';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import { CertificateSelector, CertificateType, UploadFormat } from '@app/components/tools/certSign/CertificateSelector';
import SignatureSettingsInput, { SignatureSettings } from '@app/components/tools/certSign/SignatureSettingsInput';
import apiClient from '@app/services/apiClient';
export interface CertificateSubmitData {
@@ -14,6 +15,11 @@ export interface CertificateSubmitData {
certFile: File | null;
jksFile: File | null;
password: string;
// Appearance (only present when showAppearanceSettings=true)
showSignature?: boolean;
pageNumber?: number;
showLogo?: boolean;
includeSummaryPage?: boolean;
}
type CertValidationState =
@@ -30,6 +36,8 @@ interface CertificateConfigModalProps {
disabled?: boolean;
defaultReason?: string;
defaultLocation?: string;
/** When true, renders SignatureSettingsInput so the user can configure cert appearance */
showAppearanceSettings?: boolean;
/** Share token for external participants. When present, the participant validation endpoint is used. */
participantToken?: string;
}
@@ -42,6 +50,7 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({
disabled = false,
defaultReason = '',
defaultLocation = '',
showAppearanceSettings = false,
participantToken,
}) => {
const { t } = useTranslation();
@@ -119,6 +128,11 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({
const [reason, setReason] = useState(defaultReason);
const [location, setLocation] = useState(defaultLocation);
// Appearance settings (only used when showAppearanceSettings=true)
const [appearance, setAppearance] = useState<SignatureSettings>({
showSignature: false,
});
const isUploadValid = () => {
if (certType !== 'UPLOAD') return true;
switch (uploadFormat) {
@@ -142,11 +156,22 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({
setSigning(true);
try {
await onSign(
{ certType, uploadFormat, p12File, privateKeyFile, certFile, jksFile, password },
reason,
location
);
const certData: CertificateSubmitData = {
certType,
uploadFormat,
p12File,
privateKeyFile,
certFile,
jksFile,
password,
...(showAppearanceSettings && {
showSignature: appearance.showSignature,
pageNumber: appearance.pageNumber,
showLogo: appearance.showLogo,
includeSummaryPage: appearance.includeSummaryPage,
}),
};
await onSign(certData, reason, location);
} catch (error) {
console.error('Failed to sign document:', error);
} finally {
@@ -189,6 +214,19 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({
disabled={disabled || signing}
/>
{/* Signature Appearance Settings (combined sign tool) */}
{showAppearanceSettings && (
<>
<Divider />
<SignatureSettingsInput
value={appearance}
onChange={setAppearance}
disabled={disabled || signing}
/>
<Divider />
</>
)}
{/* Certificate validation status */}
{certValidation.status === 'validating' && (
<Group gap="xs">
@@ -0,0 +1,332 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Paper, Group, Button, Text, SegmentedControl, Divider, CloseButton } from '@mantine/core';
import ZoomInIcon from '@mui/icons-material/ZoomIn';
import ZoomOutIcon from '@mui/icons-material/ZoomOut';
import ZoomOutMapIcon from '@mui/icons-material/ZoomOutMap';
import CheckIcon from '@mui/icons-material/Check';
import { LocalIcon } from '@app/components/shared/LocalIcon';
import { Z_INDEX_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
import { LocalEmbedPDFWithAnnotations, AnnotationAPI, SignaturePreview } from '@app/components/viewer/LocalEmbedPDFWithAnnotations';
import SignControlsStrip from '@app/components/tools/certSign/SignControlsStrip';
import { CertificateConfigModal } from '@app/components/tools/certSign/modals/CertificateConfigModal';
import type { CertificateSubmitData } from '@app/components/tools/certSign/modals/CertificateConfigModal';
import { SignParameters } from '@app/hooks/tools/sign/useSignParameters';
import { useCombinedSignOperation } from '@app/hooks/tools/combinedSign/useCombinedSignOperation';
import { alert } from '@app/components/toast';
import { useIsPhone } from '@app/hooks/useIsMobile';
type SignMode = 'wet' | 'both' | 'cert';
export interface CombinedSignEditorData {
file: File;
onComplete: (blob: Blob, filename: string) => void;
onBack: () => void;
}
const DEFAULT_SIGNATURE_CONFIG: SignParameters = {
signatureType: 'canvas',
signerName: '',
fontFamily: 'Helvetica',
fontSize: 16,
textColor: '#000000',
};
/**
* Full-screen signing editor, mirroring the SignRequestWorkbenchView layout.
*
* Registered as a custom workbench view by CombinedSign.tsx. Receives its
* runtime state through the `data` prop (set via setCustomWorkbenchViewData).
*
* Modes:
* wet — visual/wet signatures only, submitted to add-signature endpoint
* cert — digital certificate only, submitted to cert-sign endpoint
* both — wet signatures + digital cert, submitted to cert-sign with wetSignaturesData
*/
const CombinedSignEditor = ({ data }: { data: CombinedSignEditorData | null }) => {
const { t } = useTranslation();
const isPhone = useIsPhone();
const { submitCertSign, submitWetOnly, loading } = useCombinedSignOperation();
const annotationApiRef = useRef<AnnotationAPI | null>(null);
const [signMode, setSignMode] = useState<SignMode>('both');
const [signatureConfig, setSignatureConfig] = useState<SignParameters>(DEFAULT_SIGNATURE_CONFIG);
const [placementMode, setPlacementMode] = useState(true);
const [previewCount, setPreviewCount] = useState(0);
const [hasSelectedAnnotation, setHasSelectedAnnotation] = useState(false);
const [certModalOpen, setCertModalOpen] = useState(false);
const showWetControls = signMode === 'wet' || signMode === 'both';
// Poll for selected annotation state (enables delete button)
useEffect(() => {
if (!showWetControls) {
setHasSelectedAnnotation(false);
return;
}
const check = () => {
const has = (annotationApiRef.current as any)?.getHasSelectedAnnotation?.();
setHasSelectedAnnotation(Boolean(has));
};
check();
const id = setInterval(check, 350);
return () => clearInterval(id);
}, [showWetControls]);
// Clear placed signatures when switching to cert-only mode
useEffect(() => {
if (signMode === 'cert') {
annotationApiRef.current?.clearPreviews();
setPreviewCount(0);
}
}, [signMode]);
const handleComplete = useCallback(() => {
if (!data) return;
if (signMode === 'wet') {
const previews = annotationApiRef.current?.getSignaturePreviews() ?? [];
if (previews.length === 0) {
alert({
alertType: 'error',
title: t('common.error'),
body: t('sign.editor.noSignatures', 'Place at least one signature on the PDF first.'),
});
return;
}
void handleWetSign(previews);
} else {
// cert or both — open the certificate modal
if (signMode === 'both' && previewCount === 0) {
alert({
alertType: 'error',
title: t('common.error'),
body: t('sign.editor.noSignatures', 'Place at least one signature on the PDF first.'),
});
return;
}
setCertModalOpen(true);
}
}, [data, signMode, previewCount, t]);
const handleWetSign = async (previews: SignaturePreview[]) => {
if (!data) return;
try {
const result = await submitWetOnly(data.file, previews);
data.onComplete(result.blob, result.filename);
} catch {
alert({
alertType: 'error',
title: t('common.error'),
body: t('sign.editor.signingFailed', 'Signing failed. Please try again.'),
});
}
};
const handleCertSign = async (
certData: CertificateSubmitData,
reason?: string,
location?: string,
) => {
if (!data) return;
const formData = new FormData();
formData.append('fileInput', data.file);
if (certData.certType === 'UPLOAD') {
formData.append('certType', certData.uploadFormat);
if (certData.p12File) formData.append('p12File', certData.p12File);
if (certData.privateKeyFile) formData.append('privateKeyFile', certData.privateKeyFile);
if (certData.certFile) formData.append('certFile', certData.certFile);
if (certData.jksFile) formData.append('jksFile', certData.jksFile);
if (certData.password) formData.append('password', certData.password);
} else {
formData.append('certType', certData.certType);
}
// Appearance settings (from extended CertificateConfigModal)
if (certData.showSignature !== undefined) {
formData.append('showSignature', certData.showSignature.toString());
}
if (certData.showSignature) {
if (certData.pageNumber !== undefined) formData.append('pageNumber', certData.pageNumber.toString());
if (certData.showLogo !== undefined) formData.append('showLogo', certData.showLogo.toString());
}
if (reason?.trim()) formData.append('reason', reason);
if (location?.trim()) formData.append('location', location);
// Wet signatures (both mode only)
if (signMode === 'both') {
const previews = annotationApiRef.current?.getSignaturePreviews() ?? [];
if (previews.length > 0) {
const wetSignaturesJson = previews.map((p) => ({
type: p.signatureType,
data: p.signatureData,
page: p.pageIndex,
x: p.x,
y: p.y,
width: p.width,
height: p.height,
}));
formData.append('wetSignaturesData', JSON.stringify(wetSignaturesJson));
}
}
try {
const result = await submitCertSign(data.file, formData);
setCertModalOpen(false);
data.onComplete(result.blob, result.filename);
} catch {
alert({
alertType: 'error',
title: t('common.error'),
body: t('sign.editor.signingFailed', 'Signing failed. Please try again.'),
});
}
};
const handleDeleteSelected = useCallback(() => {
(annotationApiRef.current as any)?.deleteSelectedAnnotation?.();
}, []);
if (!data) return null;
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* ── Top bar ─────────────────────────────────────────────────────── */}
<Paper
p="sm"
shadow="sm"
style={{ flexShrink: 0, zIndex: Z_INDEX_FULLSCREEN_SURFACE, position: 'relative' }}
>
<Group justify="space-between" style={{ flexWrap: isPhone ? 'wrap' : 'nowrap' }}>
<Group gap="md">
<LocalIcon icon="signature-rounded" width="1.5rem" height="1.5rem" />
<Text
size="sm"
fw={600}
truncate={isPhone ? 'end' : undefined}
style={{ maxWidth: isPhone ? '140px' : undefined }}
>
{data.file.name}
</Text>
</Group>
<Group gap="xs" style={{ width: isPhone ? '100%' : undefined }} justify={isPhone ? 'flex-end' : undefined}>
{/* Sign mode selector */}
<SegmentedControl
value={signMode}
onChange={(v) => setSignMode(v as SignMode)}
size="xs"
radius="xl"
data={[
{ value: 'wet', label: t('sign.mode.wet', 'Wet Sign') },
{ value: 'both', label: t('sign.mode.both', 'Both') },
{ value: 'cert', label: t('sign.mode.cert', 'Cert Sign') },
]}
/>
{!isPhone && (
<>
<Divider orientation="vertical" />
<Button.Group>
<Button
variant="subtle"
size="sm"
onClick={() => annotationApiRef.current?.zoomOut()}
title={t('viewer.zoomOut', 'Zoom out')}
>
<ZoomOutIcon fontSize="small" />
</Button>
<Button
variant="subtle"
size="sm"
onClick={() => annotationApiRef.current?.resetZoom()}
title={t('viewer.resetZoom', 'Reset zoom')}
>
<ZoomOutMapIcon fontSize="small" />
</Button>
<Button
variant="subtle"
size="sm"
onClick={() => annotationApiRef.current?.zoomIn()}
title={t('viewer.zoomIn', 'Zoom in')}
>
<ZoomInIcon fontSize="small" />
</Button>
</Button.Group>
</>
)}
{/* Cert-only mode: show sign button in the top bar (no strip below) */}
{signMode === 'cert' && (
<>
<Divider orientation="vertical" />
<Button
size="sm"
leftSection={<CheckIcon fontSize="small" />}
onClick={handleComplete}
loading={loading}
>
{t('sign.editor.signDocument', 'Sign Document')}
</Button>
</>
)}
<Divider orientation="vertical" />
<CloseButton
size="md"
onClick={data.onBack}
title={t('sign.editor.back', 'Back to file selection')}
/>
</Group>
</Group>
</Paper>
{/* ── Wet signature controls strip (wet / both modes) ─────────────── */}
{showWetControls && (
<SignControlsStrip
visible
placementMode={placementMode}
onPlacementModeChange={setPlacementMode}
onSignatureSelected={setSignatureConfig}
onComplete={handleComplete}
canComplete={previewCount > 0}
signatureConfig={signatureConfig}
hasSelectedAnnotation={hasSelectedAnnotation}
onDeleteSelected={handleDeleteSelected}
/>
)}
{/* ── PDF viewer ──────────────────────────────────────────────────── */}
<div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
<LocalEmbedPDFWithAnnotations
ref={annotationApiRef}
file={data.file}
onAnnotationChange={() => {}}
placementMode={showWetControls ? placementMode : false}
signatureData={showWetControls ? signatureConfig?.signatureData : undefined}
signatureType={showWetControls ? signatureConfig?.signatureType : undefined}
onPlaceSignature={() => {}}
onPreviewCountChange={setPreviewCount}
/>
</div>
{/* ── Certificate modal (cert / both modes) ───────────────────────── */}
{(signMode === 'cert' || signMode === 'both') && (
<CertificateConfigModal
opened={certModalOpen}
onClose={() => setCertModalOpen(false)}
onSign={handleCertSign}
signatureCount={previewCount}
disabled={loading}
showAppearanceSettings
/>
)}
</div>
);
};
export default CombinedSignEditor;
@@ -1,4 +1,63 @@
/* Attachment Sidebar - Attachment-specific styles (base styles in SidebarBase.css) */
/* Attachment Sidebar - Modern styling to match AllTools section */
.attachment-sidebar {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.attachment-sidebar__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.attachment-sidebar__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.attachment-sidebar__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section */
.attachment-sidebar__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.attachment-sidebar__content {
padding-top: 0.5rem !important;
}
.attachment-sidebar__empty-state,
.attachment-sidebar__error {
padding: 2rem 1rem;
text-align: center;
}
.attachment-sidebar__loading {
padding: 2rem 1rem !important;
}
/* Attachment List */
.attachment-list {
@@ -6,7 +6,6 @@ import { PdfAttachmentObject } from '@embedpdf/models';
import AttachmentIcon from '@mui/icons-material/AttachmentRounded';
import DownloadIcon from '@mui/icons-material/DownloadRounded';
import { useTranslation } from 'react-i18next';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/AttachmentSidebar.css';
interface AttachmentSidebarProps {
@@ -285,7 +284,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
return (
<Box
className="sidebar-base attachment-sidebar"
className="attachment-sidebar"
style={{
position: 'fixed',
right: `${(thumbnailVisible ? 15 : 0) + (bookmarkVisible ? 15 : 0)}rem`,
@@ -295,9 +294,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
zIndex: 998,
}}
>
<div className="sidebar-base__header attachment-sidebar__header">
<div className="sidebar-base__header-title attachment-sidebar__header-title">
<span className="sidebar-base__header-icon attachment-sidebar__header-icon">
<div className="attachment-sidebar__header">
<div className="attachment-sidebar__header-title">
<span className="attachment-sidebar__header-icon">
<AttachmentIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -306,7 +305,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</div>
</div>
<Box px="sm" pb="sm" className="sidebar-base__search attachment-sidebar__search">
<Box px="sm" pb="sm" className="attachment-sidebar__search">
<TextInput
value={searchTerm}
placeholder={t('viewer.attachments.searchPlaceholder', 'Search attachments')}
@@ -317,9 +316,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content attachment-sidebar__content">
<Box p="sm" className="attachment-sidebar__content">
{!attachmentSupport && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noSupport', 'Attachment support is unavailable for this viewer.')}
</Text>
@@ -327,7 +326,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && showNoDocument && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noDocument', 'Open a PDF to view its attachments.')}
</Text>
@@ -335,7 +334,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="sidebar-base__error">
<Stack gap="xs" align="center" className="attachment-sidebar__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -346,7 +345,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Stack gap="md" align="center" c="dimmed" py="xl" className="attachment-sidebar__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
{t('viewer.attachments.loading', 'Loading attachments...')}
@@ -355,7 +354,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showEmptyState && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.empty', 'No attachments in this document')}
</Text>
@@ -369,7 +368,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showSearchEmpty && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noMatch', 'No attachments match your search')}
</Text>
@@ -1,4 +1,63 @@
/* Bookmark Sidebar - Bookmark-specific styles (base styles in SidebarBase.css) */
/* Bookmark Sidebar - Modern styling to match AllTools section */
.bookmark-sidebar {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.bookmark-sidebar__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.bookmark-sidebar__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.bookmark-sidebar__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section */
.bookmark-sidebar__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.bookmark-sidebar__content {
padding-top: 0.5rem !important;
}
.bookmark-sidebar__empty-state,
.bookmark-sidebar__error {
padding: 2rem 1rem;
text-align: center;
}
.bookmark-sidebar__loading {
padding: 2rem 1rem !important;
}
/* Bookmark List */
.bookmark-list {
@@ -134,3 +193,4 @@
animation: none;
}
}
@@ -4,7 +4,6 @@ import LocalIcon from '@app/components/shared/LocalIcon';
import { useViewer } from '@app/contexts/ViewerContext';
import { PdfBookmarkObject, PdfActionType } from '@embedpdf/models';
import BookmarksIcon from '@mui/icons-material/BookmarksRounded';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/BookmarkSidebar.css';
interface BookmarkSidebarProps {
@@ -430,7 +429,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
return (
<Box
className="sidebar-base bookmark-sidebar"
className="bookmark-sidebar"
style={{
position: 'fixed',
right: thumbnailVisible ? SIDEBAR_WIDTH : 0,
@@ -440,9 +439,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
zIndex: 998,
}}
>
<div className="sidebar-base__header bookmark-sidebar__header">
<div className="sidebar-base__header-title bookmark-sidebar__header-title">
<span className="sidebar-base__header-icon bookmark-sidebar__header-icon">
<div className="bookmark-sidebar__header">
<div className="bookmark-sidebar__header-title">
<span className="bookmark-sidebar__header-icon">
<BookmarksIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -476,7 +475,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
</div>
<Box px="sm" pb="sm" className="sidebar-base__search bookmark-sidebar__search">
<Box px="sm" pb="sm" className="bookmark-sidebar__search">
<TextInput
value={searchTerm}
placeholder="Search bookmarks"
@@ -487,9 +486,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content bookmark-sidebar__content">
<Box p="sm" className="bookmark-sidebar__content">
{!bookmarkSupport && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
Bookmark support is unavailable for this viewer.
</Text>
@@ -497,7 +496,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && showNoDocument && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
Open a PDF to view its bookmarks.
</Text>
@@ -505,7 +504,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="sidebar-base__error">
<Stack gap="xs" align="center" className="bookmark-sidebar__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -516,7 +515,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Stack gap="md" align="center" c="dimmed" py="xl" className="bookmark-sidebar__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
Loading bookmarks...
@@ -525,7 +524,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showEmptyState && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks in this document
</Text>
@@ -539,7 +538,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showSearchEmpty && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks match your search
</Text>
@@ -10,7 +10,6 @@ import { PdfViewerToolbar } from '@app/components/viewer/PdfViewerToolbar';
import { ThumbnailSidebar } from '@app/components/viewer/ThumbnailSidebar';
import { BookmarkSidebar } from '@app/components/viewer/BookmarkSidebar';
import { AttachmentSidebar } from '@app/components/viewer/AttachmentSidebar';
import { LayerSidebar } from '@app/components/viewer/LayerSidebar';
import { useNavigationGuard, useNavigationState } from '@app/contexts/NavigationContext';
import { useSignature } from '@app/contexts/SignatureContext';
import { useRedaction } from '@app/contexts/RedactionContext';
@@ -25,7 +24,6 @@ import type { PDFDict, PDFNumber } from '@cantoo/pdf-lib';
import { useWheelZoom } from '@app/hooks/useWheelZoom';
import { useFormFill } from '@app/tools/formFill/FormFillContext';
import { FormSaveBar } from '@app/tools/formFill/FormSaveBar';
import { useViewerKeyCommand } from '@app/hooks/useViewerKeyCommand';
// ─── Measure dictionary extraction ────────────────────────────────────────────
@@ -127,8 +125,6 @@ const EmbedPdfViewerContent = ({
toggleThumbnailSidebar,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
setHasLayers,
isCommentsSidebarVisible,
isSearchInterfaceVisible,
searchInterfaceActions,
@@ -381,19 +377,15 @@ const EmbedPdfViewerContent = ({
onZoomOut: zoomActions.zoomOut,
});
const viewerKeyCommand = useViewerKeyCommand();
// Handle keyboard shortcuts
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const mod = event.ctrlKey || event.metaKey;
// Ctrl+P (print) must be intercepted unconditionally
// Ctrl+P (print) and Ctrl+R (rotate) must be intercepted unconditionally
// whenever the viewer is mounted, even before the user has hovered over it.
// Ctrl+R (rotate) is intercepted only on desktop (Tauri), while on web it still falls through to browser refresh.
// Without this, the browser falls through to its native "print HTML page"
// or "reload page" behaviour.
if (mod) {
const target = event.target as Element;
const isInTextInput =
@@ -402,15 +394,12 @@ const EmbedPdfViewerContent = ({
(target as HTMLElement).isContentEditable;
if (!isInTextInput) {
const wasOverridden = viewerKeyCommand(event)
if (!wasOverridden){
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
}
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
}
}
}
@@ -517,7 +506,7 @@ const EmbedPdfViewerContent = ({
}, [
isViewerHovered, isSearchInterfaceVisible, zoomActions, searchInterfaceActions,
scrollActions, printActions, exportActions, rotationActions, historyApiRef,
viewerApplyChanges, cyclePdfRenderMode, viewerKeyCommand,
viewerApplyChanges, cyclePdfRenderMode,
]);
// Watch the annotation history API to detect when the document becomes "dirty".
@@ -711,46 +700,6 @@ const EmbedPdfViewerContent = ({
return () => window.removeEventListener('formfill:apply', handler);
}, [handleFormApply]);
// Apply layer visibility changes - reload the modified PDF into the viewer
const layerApplyInProgressRef = useRef(false);
const handleLayerApply = useCallback(async (modifiedBlob: Blob) => {
if (layerApplyInProgressRef.current) return;
if (!currentFile || activeFileIds.length === 0) return;
layerApplyInProgressRef.current = true;
try {
const pageToRestore = lastKnownScrollPageRef.current;
const currentRotation = rotationState.rotation ?? 0;
const filename = currentFile.name || 'document.pdf';
const file = new File([modifiedBlob], filename, { type: 'application/pdf' });
const currentFileId = activeFiles[activeFileIndex]?.fileId;
if (!currentFileId) throw new Error('Current file ID not found');
const parentStub = selectors.getStirlingFileStub(currentFileId);
if (!parentStub) throw new Error('Parent stub not found');
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs([file], parentStub, 'multiTool');
pendingScrollRestoreRef.current = pageToRestore;
scrollRestoreAttemptsRef.current = 0;
pendingRotationRestoreRef.current = currentRotation;
rotationRestoreAttemptsRef.current = 0;
const newFileId = stubs[0]?.id;
if (newFileId) {
pendingFileIdRef.current = newFileId;
}
await actions.consumeFiles([currentFileId], stirlingFiles, stubs);
} catch (error) {
console.error('[Viewer] Apply layer changes failed:', error);
} finally {
layerApplyInProgressRef.current = false;
}
}, [currentFile, activeFiles, activeFileIndex, actions, selectors, activeFileIds.length, rotationState.rotation]);
// Discard pending redactions but save already-applied ones
// This is called when user clicks "Discard & Leave" - we want to:
// 1. NOT commit pending redaction marks (they get discarded)
@@ -970,7 +919,6 @@ const EmbedPdfViewerContent = ({
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) +
(isBookmarkSidebarVisible ? sidebarWidthRem : 0) +
(isAttachmentSidebarVisible ? sidebarWidthRem : 0) +
(isLayerSidebarVisible ? sidebarWidthRem : 0) +
(isCommentsSidebarVisible ? commentsSidebarWidthRem : 0);
return (
@@ -1039,7 +987,7 @@ const EmbedPdfViewerContent = ({
redactionTrackerRef={redactionTrackerRef as React.RefObject<RedactionPendingTrackerAPI>}
fileId={currentFileId}
isCommentsSidebarVisible={isCommentsSidebarVisible}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0) + (isLayerSidebarVisible ? sidebarWidthRem : 0)}rem`}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0)}rem`}
onSignatureAdded={() => {
// Handle signature added - for debugging, enable console logs as needed
// Future: Handle signature completion
@@ -1109,18 +1057,6 @@ const EmbedPdfViewerContent = ({
documentCacheKey={bookmarkCacheKey}
preloadCacheKeys={allBookmarkCacheKeys}
/>
<LayerSidebar
visible={isLayerSidebarVisible}
rightOffset={
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) +
(isBookmarkSidebarVisible ? sidebarWidthRem : 0) +
(isAttachmentSidebarVisible ? sidebarWidthRem : 0)
}
file={effectiveFile?.file ?? null}
documentCacheKey={bookmarkCacheKey}
onApplyLayers={handleLayerApply}
onLayersDetected={setHasLayers}
/>
{/* Navigation Warning Modal */}
{!previewFile && (
@@ -1,140 +0,0 @@
/* Layer Sidebar - Layer-specific styles (base styles in SidebarBase.css) */
/* Header actions (show/hide all buttons) */
.layer-sidebar__header-actions {
display: flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
}
/* Layer List */
.layer-list {
display: flex;
flex-direction: column;
gap: 0.125rem;
}
/* Layer Items */
.layer-item-wrapper {
display: flex;
flex-direction: column;
}
.layer-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.65rem;
border-radius: 0.5rem;
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease;
background: transparent;
border: 1px solid transparent;
width: 100%;
box-sizing: border-box;
}
.layer-item:hover {
background: color-mix(in srgb, var(--text-primary) 6%, var(--bg-toolbar));
border-color: color-mix(in srgb, var(--text-primary) 14%, var(--border-subtle));
}
.layer-item:active {
background: color-mix(in srgb, var(--text-primary) 10%, var(--bg-toolbar));
}
.layer-item__expand-btn {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 1.25rem;
height: 1.25rem;
cursor: pointer;
color: var(--text-muted);
opacity: 0.7;
transition: opacity 0.15s ease;
}
.layer-item__expand-btn:hover {
opacity: 1;
}
.layer-item__expand-placeholder {
flex-shrink: 0;
width: 1.25rem;
}
.layer-item__label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
line-height: 1.4;
cursor: pointer;
user-select: none;
}
.layer-item--hidden .layer-item__label {
color: var(--text-muted);
text-decoration: line-through;
text-decoration-color: color-mix(in srgb, var(--text-muted) 60%, transparent);
}
/* Children Container */
.layer-item__children {
display: flex;
flex-direction: column;
gap: 0.125rem;
margin-top: 0.125rem;
border-left: 2px solid color-mix(in srgb, var(--border-subtle) 60%, transparent);
margin-left: 0.875rem;
padding-left: 0.25rem;
}
/* Footer with Apply button */
.layer-sidebar__footer {
padding: 0.625rem 0.875rem;
background: var(--bg-toolbar);
border-top: 1px solid var(--border-subtle);
}
/* Dirty indicator badge */
.layer-sidebar__dirty-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background: var(--mantine-color-orange-5);
flex-shrink: 0;
}
/* Animation */
@keyframes layer-fade-in {
from {
opacity: 0;
transform: translateY(-3px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.layer-item__children {
animation: layer-fade-in 0.15s ease;
}
/* Accessibility & Reduced Motion */
@media (prefers-reduced-motion: reduce) {
.layer-item,
.layer-item__children {
transition: none;
animation: none;
}
}
@@ -1,377 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { Box, ScrollArea, Text, Checkbox, Stack, Loader, ActionIcon, Tooltip } from '@mantine/core';
import LayersIcon from '@mui/icons-material/Layers';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/LayerSidebar.css';
import { readPdfLayers, applyOCGVisibilityToPdf, collectLeafIds } from '@app/components/viewer/layerUtils';
import type { LayerInfo } from '@app/components/viewer/layerUtils';
export type { LayerInfo };
interface LayerSidebarProps {
visible: boolean;
/** Right offset in rem (how far from the right edge). */
rightOffset: number;
/** The current PDF file to read layers from. */
file?: Blob | null;
/** Stable key that changes when the document changes (used to avoid re-fetching). */
documentCacheKey?: string;
/** Called when the user applies layer visibility changes. Receives the modified PDF blob. */
onApplyLayers: (modifiedBlob: Blob) => Promise<void>;
/** Called when layer detection completes, reporting whether the PDF has layers. */
onLayersDetected?: (hasLayers: boolean) => void;
}
const SIDEBAR_WIDTH = '15rem';
type LoadStatus = 'idle' | 'loading' | 'ready' | 'no-layers' | 'error';
export function LayerSidebar({
visible,
rightOffset,
file,
documentCacheKey,
onApplyLayers,
onLayersDetected,
}: LayerSidebarProps) {
const [layers, setLayers] = useState<LayerInfo[]>([]);
const [visibility, setVisibility] = useState<Record<string, boolean>>({});
const [status, setStatus] = useState<LoadStatus>('idle');
const [loadError, setLoadError] = useState<string | null>(null);
const [isApplying, setIsApplying] = useState(false);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const loadedKeyRef = useRef<string | null>(null);
// Track whether visibility was set by user interaction (not initial load)
const userChangedRef = useRef(false);
// Load layers when the document changes
useEffect(() => {
if (!file || !documentCacheKey) {
setStatus('idle');
setLayers([]);
setVisibility({});
loadedKeyRef.current = null;
userChangedRef.current = false;
onLayersDetected?.(false);
return;
}
if (loadedKeyRef.current === documentCacheKey) return;
setStatus('loading');
setLoadError(null);
userChangedRef.current = false;
let cancelled = false;
readPdfLayers(file)
.then(layerList => {
if (cancelled) return;
if (layerList.length === 0) {
setStatus('no-layers');
setLayers([]);
setVisibility({});
loadedKeyRef.current = documentCacheKey;
onLayersDetected?.(false);
return;
}
// Build visibility map from the layer defaults (all leaf IDs)
const visMap: Record<string, boolean> = {};
const populateVisibility = (items: LayerInfo[]) => {
for (const item of items) {
if (item.children && item.children.length > 0) {
populateVisibility(item.children);
} else {
visMap[item.id] = item.visible;
}
}
};
populateVisibility(layerList);
setLayers(layerList);
setVisibility(visMap);
setStatus('ready');
loadedKeyRef.current = documentCacheKey;
onLayersDetected?.(true);
})
.catch(err => {
if (cancelled) return;
setStatus('error');
setLoadError(err instanceof Error ? err.message : 'Failed to read PDF layers');
onLayersDetected?.(false);
});
return () => {
cancelled = true;
};
}, [file, documentCacheKey, onLayersDetected]);
// Reset when document changes
useEffect(() => {
setExpanded({});
userChangedRef.current = false;
}, [documentCacheKey]);
// Auto-apply: debounce visibility changes from user interaction
useEffect(() => {
if (!userChangedRef.current || !file || isApplying || layers.length === 0) return;
const timer = setTimeout(async () => {
setIsApplying(true);
try {
const nameVisibility: Record<string, boolean> = {};
const collectNames = (items: LayerInfo[]) => {
for (const item of items) {
if (item.children && item.children.length > 0) {
collectNames(item.children);
} else {
nameVisibility[item.name] = visibility[item.id] ?? item.visible;
}
}
};
collectNames(layers);
const arrayBuffer = await file.arrayBuffer();
const modifiedBytes = await applyOCGVisibilityToPdf(arrayBuffer, nameVisibility);
const blob = new Blob([new Uint8Array(modifiedBytes)], { type: 'application/pdf' });
await onApplyLayers(blob);
} catch (err) {
console.error('[LayerSidebar] Failed to apply layer changes:', err);
} finally {
setIsApplying(false);
userChangedRef.current = false;
}
}, 300);
return () => clearTimeout(timer);
}, [visibility, file, layers, isApplying, onApplyLayers]);
const toggleLayerVisibility = useCallback((id: string) => {
userChangedRef.current = true;
setVisibility(prev => ({ ...prev, [id]: !prev[id] }));
}, []);
const showAll = useCallback(() => {
userChangedRef.current = true;
setVisibility(prev => {
const updated: Record<string, boolean> = {};
for (const id of Object.keys(prev)) {
updated[id] = true;
}
return updated;
});
}, []);
const hideAll = useCallback(() => {
userChangedRef.current = true;
setVisibility(prev => {
const updated: Record<string, boolean> = {};
for (const id of Object.keys(prev)) {
updated[id] = false;
}
return updated;
});
}, []);
const toggleExpanded = useCallback((id: string) => {
setExpanded(prev => ({ ...prev, [id]: !(prev[id] ?? true) }));
}, []);
const renderLayer = (layer: LayerInfo & { depth: number }) => {
const hasChildren = Boolean(layer.children && layer.children.length > 0);
const isExpanded = expanded[layer.id] !== false; // default expanded
const isLeaf = !hasChildren;
const isVisible = isLeaf
? visibility[layer.id] ?? layer.visible
: collectLeafIds(layer.children ?? []).every(id => visibility[id] ?? true);
return (
<div
key={layer.id}
className="layer-item-wrapper"
style={{ marginLeft: layer.depth > 0 ? `${layer.depth * 0.875}rem` : '0' }}
>
<div
className={`layer-item ${!isVisible ? 'layer-item--hidden' : ''}`}
onClick={() => {
if (hasChildren) {
toggleExpanded(layer.id);
} else {
toggleLayerVisibility(layer.id);
}
}}
role="button"
tabIndex={0}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (hasChildren) {
toggleExpanded(layer.id);
} else {
toggleLayerVisibility(layer.id);
}
}
}}
>
{hasChildren ? (
<span
className="layer-item__expand-btn"
onClick={e => {
e.stopPropagation();
toggleExpanded(layer.id);
}}
>
{isExpanded ? (
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
<path d="M2 4l4 4 4-4z" />
</svg>
) : (
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
<path d="M4 2l4 4-4 4z" />
</svg>
)}
</span>
) : (
<span className="layer-item__expand-placeholder" />
)}
{isLeaf && (
<Checkbox
size="xs"
checked={visibility[layer.id] ?? layer.visible}
onChange={() => toggleLayerVisibility(layer.id)}
onClick={e => e.stopPropagation()}
style={{ flexShrink: 0 }}
/>
)}
<Tooltip
label={layer.name}
position="left"
withinPortal
disabled={layer.name.length < 20}
>
<span className="layer-item__label">
{layer.name}
</span>
</Tooltip>
</div>
{hasChildren && isExpanded && (
<div className="layer-item__children">
{(layer.children ?? []).map(child => renderLayer({ ...child, depth: 0 }))}
</div>
)}
</div>
);
};
if (!visible) return null;
const leafIds = collectLeafIds(layers);
const allVisible = leafIds.every(id => visibility[id] !== false);
const allHidden = leafIds.every(id => visibility[id] === false);
return (
<Box
className="sidebar-base layer-sidebar"
style={{
position: 'fixed',
right: `${rightOffset}rem`,
top: 0,
bottom: 0,
width: SIDEBAR_WIDTH,
zIndex: 998,
}}
>
{/* Header */}
<div className="sidebar-base__header">
<div className="sidebar-base__header-title">
<span className="sidebar-base__header-icon">
<LayersIcon fontSize="small" />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5} style={{ flex: 1 }}>
Layers
</Text>
{isApplying && <Loader size="xs" type="dots" />}
</div>
{status === 'ready' && leafIds.length > 0 && (
<div className="layer-sidebar__header-actions">
<ActionIcon
variant="subtle"
size="sm"
onClick={showAll}
disabled={allVisible || isApplying}
aria-label="Show all layers"
title="Show all"
>
<VisibilityIcon sx={{ fontSize: '1rem' }} />
</ActionIcon>
<ActionIcon
variant="subtle"
size="sm"
onClick={hideAll}
disabled={allHidden || isApplying}
aria-label="Hide all layers"
title="Hide all"
>
<VisibilityOffIcon sx={{ fontSize: '1rem' }} />
</ActionIcon>
</div>
)}
</div>
{/* Content */}
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content">
{status === 'idle' && (
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
Open a PDF to view its layers.
</Text>
</div>
)}
{status === 'loading' && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
Loading layers...
</Text>
</Stack>
)}
{status === 'error' && (
<div className="sidebar-base__error">
<Text size="sm" c="red" ta="center">
{loadError ?? 'Failed to load layers.'}
</Text>
</div>
)}
{status === 'no-layers' && (
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
This document has no layers.
</Text>
</div>
)}
{status === 'ready' && layers.length > 0 && (
<div className="layer-list">
{layers.map(layer => renderLayer({ ...layer, depth: 0 }))}
</div>
)}
</Box>
</ScrollArea>
</Box>
);
}
@@ -4,7 +4,6 @@ import type { PluginRegistry } from '@embedpdf/core';
import { EmbedPDF } from '@embedpdf/core/react';
import { usePdfiumEngine } from '@embedpdf/engines/react';
import { PrivateContent } from '@app/components/shared/PrivateContent';
import { useAppConfig } from '@app/contexts/AppConfigContext';
// Import the essential plugins
import { Viewport, ViewportPluginPackage } from '@embedpdf/plugin-viewport/react';
@@ -95,17 +94,15 @@ interface LocalEmbedPDFProps {
export function LocalEmbedPDF({ file, url, fileName, enableAnnotations = false, enableRedaction = false, enableFormFill = false, isManualRedactionMode = false, showBakedAnnotations = true, onSignatureAdded, signatureApiRef, annotationApiRef, historyApiRef, redactionTrackerRef, fileId, isCommentsSidebarVisible = false, commentsSidebarRightOffset = '0rem', isSignMode = false, pdfRenderMode = 'normal' }: LocalEmbedPDFProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [, setAnnotations] = useState<Array<{id: string, pageIndex: number, rect: Rect}>>([]);
const [commentAuthorName, setCommentAuthorName] = useState<string>('Guest');
useEffect(() => {
if (!config?.enableLogin) return;
accountService.getAccountData().then((data) => {
if (data?.username) setCommentAuthorName(data.username);
}).catch(() => {/* not logged in or security disabled */});
}, [config?.enableLogin]);
}, []);
// Convert File to URL if needed
useEffect(() => {
@@ -1,113 +0,0 @@
import { useCallback, useMemo } from 'react';
import { Box, Button, Center, Stack, Text } from '@mantine/core';
import ArticleIcon from '@mui/icons-material/Article';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import { useFileState } from '@app/contexts/FileContext';
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
import { detectFileExtension, detectNonPdfFileType } from '@app/utils/fileUtils';
import { CONVERSION_MATRIX } from '@app/constants/convertConstants';
import { NonPdfBanner } from '@app/components/viewer/nonpdf/NonPdfBanner';
import { getFileTypeMeta } from '@app/components/viewer/nonpdf/types';
import { ImageViewer } from '@app/components/viewer/nonpdf/ImageViewer';
import { CsvViewer } from '@app/components/viewer/nonpdf/CsvViewer';
import { JsonViewer } from '@app/components/viewer/nonpdf/JsonViewer';
import { TextViewer } from '@app/components/viewer/nonpdf/TextViewer';
import { HtmlViewer } from '@app/components/viewer/nonpdf/HtmlViewer';
export interface ViewerProps {
sidebarsVisible: boolean;
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
activeFileIndex?: number;
setActiveFileIndex?: (index: number) => void;
}
export interface NonPdfViewerProps extends ViewerProps {
file: File;
}
export function NonPdfViewer({ file }: NonPdfViewerProps) {
const fileType = useMemo(() => detectNonPdfFileType(file), [file]);
const meta = useMemo(() => getFileTypeMeta(fileType, file.name), [fileType, file.name]);
const { handleToolSelect, toolAvailability } = useToolWorkflow();
const fileExtension = detectFileExtension(file.name);
// Only show convert when the extension has an explicit entry in the conversion matrix
// (skip the 'any'/'image' wildcard fallbacks that would match everything)
const isConvertAvailable = toolAvailability['convert']?.available === true
&& fileExtension !== ''
&& fileExtension in CONVERSION_MATRIX;
const handleConvertToPdf = useCallback(() => {
handleToolSelect('convert');
}, [handleToolSelect]);
const renderContent = () => {
switch (fileType) {
case 'image':
return <ImageViewer file={file} fileName={file.name} />;
case 'csv':
return <CsvViewer file={file} isTsv={file.name.toLowerCase().endsWith('.tsv')} />;
case 'json':
return <JsonViewer file={file} />;
case 'markdown':
return <TextViewer file={file} isMarkdown />;
case 'text':
return <TextViewer file={file} isMarkdown={false} />;
case 'html':
return <HtmlViewer file={file} />;
default:
return (
<Center style={{ flex: 1 }}>
<Stack align="center" gap="sm">
<ArticleIcon style={{ fontSize: '3rem', color: 'var(--mantine-color-gray-4)' }} />
<Text c="dimmed" size="sm">Preview not available for this file type</Text>
{isConvertAvailable && (
<Button variant="light" color="orange" leftSection={<PictureAsPdfIcon />} onClick={handleConvertToPdf}>
Convert to PDF
</Button>
)}
</Stack>
</Center>
);
}
};
return (
<Stack gap={0} style={{ height: '100%', flex: 1, overflow: 'hidden', position: 'relative' }}>
<NonPdfBanner
meta={meta}
onConvertToPdf={isConvertAvailable ? handleConvertToPdf : undefined}
/>
<Box style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{renderContent()}
</Box>
</Stack>
);
}
// ─── Wrapper that resolves the active file from FileContext ───────────────────
export function NonPdfViewerWrapper(props: ViewerProps) {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
const activeFileIndex = props.activeFileIndex ?? 0;
const file = props.previewFile ?? activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
if (!file) {
return (
<Center style={{ flex: 1 }}>
<Text c="dimmed" size="sm">No file selected</Text>
</Center>
);
}
return <NonPdfViewer {...props} file={file} />;
}
export default NonPdfViewerWrapper;
@@ -1,61 +0,0 @@
/* Shared Sidebar Base - Common styles for all viewer sidebars */
/* Container */
.sidebar-base {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.sidebar-base__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.sidebar-base__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.sidebar-base__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section (used by bookmark & attachment sidebars) */
.sidebar-base__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.sidebar-base__content {
padding-top: 0.5rem !important;
}
.sidebar-base__empty-state,
.sidebar-base__error {
padding: 2rem 1rem;
text-align: center;
}
.sidebar-base__loading {
padding: 2rem 1rem !important;
}
+9 -20
View File
@@ -1,27 +1,16 @@
import { useMemo } from 'react';
import EmbedPdfViewer from '@app/components/viewer/EmbedPdfViewer';
import { NonPdfViewerWrapper, type ViewerProps } from '@app/components/viewer/NonPdfViewer';
import { useFileState } from '@app/contexts/FileContext';
import { isPdfFile } from '@app/utils/fileUtils';
export type { ViewerProps };
export interface ViewerProps {
sidebarsVisible: boolean;
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
activeFileIndex?: number;
setActiveFileIndex?: (index: number) => void;
}
const Viewer = (props: ViewerProps) => {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
const activeFileIndex = props.activeFileIndex ?? 0;
// Determine the active file — previewFile takes priority
const activeFile = useMemo(() => {
if (props.previewFile) return props.previewFile;
return activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
}, [props.previewFile, activeFiles, activeFileIndex]);
// Route to the appropriate viewer based on file type
if (activeFile && !isPdfFile(activeFile)) {
return <NonPdfViewerWrapper {...props} />;
}
// Default to EmbedPDF viewer
return <EmbedPdfViewer {...props} />;
};
@@ -1,228 +0,0 @@
export interface LayerInfo {
id: string;
name: string;
visible: boolean;
children?: LayerInfo[];
}
/**
* Reads OCG layer info from a PDF file using pdfjs-dist.
* Returns a flat list of all OCG groups with their names and default visibility.
*/
export async function readPdfLayers(file: Blob): Promise<LayerInfo[]> {
const { getDocument, GlobalWorkerOptions } = await import('pdfjs-dist/legacy/build/pdf.mjs');
if (!GlobalWorkerOptions.workerSrc) {
GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
import.meta.url
).toString();
}
const arrayBuffer = await file.arrayBuffer();
const loadingTask = getDocument({ data: arrayBuffer, verbosity: 0 });
const pdfDoc = await loadingTask.promise;
try {
const ocConfig = await pdfDoc.getOptionalContentConfig();
if (!ocConfig) return [];
// pdfjs v5 uses [Symbol.iterator] and getGroup(id), not getGroups()
const groups: Record<string, any> = {};
for (const [id, group] of ocConfig as any) {
groups[id] = group;
}
if (Object.keys(groups).length === 0) return [];
// Use getOrder() for hierarchical display
let order: any[] | null = null;
try {
order = ocConfig.getOrder?.() ?? null;
} catch {
// getOrder not available
}
if (order && Array.isArray(order) && order.length > 0) {
return buildLayerTree(order, groups);
}
// Fallback: flat list in enumeration order
return Object.entries(groups).map(([id, group]) => ({
id,
name: (group as any).name ?? id,
visible: (group as any).visible ?? true,
}));
} finally {
await pdfDoc.destroy();
}
}
/**
* Recursively builds a LayerInfo tree from pdfjs OCG order array.
* The order array can contain:
* - string: an OCG id
* - { name: string, order: any[] }: a named group with children
* - array: a nested group
*/
function buildLayerTree(
order: any[],
groups: Record<string, any>,
visited = new Set<string>()
): LayerInfo[] {
const result: LayerInfo[] = [];
for (const item of order) {
if (typeof item === 'string') {
// It's an OCG id
if (visited.has(item)) continue;
visited.add(item);
const group = groups[item];
if (group) {
result.push({
id: item,
name: (group as any).name ?? item,
visible: (group as any).visible ?? true,
});
}
} else if (Array.isArray(item)) {
// Nested group (unlabeled)
const children = buildLayerTree(item, groups, visited);
result.push(...children);
} else if (item && typeof item === 'object') {
// Named group with nested items
const { name, order: subOrder } = item as { name?: string; order?: any[] };
const children = subOrder ? buildLayerTree(subOrder, groups, visited) : [];
if (name && children.length > 0) {
// Use the first child's id as a synthetic group id
result.push({
id: `group-${name}`,
name: name,
visible: children.every(c => c.visible),
children,
});
} else {
result.push(...children);
}
}
}
return result;
}
/**
* Modifies OCG visibility in a PDF using @cantoo/pdf-lib.
* Accepts a flat map of { layerName -> visible } and rewrites the /D config.
*
* Strategy: set /BaseState to /OFF and only list visible layers in /ON.
* This is the most unambiguous approach and avoids conflicts between
* /BaseState, /ON, and /OFF that can confuse some viewers.
* Also removes /AS (auto-state) entries that can override visibility.
*/
export async function applyOCGVisibilityToPdf(
pdfBytes: ArrayBuffer,
layerVisibility: Record<string, boolean>
): Promise<Uint8Array> {
const { PDFDocument, PDFDict, PDFName, PDFArray, PDFString, PDFHexString } =
await import('@cantoo/pdf-lib');
const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
const context = doc.context;
// Access the catalog via the trailer's Root reference
const catalogRef = context.trailerInfo.Root;
const catalog = context.lookup(catalogRef) as unknown as typeof PDFDict.prototype;
// Get OCProperties dict (may be a direct dict or an indirect reference)
const ocPropsRaw = (catalog as any).lookup(PDFName.of('OCProperties'));
if (!ocPropsRaw) {
return doc.save();
}
const ocProps = (ocPropsRaw instanceof PDFDict
? ocPropsRaw
: context.lookup(ocPropsRaw)) as unknown as typeof PDFDict.prototype;
// Get the /OCGs array
const ocgsRaw = (ocProps as any).lookup(PDFName.of('OCGs'));
if (!(ocgsRaw instanceof PDFArray)) {
return doc.save();
}
const ocgsArray = ocgsRaw as unknown as typeof PDFArray.prototype;
// Get or create the /D (default config) dict
const dRaw = (ocProps as any).lookup(PDFName.of('D'));
if (!dRaw) {
return doc.save();
}
const dDict = (dRaw instanceof PDFDict
? dRaw
: context.lookup(dRaw)) as unknown as typeof PDFDict.prototype;
// Collect OCG refs for ON vs OFF based on user visibility settings
const onRefs: any[] = [];
const offRefs: any[] = [];
const size = (ocgsArray as any).size() as number;
for (let i = 0; i < size; i++) {
const ocgRef = (ocgsArray as any).get(i);
const ocgDict = context.lookup(ocgRef) as unknown as typeof PDFDict.prototype;
if (!ocgDict) continue;
// Get the OCG name
const nameRaw = (ocgDict as any).lookup(PDFName.of('Name'));
let ocgName = '';
if (nameRaw instanceof PDFString || nameRaw instanceof PDFHexString) {
ocgName = (nameRaw as any).decodeText?.() ?? (nameRaw as any).asString?.() ?? '';
} else if (nameRaw) {
ocgName = String(nameRaw);
}
// Look up visibility by name
const shouldBeVisible = layerVisibility[ocgName] ?? true;
if (shouldBeVisible) {
onRefs.push(ocgRef);
} else {
offRefs.push(ocgRef);
}
}
// Set /BaseState to /OFF so all layers start hidden, then /ON lists visible ones.
// This is unambiguous and avoids conflicts between /BaseState and /ON//OFF.
(dDict as any).set(PDFName.of('BaseState'), PDFName.of('OFF'));
// Set /ON to only the visible layers
if (onRefs.length > 0) {
(dDict as any).set(PDFName.of('ON'), context.obj(onRefs));
} else {
(dDict as any).delete?.(PDFName.of('ON'));
}
// Set /OFF to only the hidden layers (for viewers that check it)
if (offRefs.length > 0) {
(dDict as any).set(PDFName.of('OFF'), context.obj(offRefs));
} else {
(dDict as any).delete?.(PDFName.of('OFF'));
}
// Remove /AS (auto-state) array — it can contain usage-based overrides
// (e.g., print vs view) that conflict with our explicit visibility settings.
(dDict as any).delete?.(PDFName.of('AS'));
return doc.save();
}
/**
* Collects all leaf-level layer IDs (those that are actual OCGs, not synthetic groups).
*/
export function collectLeafIds(layers: LayerInfo[]): string[] {
const ids: string[] = [];
for (const layer of layers) {
if (layer.children && layer.children.length > 0) {
ids.push(...collectLeafIds(layer.children));
} else {
ids.push(layer.id);
}
}
return ids;
}
@@ -1,191 +0,0 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Badge, Center, Group, Paper, ScrollArea, Stack, Table, Text } from '@mantine/core';
import SortIcon from '@mui/icons-material/Sort';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
// ─── CSV parser ───────────────────────────────────────────────────────────────
function parseCsv(text: string, delimiter: string): string[][] {
const rows: string[][] = [];
let field = '';
let inQuotes = false;
let row: string[] = [];
for (let i = 0; i < text.length; i++) {
const ch = text[i];
const next = text[i + 1];
if (inQuotes) {
if (ch === '"' && next === '"') {
field += '"';
i++;
} else if (ch === '"') {
inQuotes = false;
} else {
field += ch;
}
} else if (ch === '"') {
inQuotes = true;
} else if (ch === delimiter) {
row.push(field);
field = '';
} else if (ch === '\r' && next === '\n') {
row.push(field);
field = '';
rows.push(row);
row = [];
i++;
} else if (ch === '\n' || ch === '\r') {
row.push(field);
field = '';
rows.push(row);
row = [];
} else {
field += ch;
}
}
if (field || row.length > 0) {
row.push(field);
rows.push(row);
}
// Remove trailing empty row
if (rows.length > 0 && rows[rows.length - 1].every(f => f === '')) {
rows.pop();
}
return rows;
}
// ─── CSV viewer ───────────────────────────────────────────────────────────────
interface CsvViewerProps {
file: File;
isTsv: boolean;
}
export function CsvViewer({ file, isTsv }: CsvViewerProps) {
const { t } = useTranslation();
const [rows, setRows] = useState<string[][]>([]);
const [loading, setLoading] = useState(true);
const [sortCol, setSortCol] = useState<number | null>(null);
const [sortAsc, setSortAsc] = useState(true);
useEffect(() => {
setLoading(true);
file.text().then(text => {
const delimiter = isTsv ? '\t' : ',';
setRows(parseCsv(text, delimiter));
setLoading(false);
});
}, [file, isTsv]);
const headers = rows[0] ?? [];
const dataRows = rows.slice(1);
const sortedDataRows = useMemo(() => {
if (sortCol === null) return dataRows;
return [...dataRows].sort((a, b) => {
const av = a[sortCol] ?? '';
const bv = b[sortCol] ?? '';
const numA = Number(av);
const numB = Number(bv);
const cmp = (!isNaN(numA) && !isNaN(numB)) ? numA - numB : av.localeCompare(bv);
return sortAsc ? cmp : -cmp;
});
}, [dataRows, sortCol, sortAsc]);
const handleSort = (colIdx: number) => {
if (sortCol === colIdx) {
setSortAsc(a => !a);
} else {
setSortCol(colIdx);
setSortAsc(true);
}
};
if (loading) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>;
}
if (rows.length === 0) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.emptyFile')}</Text></Center>;
}
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{/* Stats bar */}
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Group gap="md" align="center">
<Text size="xs" c="dimmed">
{t('viewer.nonPdf.csvStats', { rows: dataRows.length.toLocaleString(), columns: headers.length, size: formatFileSize(file.size) })}
</Text>
{sortCol !== null && (
<Badge
variant="light"
color="teal"
size="xs"
style={{ cursor: 'pointer' }}
onClick={() => { setSortCol(null); setSortAsc(true); }}
>
{t('viewer.nonPdf.sortedBy', { column: headers[sortCol] || t('viewer.nonPdf.columnDefault', { index: sortCol + 1 }) })} {sortAsc ? '\u2191' : '\u2193'} \u2715
</Badge>
)}
</Group>
</Paper>
{/* Table */}
<ScrollArea style={{ flex: 1 }}>
<Table
striped
highlightOnHover
withColumnBorders
withTableBorder={false}
style={{ fontSize: 'var(--mantine-font-size-xs)', whiteSpace: 'nowrap' }}
stickyHeader
>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 48, color: 'var(--mantine-color-dimmed)', textAlign: 'center', paddingInline: 8 }}>
#
</Table.Th>
{headers.map((h, i) => (
<Table.Th
key={i}
style={{ cursor: 'pointer', paddingInline: 8 }}
onClick={() => handleSort(i)}
>
<Group gap={4} align="center" wrap="nowrap">
<Text size="xs" fw={600} truncate style={{ maxWidth: 200 }}>{h || t('viewer.nonPdf.columnDefault', { index: i + 1 })}</Text>
<SortIcon
style={{
fontSize: '0.85rem',
opacity: sortCol === i ? 1 : 0.3,
color: sortCol === i ? 'var(--mantine-color-teal-6)' : undefined,
transform: sortCol === i && !sortAsc ? 'scaleY(-1)' : undefined,
}}
/>
</Group>
</Table.Th>
))}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{sortedDataRows.map((row, ri) => (
<Table.Tr key={ri}>
<Table.Td style={{ color: 'var(--mantine-color-dimmed)', textAlign: 'center', paddingInline: 8 }}>
{ri + 1}
</Table.Td>
{headers.map((_, ci) => (
<Table.Td key={ci} style={{ paddingInline: 8, maxWidth: 300 }}>
<Text size="xs" truncate title={row[ci]}>{row[ci] ?? ''}</Text>
</Table.Td>
))}
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea>
</Stack>
);
}
@@ -1,36 +0,0 @@
import { useEffect, useState } from 'react';
import { Box, Paper, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
interface HtmlViewerProps {
file: File;
}
export function HtmlViewer({ file }: HtmlViewerProps) {
const { t } = useTranslation();
const [objectUrl, setObjectUrl] = useState<string | null>(null);
useEffect(() => {
const url = URL.createObjectURL(file);
setObjectUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<Box style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Text size="xs" c="dimmed">{t('viewer.nonPdf.htmlPreviewWarning', { size: formatFileSize(file.size) })}</Text>
</Paper>
{objectUrl && (
<iframe
src={objectUrl}
title={t('viewer.nonPdf.htmlPreview')}
sandbox="allow-scripts"
style={{ flex: 1, border: 'none', background: '#fff' }}
/>
)}
</Box>
);
}
@@ -1,44 +0,0 @@
import { useEffect, useState } from 'react';
import { Box } from '@mantine/core';
interface ImageViewerProps {
file: File;
fileName: string;
}
export function ImageViewer({ file, fileName }: ImageViewerProps) {
const [objectUrl, setObjectUrl] = useState<string | null>(null);
useEffect(() => {
const url = URL.createObjectURL(file);
setObjectUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<Box
style={{
flex: 1,
overflow: 'hidden',
background: 'var(--mantine-color-gray-1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{objectUrl && (
<img
src={objectUrl}
alt={fileName}
draggable={false}
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
display: 'block',
}}
/>
)}
</Box>
);
}
@@ -1,57 +0,0 @@
import { useEffect, useState } from 'react';
import { Box, Center, Paper, ScrollArea, Stack, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
interface JsonViewerProps {
file: File;
}
export function JsonViewer({ file }: JsonViewerProps) {
const { t } = useTranslation();
const [content, setContent] = useState<string | null>(null);
const [isInvalidJson, setIsInvalidJson] = useState(false);
useEffect(() => {
file.text().then(text => {
try {
const parsed = JSON.parse(text);
setContent(JSON.stringify(parsed, null, 2));
setIsInvalidJson(false);
} catch (_e) {
// Show raw content if JSON is invalid
setContent(text);
setIsInvalidJson(true);
}
});
}, [file]);
if (content === null) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>;
}
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{isInvalidJson && (
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-red-2)', background: 'var(--mantine-color-red-0)', flexShrink: 0 }}>
<Text size="xs" c="red">{t('viewer.nonPdf.invalidJson')}</Text>
</Paper>
)}
<ScrollArea style={{ flex: 1 }} type="auto">
<Box
component="pre"
style={{
margin: 0,
padding: 'var(--mantine-spacing-sm)',
fontFamily: 'monospace',
fontSize: '0.8rem',
lineHeight: 1.6,
whiteSpace: 'pre',
overflowX: 'auto',
}}
>
{content}
</Box>
</ScrollArea>
</Stack>
);
}
@@ -1,53 +0,0 @@
import { Badge, Box, Button, Group } from '@mantine/core';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import { useTranslation } from 'react-i18next';
import type { FileTypeMeta } from '@app/components/viewer/nonpdf/types';
interface NonPdfBannerProps {
meta: FileTypeMeta;
onConvertToPdf?: () => void;
}
export function NonPdfBanner({ meta, onConvertToPdf }: NonPdfBannerProps) {
const { t } = useTranslation();
return (
<Group
gap="xs"
wrap="nowrap"
align="center"
style={{
position: 'absolute',
top: 8,
right: 8,
zIndex: 10,
pointerEvents: 'auto',
}}
>
<Badge
variant="default"
size="lg"
leftSection={
<Box style={{ display: 'flex', alignItems: 'center', fontSize: '0.85rem' }}>
{meta.icon}
</Box>
}
style={{ fontWeight: 600 }}
>
{t('viewer.nonPdf.fileTypeBadge', { type: meta.label })}
</Badge>
{onConvertToPdf && (
<Button
size="xs"
variant="light"
color="orange"
leftSection={<PictureAsPdfIcon style={{ fontSize: '0.9rem' }} />}
onClick={onConvertToPdf}
>
{t('viewer.nonPdf.convertToPdf')}
</Button>
)}
</Group>
);
}
@@ -1,192 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Box, Center, Checkbox, Group, Paper, ScrollArea, Stack, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
// ─── Markdown renderer ────────────────────────────────────────────────────────
function renderInline(text: string): React.ReactNode[] {
const parts: React.ReactNode[] = [];
// Patterns: **bold**, *italic*, `code`, [link](url)
const re = /(\*\*(.+?)\*\*|\*(.+?)\*|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\))/g;
let last = 0;
let match;
let key = 0;
while ((match = re.exec(text)) !== null) {
if (match.index > last) parts.push(text.slice(last, match.index));
if (match[2]) parts.push(<strong key={key++}>{match[2]}</strong>);
else if (match[3]) parts.push(<em key={key++}>{match[3]}</em>);
else if (match[4]) parts.push(<code key={key++} style={{ background: 'var(--mantine-color-gray-1)', padding: '0 3px', borderRadius: 3, fontFamily: 'monospace', fontSize: '0.85em' }}>{match[4]}</code>);
else if (match[5]) parts.push(<a key={key++} href={match[6]} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--mantine-color-blue-6)' }}>{match[5]}</a>);
last = match.index + match[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts;
}
function renderMarkdown(text: string): React.ReactNode[] {
const lines = text.split('\n');
const elements: React.ReactNode[] = [];
let inCodeBlock = false;
let codeLines: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (line.startsWith('```')) {
if (inCodeBlock) {
elements.push(
<pre key={i} style={{ background: 'var(--mantine-color-gray-1)', padding: '8px 12px', borderRadius: 4, overflowX: 'auto', fontSize: '0.85em', margin: '4px 0' }}>
<code>{codeLines.join('\n')}</code>
</pre>
);
codeLines = [];
inCodeBlock = false;
} else {
inCodeBlock = true;
}
i++;
continue;
}
if (inCodeBlock) {
codeLines.push(line);
i++;
continue;
}
if (line.startsWith('### ')) {
elements.push(<Text key={i} fw={600} size="md" mt="xs" mb={2}>{renderInline(line.slice(4))}</Text>);
} else if (line.startsWith('## ')) {
elements.push(<Text key={i} fw={700} size="lg" mt="sm" mb={4}>{renderInline(line.slice(3))}</Text>);
} else if (line.startsWith('# ')) {
elements.push(<Text key={i} fw={800} size="xl" mt="md" mb={6}>{renderInline(line.slice(2))}</Text>);
} else if (line.startsWith('- ') || line.startsWith('* ')) {
elements.push(
<Group key={i} gap={6} align="flex-start" style={{ paddingLeft: 16 }}>
<Text size="sm" style={{ lineHeight: 1.6, flexShrink: 0 }}>{'\u2022'}</Text>
<Text size="sm" style={{ lineHeight: 1.6 }}>{renderInline(line.slice(2))}</Text>
</Group>
);
} else if (/^\d+\.\s/.test(line)) {
const num = line.match(/^(\d+)\.\s/)?.[1];
const rest = line.replace(/^\d+\.\s/, '');
elements.push(
<Group key={i} gap={6} align="flex-start" style={{ paddingLeft: 16 }}>
<Text size="sm" style={{ lineHeight: 1.6, flexShrink: 0 }}>{num}.</Text>
<Text size="sm" style={{ lineHeight: 1.6 }}>{renderInline(rest)}</Text>
</Group>
);
} else if (line.trim() === '' || line === '---' || line === '***') {
elements.push(<Box key={i} style={{ height: 8 }} />);
} else {
elements.push(<Text key={i} size="sm" style={{ lineHeight: 1.7 }}>{renderInline(line)}</Text>);
}
i++;
}
return elements;
}
// ─── Text / Markdown viewer ───────────────────────────────────────────────────
interface TextViewerProps {
file: File;
isMarkdown: boolean;
}
export function TextViewer({ file, isMarkdown }: TextViewerProps) {
const { t } = useTranslation();
const [content, setContent] = useState<string | null>(null);
const [showLineNumbers, setShowLineNumbers] = useState(!isMarkdown);
const [renderMd, setRenderMd] = useState(isMarkdown);
useEffect(() => {
file.text().then(setContent);
}, [file]);
const lines = content?.split('\n') ?? [];
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{/* Toolbar */}
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Group gap="md" align="center">
<Text size="xs" c="dimmed">{t('viewer.nonPdf.textStats', { lines: lines.length.toLocaleString(), size: formatFileSize(file.size) })}</Text>
{!isMarkdown && (
<Checkbox
label={<Text size="xs">{t('viewer.nonPdf.lineNumbers')}</Text>}
checked={showLineNumbers}
onChange={e => setShowLineNumbers(e.currentTarget.checked)}
size="xs"
/>
)}
{isMarkdown && (
<Checkbox
label={<Text size="xs">{t('viewer.nonPdf.renderMarkdown')}</Text>}
checked={renderMd}
onChange={e => setRenderMd(e.currentTarget.checked)}
size="xs"
/>
)}
</Group>
</Paper>
{/* Content */}
<ScrollArea style={{ flex: 1 }} p="md">
{content === null ? (
<Center><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>
) : isMarkdown && renderMd ? (
<Box style={{ maxWidth: 800, margin: '0 auto', padding: '8px 0' }}>
{renderMarkdown(content)}
</Box>
) : (
<Box
component="pre"
style={{
fontFamily: 'monospace',
fontSize: '0.8rem',
lineHeight: 1.6,
margin: 0,
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
display: 'table',
width: '100%',
}}
>
{lines.map((line, i) => (
<Box
key={i}
component="div"
style={{ display: 'table-row' }}
>
{showLineNumbers && (
<Box
component="span"
style={{
display: 'table-cell',
paddingRight: 16,
paddingLeft: 4,
textAlign: 'right',
color: 'var(--mantine-color-gray-5)',
userSelect: 'none',
borderRight: '1px solid var(--mantine-color-gray-2)',
minWidth: `${String(lines.length).length + 1}ch`,
}}
>
{i + 1}
</Box>
)}
<Box component="span" style={{ display: 'table-cell', paddingLeft: showLineNumbers ? 12 : 0 }}>
{line || '\u00A0'}
</Box>
</Box>
))}
</Box>
)}
</ScrollArea>
</Stack>
);
}
@@ -1,51 +0,0 @@
import React from 'react';
import ImageIcon from '@mui/icons-material/Image';
import TableChartIcon from '@mui/icons-material/TableChart';
import ArticleIcon from '@mui/icons-material/Article';
import CodeIcon from '@mui/icons-material/Code';
import DataObjectIcon from '@mui/icons-material/DataObject';
import HtmlIcon from '@mui/icons-material/Html';
import type { NonPdfFileType } from '@app/utils/fileUtils';
export interface FileTypeMeta {
label: string;
icon: React.ReactNode;
color: string; // Mantine color name (e.g. 'teal', 'violet')
accentColor: string;
borderColor: string;
bgColor: string;
textColor: string;
}
// Shared neutral color scheme for all file type badges — consistent in light & dark mode
const BADGE_COLORS = {
color: 'gray' as const,
accentColor: 'var(--mantine-color-gray-6)',
borderColor: 'var(--mantine-color-gray-3)',
bgColor: 'var(--mantine-color-gray-0)',
textColor: 'var(--mantine-color-gray-9)',
};
export function getFileTypeMeta(type: NonPdfFileType, fileName?: string): FileTypeMeta {
switch (type) {
case 'image':
return { label: 'Image', icon: React.createElement(ImageIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'csv':
return { label: 'Spreadsheet', icon: React.createElement(TableChartIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'json':
return { label: 'JSON', icon: React.createElement(DataObjectIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'markdown':
return { label: 'Markdown', icon: React.createElement(CodeIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'html':
return { label: 'HTML', icon: React.createElement(HtmlIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'text':
return { label: 'Text', icon: React.createElement(ArticleIcon, { fontSize: 'small' }), ...BADGE_COLORS };
default: {
// For unknown types, derive label from the file extension (e.g. ".docx" → "DOCX")
const ext = fileName?.split('.').pop()?.toUpperCase();
const label = ext || 'File';
return { label, icon: React.createElement(ArticleIcon, { fontSize: 'small' }), ...BADGE_COLORS };
}
}
}
@@ -16,7 +16,6 @@ import { BASE_PATH, withBasePath } from '@app/constants/app';
import { useRedaction, useRedactionMode } from '@app/contexts/RedactionContext';
import TextFieldsIcon from '@mui/icons-material/TextFields';
import StraightenIcon from '@mui/icons-material/Straighten';
import LayersIcon from '@mui/icons-material/Layers';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import StopIcon from '@mui/icons-material/Stop';
import { useViewerReadAloud } from '@app/components/viewer/useViewerReadAloud';
@@ -27,7 +26,7 @@ export function useViewerRightRailButtons(
) {
const { t, i18n } = useTranslation();
const viewer = useViewer();
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isLayerSidebarVisible, hasLayers, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const [isPanning, setIsPanning] = useState<boolean>(() => viewer.getPanState()?.isPanning ?? false);
const { sidebarRefs } = useSidebarContext();
const { position: tooltipPosition } = useRightRailTooltipSide(sidebarRefs, 12);
@@ -84,7 +83,6 @@ export function useViewerRightRailButtons(
const sidebarLabel = t('rightRail.toggleSidebar', 'Toggle Sidebar');
const bookmarkLabel = t('rightRail.toggleBookmarks', 'Toggle Bookmarks');
const attachmentLabel = t('rightRail.toggleAttachments', 'Toggle Attachments');
const layersLabel = t('rightRail.toggleLayers', 'Toggle Layers');
const commentsLabel = t('rightRail.toggleComments', 'Comments');
const printLabel = t('rightRail.print', 'Print PDF');
const annotationsLabel = t('rightRail.annotations', 'Annotations');
@@ -238,18 +236,6 @@ export function useViewerRightRailButtons(
viewer.toggleAttachmentSidebar();
}
},
...(hasLayers ? [{
id: 'viewer-toggle-layers',
icon: <LayersIcon sx={{ fontSize: '1.5rem' }} />,
tooltip: layersLabel,
ariaLabel: layersLabel,
section: 'top' as const,
order: 56.3,
active: isLayerSidebarVisible,
onClick: () => {
viewer.toggleLayerSidebar();
}
}] : []),
{
id: 'viewer-toggle-comments',
icon: <LocalIcon icon="comment" width="1.5rem" height="1.5rem" />,
@@ -438,8 +424,6 @@ export function useViewerRightRailButtons(
isThumbnailSidebarVisible,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
hasLayers,
isSearchInterfaceVisible,
isPanning,
searchLabel,
@@ -450,7 +434,6 @@ export function useViewerRightRailButtons(
sidebarLabel,
bookmarkLabel,
attachmentLabel,
layersLabel,
printLabel,
tooltipPosition,
annotationsLabel,
@@ -114,12 +114,6 @@ export const NavigationProvider: React.FC<{
const setWorkbench = useCallback((workbench: WorkbenchType) => {
// Check for unsaved changes using registered checker or state
const hasUnsavedChanges = unsavedChangesCheckerRef.current?.() || state.hasUnsavedChanges;
console.log('[NavigationContext] setWorkbench:', {
from: state.workbench,
to: workbench,
hasChecker: !!unsavedChangesCheckerRef.current,
hasUnsavedChanges
});
// If we're leaving pageEditor, viewer, or custom workbench and have unsaved changes, request navigation
const leavingWorkbenchWithChanges =
@@ -134,16 +128,9 @@ export const NavigationProvider: React.FC<{
}
const performWorkbenchChange = () => {
// When leaving a custom workbench, clear the selected tool
console.log('[NavigationContext] performWorkbenchChange executing', {
from: state.workbench,
to: workbench,
isCustom: state.workbench.startsWith('custom:')
});
if (state.workbench.startsWith('custom:')) {
console.log('[NavigationContext] Clearing tool and changing workbench to:', workbench);
dispatch({ type: 'SET_TOOL_AND_WORKBENCH', payload: { toolId: null, workbench } });
} else {
console.log('[NavigationContext] Just changing workbench to:', workbench);
dispatch({ type: 'SET_WORKBENCH', payload: { workbench } });
}
};
@@ -206,19 +193,13 @@ export const NavigationProvider: React.FC<{
}, [state.hasUnsavedChanges]);
const confirmNavigation = useCallback(() => {
console.log('[NavigationContext] confirmNavigation called', {
hasPendingNav: !!state.pendingNavigation,
currentWorkbench: state.workbench,
currentTool: state.selectedTool
});
if (state.pendingNavigation) {
state.pendingNavigation();
}
dispatch({ type: 'SET_PENDING_NAVIGATION', payload: { navigationFn: null } });
dispatch({ type: 'SHOW_NAVIGATION_WARNING', payload: { show: false } });
console.log('[NavigationContext] confirmNavigation completed');
}, [state.pendingNavigation, state.workbench, state.selectedTool]);
}, [state.pendingNavigation]);
const cancelNavigation = useCallback(() => {
dispatch({ type: 'SET_PENDING_NAVIGATION', payload: { navigationFn: null } });
@@ -3,7 +3,7 @@
* Eliminates prop drilling with a single, simple context
*/
import React, { createContext, useContext, useReducer, useCallback, useMemo, useEffect } from 'react';
import React, { createContext, useContext, useReducer, useCallback, useMemo, useEffect, useRef } from 'react';
import { useToolManagement, type ToolAvailabilityMap } from '@app/hooks/useToolManagement';
import { PageEditorFunctions } from '@app/types/pageEditor';
import { ToolRegistryEntry, ToolRegistry } from '@app/data/toolsTaxonomy';
@@ -117,6 +117,12 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
// Navigation actions and state are available since we're inside NavigationProvider
const { actions } = useNavigationActions();
const navigationState = useNavigationState();
const workbenchRef = useRef(navigationState.workbench);
const actionsRef = useRef(actions);
useEffect(() => {
workbenchRef.current = navigationState.workbench;
actionsRef.current = actions;
});
// Tool management hook
const { toolRegistry, getSelectedTool, toolAvailability } = useToolManagement();
@@ -198,10 +204,10 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
return updated;
});
if (removedView && navigationState.workbench === removedView.workbenchId) {
actions.setWorkbench(getDefaultWorkbench());
if (removedView && workbenchRef.current === removedView.workbenchId) {
actionsRef.current.setWorkbench(getDefaultWorkbench());
}
}, [actions, navigationState.workbench]);
}, []); // stable — uses refs for mutable values
const setCustomWorkbenchViewData = useCallback((id: string, dataOrUpdater: any | ((prev: any) => any)) => {
setCustomViewData(prev => {
@@ -242,9 +248,9 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
const currentCustomView = customWorkbenchViews.find(view => view.workbenchId === navigationState.workbench);
if (!currentCustomView || currentCustomView.data == null) {
actions.setWorkbench(getDefaultWorkbench());
actionsRef.current.setWorkbench(getDefaultWorkbench());
}
}, [actions, customWorkbenchViews, navigationState.workbench, navigationState.pendingNavigation, navigationState.showNavigationWarning]);
}, [customWorkbenchViews, navigationState.workbench, navigationState.pendingNavigation, navigationState.showNavigationWarning]);
// Persisted via PreferencesContext; no direct localStorage writes needed here
@@ -86,10 +86,6 @@ export interface ViewerContextType {
toggleBookmarkSidebar: () => void;
isAttachmentSidebarVisible: boolean;
toggleAttachmentSidebar: () => void;
isLayerSidebarVisible: boolean;
toggleLayerSidebar: () => void;
hasLayers: boolean;
setHasLayers: (value: boolean) => void;
isCommentsSidebarVisible: boolean;
setCommentsSidebarVisible: (visible: boolean) => void;
toggleCommentsSidebar: () => void;
@@ -192,8 +188,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
const [isThumbnailSidebarVisible, setIsThumbnailSidebarVisible] = useState(false);
const [isBookmarkSidebarVisible, setIsBookmarkSidebarVisible] = useState(false);
const [isAttachmentSidebarVisible, setIsAttachmentSidebarVisible] = useState(false);
const [isLayerSidebarVisible, setIsLayerSidebarVisible] = useState(false);
const [hasLayers, setHasLayers] = useState(false);
const [isCommentsSidebarVisible, setIsCommentsSidebarVisible] = useState(false);
const [highlightCommentRequest, setHighlightCommentRequest] = useState<{
documentId: string;
@@ -295,10 +289,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
setIsAttachmentSidebarVisible(prev => !prev);
};
const toggleLayerSidebar = () => {
setIsLayerSidebarVisible(prev => !prev);
};
const setCommentsSidebarVisible = (visible: boolean) => {
setIsCommentsSidebarVisible(visible);
};
@@ -464,10 +454,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
toggleBookmarkSidebar,
isAttachmentSidebarVisible,
toggleAttachmentSidebar,
isLayerSidebarVisible,
toggleLayerSidebar,
hasLayers,
setHasLayers,
isCommentsSidebarVisible,
setCommentsSidebarVisible,
toggleCommentsSidebar,
@@ -42,7 +42,7 @@ import UnlockPdfForms from "@app/tools/UnlockPdfForms";
import FormFill from "@app/tools/formFill/FormFill";
import RemoveCertificateSign from "@app/tools/RemoveCertificateSign";
import RemoveImage from "@app/tools/RemoveImage";
import CertSign from "@app/tools/CertSign";
import CombinedSign from "@app/tools/CombinedSign";
import TimestampPdf from "@app/tools/TimestampPdf";
import BookletImposition from "@app/tools/BookletImposition";
import Flatten from "@app/tools/Flatten";
@@ -50,7 +50,6 @@ import Rotate from "@app/tools/Rotate";
import PdfTextEditor from "@app/tools/pdfTextEditor/PdfTextEditor";
import ChangeMetadata from "@app/tools/ChangeMetadata";
import Crop from "@app/tools/Crop";
import Sign from "@app/tools/Sign";
import AddText from "@app/tools/AddText";
import AddImage from "@app/tools/AddImage";
import Annotate from "@app/tools/Annotate";
@@ -69,7 +68,6 @@ import { ocrOperationConfig } from "@app/hooks/tools/ocr/useOCROperation";
import { convertOperationConfig } from "@app/hooks/tools/convert/useConvertOperation";
import { removeCertificateSignOperationConfig } from "@app/hooks/tools/removeCertificateSign/useRemoveCertificateSignOperation";
import { changePermissionsOperationConfig } from "@app/hooks/tools/changePermissions/useChangePermissionsOperation";
import { certSignOperationConfig } from "@app/hooks/tools/certSign/useCertSignOperation";
import { timestampPdfOperationConfig } from "@app/hooks/tools/timestampPdf/useTimestampPdfOperation";
import { bookletImpositionOperationConfig } from "@app/hooks/tools/bookletImposition/useBookletImpositionOperation";
import { mergeOperationConfig } from '@app/hooks/tools/merge/useMergeOperation';
@@ -113,7 +111,6 @@ import MergeSettings from '@app/components/tools/merge/MergeSettings';
import AdjustPageScaleSettings from "@app/components/tools/adjustPageScale/AdjustPageScaleSettings";
import ScannerImageSplitSettings from "@app/components/tools/scannerImageSplit/ScannerImageSplitSettings";
import ChangeMetadataSingleStep from "@app/components/tools/changeMetadata/ChangeMetadataSingleStep";
import SignSettings from "@app/components/tools/sign/SignSettings";
import AddPageNumbers from "@app/tools/AddPageNumbers";
import RemoveAnnotations from "@app/tools/RemoveAnnotations";
import PageLayoutSettings from "@app/components/tools/pageLayout/PageLayoutSettings";
@@ -123,7 +120,6 @@ import ExtractImagesSettings from "@app/components/tools/extractImages/ExtractIm
import ExtractPagesSettings from "@app/components/tools/extractPages/ExtractPagesSettings";
import ReplaceColorSettings from "@app/components/tools/replaceColor/ReplaceColorSettings";
import AddStampAutomationSettings from "@app/components/tools/addStamp/AddStampAutomationSettings";
import CertSignAutomationSettings from "@app/components/tools/certSign/CertSignAutomationSettings";
import CropAutomationSettings from "@app/components/tools/crop/CropAutomationSettings";
import RotateAutomationSettings from "@app/components/tools/rotate/RotateAutomationSettings";
import SplitAutomationSettings from "@app/components/tools/split/SplitAutomationSettings";
@@ -202,19 +198,6 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
synonyms: getSynonyms(t, "merge")
},
// Signing
certSign: {
icon: <LocalIcon icon="workspace-premium-rounded" width="1.5rem" height="1.5rem" />,
name: t("home.certSign.title", "Certificate Sign"),
component: CertSign,
description: t("home.certSign.desc", "Sign PDF documents using digital certificates"),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.SIGNING,
synonyms: getSynonyms(t, "certSign"),
maxFiles: -1,
endpoints: ["cert-sign"],
operationConfig: certSignOperationConfig,
automationSettings: CertSignAutomationSettings,
},
timestampPdf: {
icon: <LocalIcon icon="schedule-rounded" width="1.5rem" height="1.5rem" />,
name: t("home.timestampPdf.title", "Timestamp PDF"),
@@ -231,15 +214,15 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
sign: {
icon: <LocalIcon icon="signature-rounded" width="1.5rem" height="1.5rem" />,
name: t("home.sign.title", "Sign"),
component: Sign,
description: t("home.sign.desc", "Adds signature to PDF by drawing, text or image"),
component: CombinedSign,
description: t("home.sign.desc", "Sign PDFs with a wet signature, digital certificate, or both"),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.SIGNING,
endpoints: ["sign"],
endpoints: ["sign", "cert-sign"],
operationConfig: signOperationConfig,
automationSettings: SignSettings, // TODO:: not all settings shown, suggested next tools shown
automationSettings: null,
synonyms: getSynonyms(t, "sign"),
supportsAutomate: false, //TODO make support Sign
supportsAutomate: false,
},
addText: {
icon: <LocalIcon icon="text-fields-rounded" width="1.5rem" height="1.5rem" />,
@@ -0,0 +1,78 @@
import { useState, useCallback } from 'react';
import apiClient from '@app/services/apiClient';
import type { SignaturePreview } from '@app/components/viewer/LocalEmbedPDFWithAnnotations';
export interface CombinedSignResult {
blob: Blob;
filename: string;
}
export interface UseCombinedSignOperationReturn {
submitCertSign: (file: File, formData: FormData) => Promise<CombinedSignResult>;
submitWetOnly: (file: File, previews: SignaturePreview[]) => Promise<CombinedSignResult>;
loading: boolean;
}
/**
* Operation hook for the combined sign tool.
*
* - submitCertSign: posts a pre-built FormData to /api/v1/security/cert-sign and
* returns the signed PDF blob.
* - submitWetOnly: sequentially applies each wet-signature preview via
* /api/v1/security/add-signature (one call per signature, chained).
*
* Coordinates from LocalEmbedPDFWithAnnotations are normalised 0-1 fractions;
* both endpoints are expected to accept this format.
*/
export const useCombinedSignOperation = (): UseCombinedSignOperationReturn => {
const [loading, setLoading] = useState(false);
const extractFilename = (headers: any, fallback: string): string => {
const disposition: string = headers['content-disposition'] ?? '';
const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
if (match?.[1]) return match[1].replace(/['"]/g, '');
return fallback;
};
const submitCertSign = useCallback(async (file: File, formData: FormData): Promise<CombinedSignResult> => {
setLoading(true);
try {
const response = await apiClient.post('/api/v1/security/cert-sign', formData, {
responseType: 'blob',
});
const blob = new Blob([response.data], { type: 'application/pdf' });
return { blob, filename: extractFilename(response.headers, `signed_${file.name}`) };
} finally {
setLoading(false);
}
}, []);
const submitWetOnly = useCallback(async (file: File, previews: SignaturePreview[]): Promise<CombinedSignResult> => {
setLoading(true);
try {
let currentFile: File = file;
for (const preview of previews) {
const formData = new FormData();
formData.append('fileInput', currentFile);
formData.append('signatureData', preview.signatureData);
formData.append('signatureType', preview.signatureType);
formData.append('x', preview.x.toString());
formData.append('y', preview.y.toString());
formData.append('width', preview.width.toString());
formData.append('height', preview.height.toString());
formData.append('page', preview.pageIndex.toString());
const response = await apiClient.post('/api/v1/security/add-signature', formData, {
responseType: 'blob',
});
const blob = new Blob([response.data], { type: 'application/pdf' });
currentFile = new File([blob], file.name, { type: 'application/pdf' });
}
return { blob: currentFile, filename: `signed_${file.name}` };
} finally {
setLoading(false);
}
}, []);
return { submitCertSign, submitWetOnly, loading };
};
@@ -1,8 +0,0 @@
export interface FrontendVersionInfo {
appVersion: string | null | undefined; // undefined = not applicable, null = loading, string = loaded
mismatchVersion: boolean;
}
export function useFrontendVersionInfo(_backendVersion: string | undefined): FrontendVersionInfo {
return { appVersion: undefined, mismatchVersion: false };
}
@@ -1,10 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
/**
* Returns whether the shared (group) signing feature is available.
* Core implementation reads directly from server config.
*/
export function useGroupSigningEnabled(): boolean {
const { config } = useAppConfig();
return config?.storageGroupSigningEnabled === true;
}
@@ -1,18 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
export interface SharingEnabledResult {
sharingEnabled: boolean;
shareLinksEnabled: boolean;
}
/**
* Returns whether file-sharing features are available.
* Core implementation reads directly from server config.
*/
export function useSharingEnabled(): SharingEnabledResult {
const { config } = useAppConfig();
return {
sharingEnabled: config?.storageSharingEnabled === true,
shareLinksEnabled: config?.storageShareLinksEnabled === true,
};
}
@@ -1,4 +0,0 @@
// Default implementation for non-desktop environments (overridden in desktop)
export function useViewerKeyCommand(): (event: KeyboardEvent) => boolean {
return () => false;
}
+133
View File
@@ -0,0 +1,133 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Stack, Text } from '@mantine/core';
import OpenInFullIcon from '@mui/icons-material/OpenInFull';
import { createToolFlow } from '@app/components/tools/shared/createToolFlow';
import { useBaseTool } from '@app/hooks/tools/shared/useBaseTool';
import { BaseToolProps, ToolComponent } from '@app/types/tool';
import { useSignParameters, DEFAULT_PARAMETERS } from '@app/hooks/tools/sign/useSignParameters';
import { useSignOperation, signOperationConfig } from '@app/hooks/tools/sign/useSignOperation';
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
import { useNavigationActions, useNavigationState } from '@app/contexts/NavigationContext';
import CombinedSignEditor, { CombinedSignEditorData } from '@app/components/tools/combinedSign/CombinedSignEditor';
import { LocalIcon } from '@app/components/shared/LocalIcon';
const EDITOR_VIEW_ID = 'combinedSignEditor';
const EDITOR_WORKBENCH_ID = 'custom:combinedSignEditor' as const;
const CombinedSign = (props: BaseToolProps) => {
const { t } = useTranslation();
const { actions: navigationActions } = useNavigationActions();
const navigationState = useNavigationState();
const {
registerCustomWorkbenchView,
unregisterCustomWorkbenchView,
setCustomWorkbenchViewData,
clearCustomWorkbenchViewData,
} = useToolWorkflow();
const base = useBaseTool('sign', useSignParameters, useSignOperation, props);
const editorIcon = useMemo(
() => <LocalIcon icon="signature-rounded" width="1rem" height="1rem" />,
[],
);
// Register the full-screen editor as a custom workbench view (once on mount)
useEffect(() => {
registerCustomWorkbenchView({
id: EDITOR_VIEW_ID,
workbenchId: EDITOR_WORKBENCH_ID,
label: t('sign.editor.title', 'Sign Editor'),
icon: editorIcon,
component: CombinedSignEditor,
hideToolPanel: true,
});
return () => {
clearCustomWorkbenchViewData(EDITOR_VIEW_ID);
unregisterCustomWorkbenchView(EDITOR_VIEW_ID);
};
}, [clearCustomWorkbenchViewData, editorIcon, registerCustomWorkbenchView, t, unregisterCustomWorkbenchView]);
const handleOpenEditor = useCallback(() => {
if (base.selectedFiles.length === 0) return;
const file = base.selectedFiles[0]; // StirlingFile extends File — works directly
const editorData: CombinedSignEditorData = {
file,
onComplete: (blob, filename) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
navigationActions.setWorkbench('viewer');
},
onBack: () => {
navigationActions.setWorkbench('viewer');
},
};
setCustomWorkbenchViewData(EDITOR_VIEW_ID, editorData);
navigationActions.setWorkbench(EDITOR_WORKBENCH_ID);
}, [base.selectedFiles, navigationActions, setCustomWorkbenchViewData]);
const isEditorOpen = navigationState.workbench === EDITOR_WORKBENCH_ID;
return createToolFlow({
files: {
selectedFiles: base.selectedFiles,
isCollapsed: isEditorOpen,
},
steps: base.selectedFiles.length > 0
? [
{
title: t('sign.editor.openStep', 'Open Sign Editor'),
isCollapsed: false,
content: (
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t(
'sign.editor.hint',
'Open the editor to place wet signatures, apply a digital certificate, or both.',
)}
</Text>
<Button
leftSection={<OpenInFullIcon fontSize="small" />}
onClick={handleOpenEditor}
disabled={base.endpointLoading || isEditorOpen}
>
{t('sign.editor.open', 'Open Sign Editor')}
</Button>
</Stack>
),
},
]
: [],
executeButton: {
text: t('sign.editor.open', 'Open Sign Editor'),
loadingText: t('loading', 'Loading...'),
onClick: async () => handleOpenEditor(),
isVisible: false,
endpointEnabled: base.endpointEnabled,
paramsValid: true,
},
review: {
isVisible: false,
operation: base.operation,
title: '',
onUndo: base.handleUndo,
},
});
};
const CombinedSignTool = CombinedSign as ToolComponent;
CombinedSignTool.tool = () => useSignOperation;
CombinedSignTool.getDefaultParameters = () => ({ ...DEFAULT_PARAMETERS });
export default CombinedSignTool;
-1
View File
@@ -7,7 +7,6 @@ import {
export type ToolKind = 'regular' | 'super' | 'link';
export const CORE_REGULAR_TOOL_IDS = [
'certSign',
'sign',
'addText',
'addPassword',
-42
View File
@@ -97,45 +97,3 @@ export function isPdfFile(file: { name?: string; type?: string } | File | Blob |
return false;
}
export type NonPdfFileType = 'image' | 'csv' | 'json' | 'text' | 'markdown' | 'html' | 'unknown';
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff', 'tif', 'webp']);
const CSV_EXTENSIONS = new Set(['csv', 'tsv']);
const JSON_EXTENSIONS = new Set(['json']);
const TEXT_EXTENSIONS = new Set(['txt']);
const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']);
const HTML_EXTENSIONS = new Set(['html', 'htm']);
/**
* Detects the non-PDF file type category for viewer routing.
* Returns 'unknown' for PDFs or unrecognized formats.
*/
export function detectNonPdfFileType(file: { name?: string; type?: string } | File | null | undefined): NonPdfFileType {
if (!file) return 'unknown';
const name = 'name' in file ? file.name : undefined;
const mimeType = file.type ?? '';
// Check MIME type first
if (mimeType.startsWith('image/')) return 'image';
if (mimeType === 'text/csv') return 'csv';
if (mimeType === 'text/tab-separated-values') return 'csv';
if (mimeType === 'application/json') return 'json';
if (mimeType === 'text/html') return 'html';
if (mimeType === 'text/markdown') return 'markdown';
// Fall back to extension
if (name) {
const ext = detectFileExtension(name);
if (IMAGE_EXTENSIONS.has(ext)) return 'image';
if (CSV_EXTENSIONS.has(ext)) return 'csv';
if (JSON_EXTENSIONS.has(ext)) return 'json';
if (MARKDOWN_EXTENSIONS.has(ext)) return 'markdown';
if (TEXT_EXTENSIONS.has(ext)) return 'text';
if (HTML_EXTENSIONS.has(ext)) return 'html';
}
return 'unknown';
}
+2 -2
View File
@@ -38,8 +38,8 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {
'/add-password': 'addPassword',
'/remove-password': 'removePassword',
'/change-permissions': 'changePermissions',
'/cert-sign': 'certSign',
'/manage-signatures': 'certSign',
'/cert-sign': 'sign',
'/manage-signatures': 'sign',
'/remove-certificate-sign': 'removeCertSign',
'/remove-cert-sign': 'removeCertSign',
'/unlock-pdf-forms': 'unlockPDFForms',
@@ -1,44 +0,0 @@
import { useState, useEffect } from "react";
import { getVersion } from "@tauri-apps/api/app";
import type { FrontendVersionInfo } from "@core/hooks/useFrontendVersionInfo";
export function useFrontendVersionInfo(backendVersion: string | undefined): FrontendVersionInfo {
const [appVersion, setAppVersion] = useState<string | null>(null);
const [mismatchVersion, setMismatchVersion] = useState(false);
useEffect(() => {
let cancelled = false;
const fetchVersion = async () => {
try {
const version = await getVersion();
if (!cancelled) {
setAppVersion(version);
}
} catch (error) {
console.error("[useFrontendVersionInfo] Failed to fetch frontend version:", error);
}
};
fetchVersion();
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (!appVersion || !backendVersion) {
setMismatchVersion(false);
return;
}
if (appVersion !== backendVersion) {
console.warn("[useFrontendVersionInfo] Mismatch between frontend version and AppConfig version:", {
backendVersion,
frontendVersion: appVersion,
});
setMismatchVersion(true);
} else {
setMismatchVersion(false);
}
}, [appVersion, backendVersion]);
return { appVersion, mismatchVersion };
}
@@ -1,12 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useSelfHostedAuth } from '@app/hooks/useSelfHostedAuth';
/**
* Desktop override: shared (group) signing requires self-hosted mode AND
* an authenticated session. Returns false in SaaS/local mode or when logged out.
*/
export function useGroupSigningEnabled(): boolean {
const { config } = useAppConfig();
const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
return isSelfHosted && isAuthenticated && config?.storageGroupSigningEnabled === true;
}
@@ -1,41 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { authService } from '@app/services/authService';
import { connectionModeService } from '@app/services/connectionModeService';
export interface SelfHostedAuthState {
isSelfHosted: boolean;
isAuthenticated: boolean;
}
/**
* Tracks whether the desktop app is in self-hosted mode with an active
* authenticated session. Refetches app config when the mode first transitions
* to selfhosted, since the jwt-available config fetch fires against the local
* bundled backend before the SetupWizard has switched the mode.
*/
export function useSelfHostedAuth(): SelfHostedAuthState {
const { refetch } = useAppConfig();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isSelfHosted, setIsSelfHosted] = useState(false);
const wasSelfHosted = useRef(false);
useEffect(() => {
void connectionModeService.getCurrentMode().then(mode => setIsSelfHosted(mode === 'selfhosted'));
return connectionModeService.subscribeToModeChanges(cfg => setIsSelfHosted(cfg.mode === 'selfhosted'));
}, []);
useEffect(() => {
void authService.isAuthenticated().then(setIsAuthenticated);
return authService.subscribeToAuth(status => setIsAuthenticated(status === 'authenticated'));
}, []);
useEffect(() => {
if (isSelfHosted && !wasSelfHosted.current) {
void refetch();
}
wasSelfHosted.current = isSelfHosted;
}, [isSelfHosted, refetch]);
return { isSelfHosted, isAuthenticated };
}
@@ -1,18 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useSelfHostedAuth } from '@app/hooks/useSelfHostedAuth';
import type { SharingEnabledResult } from '@core/hooks/useSharingEnabled';
/**
* Desktop override: file-sharing features require self-hosted mode AND an
* authenticated session. Returns false for both in SaaS/local mode or when
* logged out.
*/
export function useSharingEnabled(): SharingEnabledResult {
const { config } = useAppConfig();
const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
const allowed = isSelfHosted && isAuthenticated;
return {
sharingEnabled: allowed && config?.storageSharingEnabled === true,
shareLinksEnabled: allowed && config?.storageShareLinksEnabled === true,
};
}
@@ -1,20 +0,0 @@
import { useViewer } from "@app/contexts/ViewerContext"
import { useCallback } from "react";
export function useViewerKeyCommand(): (event: KeyboardEvent) => boolean {
const { rotationActions } = useViewer();
return useCallback((event:KeyboardEvent): boolean => {
switch (event.key) {
case 'r':
case 'R':
event.preventDefault();
if (event.shiftKey) {
rotationActions.rotateBackward();
} else {
rotationActions.rotateForward();
}
return true;
}
return false;
}, [rotationActions]);
}
@@ -218,26 +218,48 @@ class TauriHttpClient {
const response = await fetch(url, fetchOptions);
// Parse response based on responseType
let data: T;
const responseType = finalConfig.responseType || 'json';
if (responseType === 'json') {
data = await response.json() as T;
} else if (responseType === 'text') {
data = (await response.text()) as T;
} else if (responseType === 'blob') {
// Standard fetch doesn't set blob.type from Content-Type header (unlike axios)
// Set it manually to match axios behavior
const blob = await response.blob();
if (!blob.type) {
const contentType = response.headers.get('content-type') || 'application/octet-stream';
data = new Blob([blob], { type: contentType }) as T;
} else {
data = blob as T;
}
} else if (responseType === 'arraybuffer') {
data = (await response.arrayBuffer()) as T;
} else {
data = await response.json() as T;
}
// Convert Headers to plain object
const responseHeaders: Record<string, string> = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
// Check for HTTP errors BEFORE reading the body so that a plain-text error
// response from the server doesn't cause a JSON parse failure that gets
// misreported as ERR_NETWORK.
if (!response.ok) {
// Read the body as text to surface the real server error message
let errorBody: string;
try {
errorBody = await response.text();
} catch {
errorBody = '';
}
const httpResponse: TauriHttpResponse<T> = {
data,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
// Check for HTTP errors
if (!response.ok) {
// Create more descriptive error messages based on status code
let errorMessage = errorBody || `Request failed with status code ${response.status}`;
let errorMessage = `Request failed with status code ${response.status}`;
let errorCode = 'ERR_BAD_REQUEST';
if (response.status === 401) {
@@ -262,22 +284,13 @@ class TauriHttpClient {
method,
status: response.status,
statusText: response.statusText,
body: errorBody,
});
const errorResponse: TauriHttpResponse<T> = {
data: errorBody as T,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
const error = this.createError(
errorMessage,
finalConfig,
errorCode,
errorResponse
httpResponse
);
// Run error interceptors
@@ -294,39 +307,6 @@ class TauriHttpClient {
throw finalError;
}
// Parse response body for successful responses
let data: T;
const responseType = finalConfig.responseType || 'json';
if (responseType === 'json') {
const text = await response.text();
data = (text ? JSON.parse(text) : null) as T;
} else if (responseType === 'text') {
data = (await response.text()) as T;
} else if (responseType === 'blob') {
// Standard fetch doesn't set blob.type from Content-Type header (unlike axios)
// Set it manually to match axios behavior
const blob = await response.blob();
if (!blob.type) {
const contentType = response.headers.get('content-type') || 'application/octet-stream';
data = new Blob([blob], { type: contentType }) as T;
} else {
data = blob as T;
}
} else if (responseType === 'arraybuffer') {
data = (await response.arrayBuffer()) as T;
} else {
data = await response.json() as T;
}
const httpResponse: TauriHttpResponse<T> = {
data,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
// Run response interceptors
let finalResponse = httpResponse;
for (const handler of this.interceptors.response.handlers) {
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { springAuth } from '@app/auth/springAuthClient';
import { startOAuthNavigation } from '@app/extensions/oauthNavigation';
import apiClient from '@app/services/apiClient';
import { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
import { AxiosError } from 'axios';
// Mock apiClient
vi.mock('@app/services/apiClient');
@@ -45,7 +45,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: { user: mockUser },
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.getSession();
@@ -74,7 +74,7 @@ describe('SpringAuthClient', () => {
statusText: 'Unauthorized',
data: {},
headers: {},
config: {} as InternalAxiosRequestConfig,
config: {} as any,
}
);
@@ -102,7 +102,7 @@ describe('SpringAuthClient', () => {
statusText: 'Forbidden',
data: {},
headers: {},
config: {} as InternalAxiosRequestConfig,
config: {} as any,
}
);
@@ -141,7 +141,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as unknown as AxiosResponse);
} as any);
// Spy on window.dispatchEvent
const dispatchEventSpy = vi.spyOn(window, 'dispatchEvent');
@@ -208,7 +208,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: { user: mockUser },
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.signUp(credentials);
@@ -259,7 +259,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: {},
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.signOut();
@@ -308,7 +308,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.refreshSession();
@@ -85,7 +85,7 @@ export interface User {
is_anonymous?: boolean;
isFirstLogin?: boolean;
authenticationType?: string;
app_metadata?: Record<string, unknown>;
app_metadata?: Record<string, any>;
}
export interface Session {
@@ -447,7 +447,7 @@ class SpringAuthClient {
*/
async signInWithOAuth(params: {
provider: OAuthProvider;
options?: { redirectTo?: string; queryParams?: Record<string, string> };
options?: { redirectTo?: string; queryParams?: Record<string, any> };
}): Promise<{ error: AuthError | null }> {
try {
const redirectPath = normalizeRedirectPath(params.options?.redirectTo);
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
ActionIcon,
@@ -126,10 +125,8 @@ export default function ChangeUserPasswordModal({ opened, onClose, user, onSucce
alert({ alertType: 'success', title: t('workspace.people.changePassword.success', 'Password updated successfully') });
onSuccess();
handleClose();
} catch (error: unknown) {
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.changePassword.error', 'Failed to update password');
} catch (error: any) {
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.changePassword.error', 'Failed to update password');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -12,7 +12,7 @@ interface TextDividerProps {
export default function DividerWithText({ text, className = '', style, variant = 'default', respondsToDarkMode = true, opacity }: TextDividerProps) {
const variantClass = variant === 'subcategory' ? 'subcategory' : '';
const themeClass = respondsToDarkMode ? '' : 'force-light';
const styleWithOpacity = opacity !== undefined ? { ...(style || {}), ['--text-divider-opacity' as string]: opacity } : style;
const styleWithOpacity = opacity !== undefined ? { ...(style || {}), ['--text-divider-opacity' as any]: opacity } : style;
if (text) {
return (
@@ -1,5 +1,4 @@
import { useState, useEffect, useRef } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Modal,
@@ -159,11 +158,9 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
forceChange: false,
forceMFA: false,
});
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to invite user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.addMember.error');
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.addMember.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -214,11 +211,12 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
body: response.errors || response.error
});
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to invite users:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.emailInvite.error', 'Failed to send invites');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.emailInvite.error', 'Failed to send invites');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -241,11 +239,9 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
if (inviteLinkForm.sendEmail && inviteLinkForm.email) {
alert({ alertType: 'success', title: t('workspace.people.inviteLink.emailSent', 'Invite link generated and sent via email') });
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to generate invite link:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.inviteLink.error', 'Failed to generate invite link');
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.inviteLink.error', 'Failed to generate invite link');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -34,12 +34,12 @@ export const ManageBillingButton: React.FC<ManageBillingButtonProps> = ({
// Open billing portal in new tab
window.open(response.url, '_blank');
setLoading(false);
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: (error instanceof Error ? error.message : undefined) || 'Please try again or contact support.',
body: error.message || 'Please try again or contact support.',
});
setLoading(false);
}
@@ -86,7 +86,7 @@ const UpgradeBanner: React.FC = () => {
const scenarioProvidesInfo =
scenarioKey && scenarioKey !== 'unknown' && scenarioKey !== 'licensed';
const derivedIsAdmin = scenarioProvidesInfo
? scenarioKey.includes('admin')
? scenarioKey!.includes('admin')
: isAdmin;
const derivedHasPaidLicense =
scenarioKey === 'licensed'
@@ -95,10 +95,10 @@ const UpgradeBanner: React.FC = () => {
? hasPaidLicense
: false;
const derivedIsUnderLimit = scenarioProvidesInfo
? scenarioKey.includes('under-limit')
? scenarioKey!.includes('under-limit')
: isUnderLimit === true;
const derivedIsOverLimit = scenarioProvidesInfo
? scenarioKey.includes('over-limit')
? scenarioKey!.includes('over-limit')
: isOverLimit === true;
const effectiveIsAdmin = scenario
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import { NumberInput, Switch, Button, Stack, Paper, Text, Loader, Group, Accordion, TextInput, MultiSelect } from '@mantine/core';
import { alert } from '@app/components/toast';
@@ -73,7 +72,7 @@ export default function AdminAdvancedSection() {
isFieldPending,
} = useAdminSettings<AdvancedSettingsData>({
sectionName: 'advanced',
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, any> }> => {
const [systemResponse, processExecutorResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/system'),
apiClient.get('/api/v1/admin/settings/section/processExecutor')
@@ -82,7 +81,7 @@ export default function AdminAdvancedSection() {
const systemData = systemResponse.data || {};
const processExecutorData = processExecutorResponse.data || {};
const result: AdvancedSettingsData & { _pending?: Record<string, unknown> } = {
const result: AdvancedSettingsData & { _pending?: Record<string, any> } = {
enableAlphaFunctionality: systemData.enableAlphaFunctionality || false,
maxDPI: systemData.maxDPI || 0,
enableUrlToPDF: systemData.enableUrlToPDF || false,
@@ -102,7 +101,7 @@ export default function AdminAdvancedSection() {
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (systemData._pending?.enableAlphaFunctionality !== undefined) {
pendingBlock.enableAlphaFunctionality = systemData._pending.enableAlphaFunctionality;
}
@@ -132,7 +131,7 @@ export default function AdminAdvancedSection() {
return result;
},
saveTransformer: (settings) => {
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
'system.enableAlphaFunctionality': settings.enableAlphaFunctionality,
'system.maxDPI': settings.maxDPI,
'system.enableUrlToPDF': settings.enableUrlToPDF,
@@ -282,8 +281,9 @@ export default function AdminAdvancedSection() {
setManualDownloadLinks([]);
} catch (error) {
console.error('[AdminAdvancedSection] Download tessdata languages failed', error);
const status = isAxiosError(error) ? error.response?.status : undefined;
const serverMessage = isAxiosError(error) ? error.response?.data?.message : undefined;
const response = (error as any)?.response;
const status = response?.status;
const serverMessage = response?.data?.message;
if (status === 403) {
console.warn('[AdminAdvancedSection] Tessdata directory not writable, falling back to manual download:', serverMessage);
@@ -309,12 +309,12 @@ export default function AdminAdvancedSection() {
}
let message: string;
if (!isAxiosError(error) || !error.response) {
if (!response) {
message = t(
'admin.settings.advanced.tessdataDir.downloadErrorNetwork',
'Download failed due to a network error. Please check your connection and try again.'
);
} else if (status !== undefined && status >= 500) {
} else if (status >= 500) {
message = t(
'admin.settings.advanced.tessdataDir.downloadErrorServer',
'The server encountered an error while downloading tessdata languages. Please try again later.'
@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { Tabs, Loader, Alert, Stack, Text, Button, Accordion } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -36,9 +35,9 @@ const AdminAuditSection: React.FC = () => {
setError(null);
const status = await auditService.getSystemStatus();
setSystemStatus(status);
} catch (err: unknown) {
} catch (err: any) {
// Check if this is a permission/license error (403/404)
const status = isAxiosError(err) ? err.response?.status : undefined;
const status = err?.response?.status;
if (status === 403 || status === 404) {
setError('enterprise-license-required');
} else {
@@ -44,66 +44,6 @@ interface TelegramSettingsData {
feedback?: FeedbackSettings;
}
interface MailSettings {
enabled?: boolean;
enableInvites?: boolean;
host?: string;
port?: number;
username?: string;
password?: string;
from?: string;
}
interface GoogleDriveSettings {
enabled?: boolean;
clientId?: string;
apiKey?: string;
appId?: string;
}
interface OAuth2GenericSettings {
enabled?: boolean;
provider?: string;
issuer?: string;
clientId?: string;
clientSecret?: string;
scopes?: string;
useAsUsername?: string;
autoCreateUser?: boolean;
blockRegistration?: boolean;
}
interface Saml2Settings {
enabled?: boolean;
provider?: string;
registrationId?: string;
idpMetadataUri?: string;
idpSingleLoginUrl?: string;
idpSingleLogoutUrl?: string;
idpIssuer?: string;
idpCert?: string;
privateKey?: string;
spCert?: string;
autoCreateUser?: boolean;
blockRegistration?: boolean;
}
interface OAuth2ClientSettings {
clientId?: string;
clientSecret?: string;
scopes?: string;
useAsUsername?: string;
issuer?: string;
}
type ProviderSettings =
| MailSettings
| TelegramSettingsData
| GoogleDriveSettings
| OAuth2GenericSettings
| Saml2Settings
| OAuth2ClientSettings;
interface ConnectionsSettingsData {
oauth2?: {
enabled?: boolean;
@@ -115,10 +55,22 @@ interface ConnectionsSettingsData {
blockRegistration?: boolean;
useAsUsername?: string;
scopes?: string;
client?: Record<string, OAuth2ClientSettings>;
client?: {
[key: string]: any;
};
};
saml2?: {
[key: string]: any;
};
mail?: {
enabled?: boolean;
enableInvites?: boolean;
host?: string;
port?: number;
username?: string;
password?: string;
from?: string;
};
saml2?: Saml2Settings;
mail?: MailSettings;
telegram?: TelegramSettingsData;
ssoAutoLogin?: boolean;
enableMobileScanner?: boolean;
@@ -141,7 +93,7 @@ export default function AdminConnectionsSection() {
const adminSettings = useAdminSettings<ConnectionsSettingsData>({
sectionName: 'connections',
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, any> }> => {
// Fetch security settings (oauth2, saml2)
const securityResponse = await apiClient.get('/api/v1/admin/settings/section/security');
const securityData = securityResponse.data || {};
@@ -162,7 +114,7 @@ export default function AdminConnectionsSection() {
const systemResponse = await apiClient.get('/api/v1/admin/settings/section/system');
const systemData = systemResponse.data || {};
const result: ConnectionsSettingsData & { _pending?: Record<string, unknown> } = {
const result: ConnectionsSettingsData & { _pending?: Record<string, any> } = {
oauth2: securityData.oauth2 || {},
saml2: securityData.saml2 || {},
mail: mailData || {},
@@ -180,7 +132,7 @@ export default function AdminConnectionsSection() {
};
// Merge pending blocks from all endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (securityData._pending?.oauth2) {
pendingBlock.oauth2 = securityData._pending.oauth2;
}
@@ -231,13 +183,13 @@ export default function AdminConnectionsSection() {
return result;
},
saveTransformer: (currentSettings: ConnectionsSettingsData) => {
const deltaSettings: Record<string, unknown> = {};
const deltaSettings: Record<string, any> = {};
// Build delta for oauth2 settings
if (currentSettings.oauth2) {
Object.keys(currentSettings.oauth2).forEach((key) => {
if (key !== 'client') {
deltaSettings[`security.oauth2.${key}`] = (currentSettings.oauth2 as Record<string, unknown>)[key];
deltaSettings[`security.oauth2.${key}`] = (currentSettings.oauth2 as Record<string, any>)[key];
}
});
@@ -245,7 +197,7 @@ export default function AdminConnectionsSection() {
const oauth2Client = currentSettings.oauth2.client;
if (oauth2Client) {
Object.keys(oauth2Client).forEach((providerId) => {
const providerSettings = oauth2Client[providerId] as Record<string, unknown>;
const providerSettings = oauth2Client[providerId];
Object.keys(providerSettings).forEach((key) => {
deltaSettings[`security.oauth2.client.${providerId}.${key}`] = providerSettings[key];
});
@@ -255,25 +207,22 @@ export default function AdminConnectionsSection() {
// Build delta for saml2 settings
if (currentSettings.saml2) {
const saml2 = currentSettings.saml2 as Record<string, unknown>;
Object.keys(saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = saml2[key];
Object.keys(currentSettings.saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = (currentSettings.saml2 as Record<string, any>)[key];
});
}
// Mail settings
if (currentSettings.mail) {
const mail = currentSettings.mail as Record<string, unknown>;
Object.keys(mail).forEach((key) => {
deltaSettings[`mail.${key}`] = mail[key];
Object.keys(currentSettings.mail).forEach((key) => {
deltaSettings[`mail.${key}`] = (currentSettings.mail as Record<string, any>)[key];
});
}
// Telegram settings
if (currentSettings.telegram) {
const telegram = currentSettings.telegram as Record<string, unknown>;
Object.keys(telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = telegram[key];
Object.keys(currentSettings.telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = (currentSettings.telegram as Record<string, any>)[key];
});
}
@@ -383,7 +332,7 @@ export default function AdminConnectionsSection() {
return !!(providerSettings?.clientId);
};
const getProviderSettings = (provider: Provider): ProviderSettings => {
const getProviderSettings = (provider: Provider): Record<string, any> => {
if (provider.id === 'saml2') {
return settings?.saml2 || {};
}
@@ -397,17 +346,17 @@ export default function AdminConnectionsSection() {
}
if (provider.id === 'googledrive') {
const gd: GoogleDriveSettings = {
return {
enabled: settings?.googleDriveEnabled,
clientId: settings?.googleDriveClientId,
apiKey: settings?.googleDriveApiKey,
appId: settings?.googleDriveAppId,
};
return gd;
}
if (provider.id === 'oauth2-generic') {
const generic: OAuth2GenericSettings = {
// Generic OAuth2 settings are at the root oauth2 level
return {
enabled: settings?.oauth2?.enabled,
provider: settings?.oauth2?.provider,
issuer: settings?.oauth2?.issuer,
@@ -418,7 +367,6 @@ export default function AdminConnectionsSection() {
autoCreateUser: settings?.oauth2?.autoCreateUser,
blockRegistration: settings?.oauth2?.blockRegistration,
};
return generic;
}
// Specific OAuth2 provider settings
@@ -438,35 +386,32 @@ export default function AdminConnectionsSection() {
const linkedProviders = allProviders.filter((p) => isProviderConfigured(p));
const availableProviders = allProviders.filter((p) => !isProviderConfigured(p));
const updateProviderSettings = (provider: Provider, updatedSettings: Record<string, unknown>) => {
const updateProviderSettings = (provider: Provider, updatedSettings: Record<string, any>) => {
if (provider.id === 'smtp') {
setSettings({ ...settings, mail: updatedSettings as MailSettings });
setSettings({ ...settings, mail: updatedSettings });
} else if (provider.id === 'telegram') {
setSettings({ ...settings, telegram: updatedSettings as TelegramSettingsData });
setSettings({ ...settings, telegram: updatedSettings });
} else if (provider.id === 'googledrive') {
const gd = updatedSettings as GoogleDriveSettings;
setSettings({
...settings,
googleDriveEnabled: gd.enabled,
googleDriveClientId: gd.clientId,
googleDriveApiKey: gd.apiKey,
googleDriveAppId: gd.appId,
googleDriveEnabled: updatedSettings.enabled,
googleDriveClientId: updatedSettings.clientId,
googleDriveApiKey: updatedSettings.apiKey,
googleDriveAppId: updatedSettings.appId,
});
} else if (provider.id === 'saml2') {
setSettings({ ...settings, saml2: updatedSettings as Saml2Settings });
setSettings({ ...settings, saml2: updatedSettings });
} else if (provider.id === 'oauth2-generic') {
const generic = updatedSettings as OAuth2GenericSettings;
setSettings({ ...settings, oauth2: { ...settings.oauth2, ...generic } });
setSettings({ ...settings, oauth2: updatedSettings });
} else {
// Specific OAuth2 provider
const clientSettings = updatedSettings as OAuth2ClientSettings;
setSettings({
...settings,
oauth2: {
...settings.oauth2,
client: {
...settings.oauth2?.client,
[provider.id]: clientSettings,
[provider.id]: updatedSettings
}
}
});
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { isAxiosError } from "axios";
import { useTranslation } from "react-i18next";
import {
NumberInput,
@@ -69,7 +68,7 @@ export default function AdminDatabaseSection() {
const { settings, setSettings, loading, saving, fetchSettings, saveSettings, isFieldPending } =
useAdminSettings<DatabaseSettingsData>({
sectionName: "database",
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, any> }> => {
const response = await apiClient.get("/api/v1/admin/settings/section/system");
const systemData = response.data || {};
@@ -86,7 +85,7 @@ export default function AdminDatabaseSection() {
};
// Map pending changes from system._pending.datasource to root level
const result: DatabaseSettingsData & { _pending?: Record<string, unknown> } = { ...datasource };
const result: DatabaseSettingsData & { _pending?: Record<string, any> } = { ...datasource };
if (systemData._pending?.datasource) {
result._pending = systemData._pending.datasource;
}
@@ -95,7 +94,7 @@ export default function AdminDatabaseSection() {
},
saveTransformer: (settings: DatabaseSettingsData) => {
// Convert flat settings to dot-notation for delta endpoint
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
"system.datasource.enableCustomDatabase": settings.enableCustomDatabase,
"system.datasource.customDatabaseUrl": settings.customDatabaseUrl,
"system.datasource.username": settings.username,
@@ -142,8 +141,8 @@ export default function AdminDatabaseSection() {
const data = await databaseManagementService.getDatabaseData();
setBackupFiles(data.backupFiles || []);
setDatabaseVersion(data.databaseVersion || null);
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.loadError", "Failed to load database backups"),
@@ -190,8 +189,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.createBackup();
alert({ alertType: "success", title: t("admin.settings.database.backupCreated", "Backup created successfully") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.backupFailed", "Failed to create backup"),
@@ -210,8 +209,8 @@ export default function AdminDatabaseSection() {
alert({ alertType: "success", title: t("admin.settings.database.importSuccess", "Backup imported successfully") });
setUploadFile(null);
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -271,8 +270,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.importFromFileName(fileName);
alert({ alertType: "success", title: t("admin.settings.database.importSuccess", "Backup imported successfully") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -290,8 +289,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.deleteBackup(fileName);
alert({ alertType: "success", title: t("admin.settings.database.deleteSuccess", "Backup deleted") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.deleteFailed", "Failed to delete backup"),
@@ -321,8 +320,8 @@ export default function AdminDatabaseSection() {
link.download = fileName;
document.body.appendChild(link);
link.click();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.downloadFailed", "Failed to download backup"),
@@ -38,11 +38,11 @@ export default function AdminFeaturesSection() {
isFieldPending,
} = useAdminSettings<FeaturesSettingsData>({
sectionName: 'features',
fetchTransformer: async (): Promise<FeaturesSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<FeaturesSettingsData & { _pending?: Record<string, any> }> => {
const systemResponse = await apiClient.get('/api/v1/admin/settings/section/system');
const systemData = systemResponse.data || {};
const result: FeaturesSettingsData & { _pending?: Record<string, unknown> } = {
const result: FeaturesSettingsData & { _pending?: Record<string, any> } = {
serverCertificate: systemData.serverCertificate || {
enabled: true,
organizationName: 'Stirling-PDF',
@@ -59,7 +59,7 @@ export default function AdminFeaturesSection() {
return result;
},
saveTransformer: (settings: FeaturesSettingsData) => {
const deltaSettings: Record<string, unknown> = {};
const deltaSettings: Record<string, any> = {};
if (settings.serverCertificate) {
deltaSettings['system.serverCertificate.enabled'] = settings.serverCertificate.enabled;
@@ -91,7 +91,7 @@ export default function AdminGeneralSection() {
isFieldPending,
} = useAdminSettings<GeneralSettingsData>({
sectionName: 'general',
fetchTransformer: async (): Promise<GeneralSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<GeneralSettingsData & { _pending?: Record<string, any> }> => {
const [uiResponse, systemResponse, premiumResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/ui'),
apiClient.get('/api/v1/admin/settings/section/system'),
@@ -113,7 +113,7 @@ export default function AdminGeneralSection() {
? watchedFoldersDirs
: (pipelinePaths.watchedFoldersDir ? [pipelinePaths.watchedFoldersDir] : []);
const result: GeneralSettingsData & { _pending?: Record<string, unknown> } = {
const result: GeneralSettingsData & { _pending?: Record<string, any> } = {
ui,
system,
customPaths: {
@@ -140,7 +140,7 @@ export default function AdminGeneralSection() {
};
// Merge pending blocks from all three endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (ui._pending) {
pendingBlock.ui = ui._pending;
}
@@ -161,7 +161,7 @@ export default function AdminGeneralSection() {
return result;
},
saveTransformer: (settings: GeneralSettingsData) => {
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
// UI settings
'ui.appNameNavbar': settings.ui?.appNameNavbar,
'ui.languages': settings.ui?.languages,
@@ -72,12 +72,12 @@ const AdminPlanSection: React.FC = () => {
// Open billing portal in new tab
window.open(response.url, '_blank');
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: (error instanceof Error ? error.message : undefined) || 'Please try again or contact support.',
body: error.message || 'Please try again or contact support.',
});
}
}, [licenseInfo, t, validateLoginEnabled]);
@@ -33,7 +33,7 @@ export default function AdminPrivacySection() {
isFieldPending,
} = useAdminSettings<PrivacySettingsData>({
sectionName: 'privacy',
fetchTransformer: async (): Promise<PrivacySettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<PrivacySettingsData & { _pending?: Record<string, any> }> => {
const [metricsResponse, systemResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/metrics'),
apiClient.get('/api/v1/admin/settings/section/system')
@@ -42,14 +42,14 @@ export default function AdminPrivacySection() {
const metrics = metricsResponse.data;
const system = systemResponse.data;
const result: PrivacySettingsData & { _pending?: Record<string, unknown> } = {
const result: PrivacySettingsData & { _pending?: Record<string, any> } = {
enableAnalytics: system.enableAnalytics || false,
googleVisibility: system.googlevisibility || false,
metricsEnabled: metrics.enabled || false
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (system._pending?.enableAnalytics !== undefined) {
pendingBlock.enableAnalytics = system._pending.enableAnalytics;
}
@@ -67,7 +67,7 @@ export default function AdminSecuritySection() {
isFieldPending,
} = useAdminSettings<SecuritySettingsData>({
sectionName: 'security',
fetchTransformer: async (): Promise<SecuritySettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<SecuritySettingsData & { _pending?: Record<string, any> }> => {
const [securityResponse, premiumResponse, systemResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/security'),
apiClient.get('/api/v1/admin/settings/section/premium'),
@@ -93,7 +93,7 @@ export default function AdminSecuritySection() {
systemPending: JSON.parse(JSON.stringify(systemPending || {}))
});
const combined: SecuritySettingsData & { _pending?: Record<string, unknown> } = {
const combined: SecuritySettingsData & { _pending?: Record<string, any> } = {
...securityActive
};
@@ -108,7 +108,7 @@ export default function AdminSecuritySection() {
}
// Merge all _pending blocks
const mergedPending: Record<string, unknown> = {};
const mergedPending: Record<string, any> = {};
if (securityPending) {
Object.assign(mergedPending, securityPending);
}
@@ -128,7 +128,7 @@ export default function AdminSecuritySection() {
saveTransformer: (settings: SecuritySettingsData) => {
const { audit, html, ...securitySettings } = settings;
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
// Security settings
'security.enableLogin': securitySettings.enableLogin,
'security.loginMethod': securitySettings.loginMethod,
@@ -155,10 +155,10 @@ const AdminUsageSection: React.FC = () => {
const displayedVisits = endpoints.reduce((sum, e) => sum + e.visits, 0);
const totalVisits = Number.isFinite(data?.totalVisits)
? Math.max(0, data?.totalVisits ?? 0)
? Math.max(0, data?.totalVisits as number)
: displayedVisits;
const totalEndpoints = Number.isFinite(data?.totalEndpoints)
? Math.max(0, data?.totalEndpoints ?? 0)
? Math.max(0, data?.totalEndpoints as number)
: endpoints.length;
const displayedPercentage = totalVisits > 0
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -18,7 +17,6 @@ import {
CloseButton,
Avatar,
Box,
type ComboboxItem,
} from '@mantine/core';
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
@@ -53,7 +51,6 @@ export default function PeopleSection() {
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [processing, setProcessing] = useState(false);
const [mailEnabled, setMailEnabled] = useState(false);
const [lockedUsers, setLockedUsers] = useState<string[]>([]);
// License information
const [licenseInfo, setLicenseInfo] = useState<{
@@ -83,7 +80,6 @@ export default function PeopleSection() {
: null;
const isCurrentUser = (user: User) => currentUser?.username === user.username;
const isLockedUser = (user: User) => lockedUsers.includes(user.username);
// Form state for edit user modal
const [editForm, setEditForm] = useState({
@@ -116,7 +112,7 @@ export default function PeopleSection() {
...user,
isActive: adminData.userSessions[user.username] || false,
lastRequest: adminData.userLastRequest[user.username] || undefined,
mfaEnabled: (adminData.userSettings?.[user.username] as Record<string, unknown> | undefined)?.mfaEnabled === 'true',
mfaEnabled: adminData.userSettings?.[user.username]?.mfaEnabled === 'true',
}));
setUsers(enrichedUsers);
@@ -132,7 +128,6 @@ export default function PeopleSection() {
totalUsers: adminData.totalUsers,
});
setMailEnabled(adminData.mailEnabled);
setLockedUsers(adminData.lockedUsers || []);
} else {
// Provide example data when login is disabled
const exampleUsers: User[] = [
@@ -194,7 +189,6 @@ export default function PeopleSection() {
setUsers(exampleUsers);
setTeams(exampleTeams);
setMailEnabled(false);
setLockedUsers([]);
// Example license information
setLicenseInfo({
@@ -227,11 +221,12 @@ export default function PeopleSection() {
alert({ alertType: 'success', title: t('workspace.people.editMember.success') });
closeEditModal();
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to update user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.editMember.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.editMember.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -243,11 +238,12 @@ export default function PeopleSection() {
await userManagementService.toggleUserEnabled(user.username, !user.enabled);
alert({ alertType: 'success', title: t('workspace.people.toggleEnabled.success') });
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to toggle user status:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.toggleEnabled.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.toggleEnabled.error');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -262,31 +258,12 @@ export default function PeopleSection() {
await userManagementService.deleteUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.deleteUserSuccess', 'User deleted successfully') });
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to delete user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
}
};
const handleUnlockUser = async (user: User) => {
const confirmMessage = t('workspace.people.confirmUnlock', 'Are you sure you want to unlock this user account?');
if (!window.confirm(`${confirmMessage}\n\nUser: ${user.username}`)) {
return;
}
try {
await userManagementService.unlockUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.unlockUserSuccess', 'User account unlocked successfully') });
fetchData();
} catch (error: unknown) {
console.error('[PeopleSection] Failed to unlock user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.unlockUserError', 'Failed to unlock user account');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -338,9 +315,9 @@ export default function PeopleSection() {
},
];
const renderRoleOption = ({ option }: { option: ComboboxItem & { icon?: string; description?: string } }) => (
const renderRoleOption = ({ option }: { option: any }) => (
<Group gap="sm" wrap="nowrap">
<LocalIcon icon={option.icon ?? ''} width="1.25rem" height="1.25rem" style={{ flexShrink: 0 }} />
<LocalIcon icon={option.icon} width="1.25rem" height="1.25rem" style={{ flexShrink: 0 }} />
<Box style={{ flex: 1 }}>
<Text size="sm" fw={500}>{option.label}</Text>
<Text size="xs" c="dimmed" style={{ whiteSpace: 'normal', lineHeight: 1.4 }}>
@@ -412,12 +389,6 @@ export default function PeopleSection() {
</Text>
)}
{lockedUsers.length > 0 && (
<Badge color="orange" variant="light" size="sm">
{lockedUsers.length} {t('workspace.people.locked', 'locked')}
</Badge>
)}
{licenseInfo.premiumEnabled && licenseInfo.licenseMaxUsers > 0 && (
<Badge color="blue" variant="light" size="sm">
+{licenseInfo.licenseMaxUsers} {t('workspace.people.license.fromLicense', 'from license')}
@@ -526,29 +497,22 @@ export default function PeopleSection() {
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<Group gap={6} wrap="nowrap" align="center">
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{isLockedUser(user) && (
<Badge color="orange" variant="light" size="xs">
{t('workspace.people.lockedBadge', 'Locked')}
</Badge>
)}
</Group>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -648,15 +612,6 @@ export default function PeopleSection() {
{user.enabled ? t('workspace.people.disable') : t('workspace.people.enable')}
</Menu.Item>
)}
{!isCurrentUser(user) && isLockedUser(user) && (
<Menu.Item
leftSection={<LocalIcon icon="lock-open" width="1rem" height="1rem" />}
onClick={() => handleUnlockUser(user)}
disabled={!loginEnabled}
>
{t('workspace.people.unlockAccount', 'Unlock Account')}
</Menu.Item>
)}
{!isCurrentUser(user) && user.mfaEnabled && (
<>
<Menu.Divider />
@@ -667,12 +622,12 @@ export default function PeopleSection() {
try {
await userManagementService.disableMfaByAdmin(user.username);
alert({ alertType: 'success', title: t('workspace.people.mfa.adminDisableSuccess', 'MFA disabled successfully for user') });
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to disable MFA for user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.mfa.adminDisableError', 'Failed to disable MFA for user');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.mfa.adminDisableError', 'Failed to disable MFA for user');
alert({ alertType: 'error', title: errorMessage });
}
}}
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -52,9 +51,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
availableSlots: number;
} | null>(null);
const [mailEnabled, setMailEnabled] = useState(false);
const [lockedUsers, setLockedUsers] = useState<string[]>([]);
const isLockedUser = (user: User) => lockedUsers.includes(user.username);
useEffect(() => {
fetchTeamDetails();
@@ -79,7 +75,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
availableSlots: adminData.availableSlots,
});
setMailEnabled(adminData.mailEnabled);
setLockedUsers(adminData.lockedUsers || []);
} catch (error) {
console.error('Failed to fetch team details:', error);
alert({ alertType: 'error', title: t('workspace.teams.loadError', 'Failed to load team details') });
@@ -111,11 +106,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setAddMemberModalOpened(false);
setSelectedUserId('');
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to add member:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.addMemberToTeam.error', 'Failed to add user to team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.addMemberToTeam.error', 'Failed to add user to team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -140,11 +136,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
await teamService.moveUserToTeam(user.username, user.rolesAsString || 'ROLE_USER', defaultTeam.id);
alert({ alertType: 'success', title: t('workspace.teams.removeMemberSuccess', 'User removed from team') });
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to remove member:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.removeMemberError', 'Failed to remove user from team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.removeMemberError', 'Failed to remove user from team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -162,37 +159,18 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
await userManagementService.deleteUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.deleteUserSuccess', 'User deleted successfully') });
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to delete user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.deleteUserError', 'Failed to delete user');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
}
};
const handleUnlockUser = async (user: User) => {
const confirmMessage = t('workspace.people.confirmUnlock', 'Are you sure you want to unlock this user account?');
if (!window.confirm(`${confirmMessage}\n\nUser: ${user.username}`)) {
return;
}
try {
await userManagementService.unlockUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.unlockUserSuccess', 'User account unlocked successfully') });
fetchTeamDetails();
} catch (error: unknown) {
console.error('[TeamDetailsSection] Failed to unlock user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.unlockUserError', 'Failed to unlock user account');
alert({ alertType: 'error', title: errorMessage });
}
};
const openChangeTeamModal = (user: User) => {
setSelectedUser(user);
setSelectedTeamId(user.team?.id?.toString() || '');
@@ -223,12 +201,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setSelectedUser(null);
setSelectedTeamId('');
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to change team:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.teams.changeTeam.error', 'Failed to change team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.changeTeam.error', 'Failed to change team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -357,29 +335,22 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<Group gap={6} wrap="nowrap" align="center">
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{isLockedUser(user) && (
<Badge color="orange" variant="light" size="xs">
{t('workspace.people.lockedBadge', 'Locked')}
</Badge>
)}
</Group>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -449,15 +420,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
>
{t('workspace.people.changePassword.action', 'Change password')}
</Menu.Item>
{isLockedUser(user) && (
<Menu.Item
leftSection={<LocalIcon icon="lock-open" width="1rem" height="1rem" />}
onClick={() => handleUnlockUser(user)}
disabled={processing}
>
{t('workspace.people.unlockAccount', 'Unlock Account')}
</Menu.Item>
)}
{team.name !== 'Internal' && team.name !== 'Default' && (
<Menu.Item
leftSection={<LocalIcon icon="person-remove" width="1rem" height="1rem" />}
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -84,11 +83,12 @@ export default function TeamsSection() {
setNewTeamName('');
setCreateModalOpened(false);
await fetchTeams();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to create team:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.createTeam.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.createTeam.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -109,11 +109,12 @@ export default function TeamsSection() {
setSelectedTeam(null);
setRenameModalOpened(false);
await fetchTeams();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to rename team:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.renameTeam.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.renameTeam.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -134,12 +135,12 @@ export default function TeamsSection() {
await teamService.deleteTeam(team.id);
alert({ alertType: 'success', title: t('workspace.teams.deleteTeam.success') });
await fetchTeams();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to delete team:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.teams.deleteTeam.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.deleteTeam.error');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -15,7 +15,7 @@ import {
UnstyledButton,
} from '@mantine/core';
import { useTranslation } from 'react-i18next';
import auditService, { AuditEvent, AuditFilters } from '@app/services/auditService';
import auditService, { AuditEvent } from '@app/services/auditService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
import { useAuditFilters } from '@app/hooks/useAuditFilters';
import AuditFiltersForm from '@app/components/shared/config/configSections/audit/AuditFiltersForm';
@@ -122,7 +122,7 @@ const AuditEventsTable: React.FC<AuditEventsTableProps> = ({
}, [filters, currentPage, loginEnabled]);
// Wrap filter handlers to reset pagination
const handleFilterChangeWithReset = (key: keyof AuditFilters, value: AuditFilters[keyof AuditFilters]) => {
const handleFilterChangeWithReset = (key: keyof typeof filters, value: any) => {
handleFilterChange(key, value);
setCurrentPage(1);
};
@@ -170,8 +170,8 @@ const AuditEventsTable: React.FC<AuditEventsTableProps> = ({
// Apply sorting to current events
const sortedEvents = [...events].sort((a, b) => {
let aVal: string | number | undefined;
let bVal: string | number | undefined;
let aVal: any;
let bVal: any;
switch (sortKey) {
case 'timestamp':
@@ -296,14 +296,14 @@ const AuditEventsTable: React.FC<AuditEventsTableProps> = ({
let author = '';
let fileHash = '';
if (event.details && typeof event.details === 'object') {
const details = event.details as Record<string, unknown>;
const details = event.details as Record<string, any>;
const files = details.files;
if (Array.isArray(files) && files.length > 0) {
const firstFile = files[0] as Record<string, unknown>;
documentName = typeof firstFile.name === 'string' ? firstFile.name : '';
const firstFile = files[0] as Record<string, any>;
documentName = firstFile.name || '';
if (showAuthor || showFileHash) {
author = typeof firstFile.pdfAuthor === 'string' ? firstFile.pdfAuthor : '';
fileHash = typeof firstFile.fileHash === 'string' ? firstFile.fileHash.substring(0, 16) + '...' : '';
author = firstFile.pdfAuthor || '';
fileHash = firstFile.fileHash ? firstFile.fileHash.substring(0, 16) + '...' : '';
}
}
}
@@ -51,7 +51,7 @@ const AuditExportSection: React.FC<AuditExportSectionProps> = ({
try {
setExporting(true);
const fieldsParam = Object.keys(selectedFields).filter(k => selectedFields[k]).join(',');
const fieldsParam = Object.keys(selectedFields).filter(k => selectedFields[k as keyof typeof selectedFields]).join(',');
const blob = await auditService.exportData(exportFormat, { ...filters, fields: fieldsParam });
@@ -43,7 +43,7 @@ interface AuditFiltersFormProps {
filters: AuditFilters;
eventTypes: string[];
users: string[];
onFilterChange: (key: keyof AuditFilters, value: AuditFilters[keyof AuditFilters]) => void;
onFilterChange: (key: keyof AuditFilters, value: any) => void;
onClearFilters: () => void;
disabled?: boolean;
}
@@ -147,8 +147,8 @@ const AuditFiltersForm: React.FC<AuditFiltersFormProps> = ({
<DateInput
placeholder={t('audit.events.startDate', 'Start date')}
value={filters.startDate ? new Date(filters.startDate) : null}
onChange={(value) => {
onFilterChange('startDate', value ? formatDateToYMD(new Date(value)) : undefined);
onChange={(value: any) => {
onFilterChange('startDate', value ? formatDateToYMD(value as Date) : undefined);
}}
clearable
disabled={disabled}
@@ -157,8 +157,8 @@ const AuditFiltersForm: React.FC<AuditFiltersFormProps> = ({
<DateInput
placeholder={t('audit.events.endDate', 'End date')}
value={filters.endDate ? new Date(filters.endDate) : null}
onChange={(value) => {
onFilterChange('endDate', value ? formatDateToYMD(new Date(value)) : undefined);
onChange={(value: any) => {
onFilterChange('endDate', value ? formatDateToYMD(value as Date) : undefined);
}}
clearable
disabled={disabled}
@@ -14,7 +14,7 @@ export const useLicensePolling = (
const pollForLicenseKey = useCallback(async (installId: string) => {
// Use shared polling utility
const result = await pollLicenseKeyWithBackoff(installId, {
isMounted: () => isMountedRef.current ?? false,
isMounted: () => isMountedRef.current!,
onStatusChange: setPollingStatus,
});
@@ -23,7 +23,7 @@ export const useLicensePolling = (
// Activate the license key
const activation = await activateLicenseKey(result.licenseKey, {
isMounted: () => isMountedRef.current ?? false,
isMounted: () => isMountedRef.current!,
onActivated: onLicenseActivated,
});
@@ -112,8 +112,8 @@ const ParticipantView: React.FC<ParticipantViewProps> = ({ token }) => {
showLogo: true,
});
setNotification({ type: 'success', message: 'Signature submitted successfully!' });
} catch (err: unknown) {
setNotification({ type: 'error', message: `Failed to submit signature: ${err instanceof Error ? err.message : String(err)}` });
} catch (err: any) {
setNotification({ type: 'error', message: `Failed to submit signature: ${err.message}` });
} finally {
setIsSubmitting(false);
}
@@ -125,8 +125,8 @@ const ParticipantView: React.FC<ParticipantViewProps> = ({ token }) => {
try {
await decline(token, declineReason || 'Declined by participant');
setNotification({ type: 'success', message: 'You have declined this signing request.' });
} catch (err: unknown) {
setNotification({ type: 'error', message: `Failed to decline: ${err instanceof Error ? err.message : String(err)}` });
} catch (err: any) {
setNotification({ type: 'error', message: `Failed to decline: ${err.message}` });
}
}
};
@@ -8,7 +8,6 @@ import {
type ReactNode,
} from 'react';
import apiClient from '@app/services/apiClient';
import { isAxiosError } from 'axios';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useAuth } from '@app/auth/UseSession';
import { useLicense } from '@app/contexts/LicenseContext';
@@ -96,8 +95,13 @@ function getErrorMessage(error: unknown): string {
if (typeof error === 'string') {
return error;
}
if (isAxiosError(error) && typeof error.response?.data?.message === 'string') {
return error.response.data.message;
if (
typeof error === 'object' &&
error !== null &&
'response' in error &&
typeof (error as any).response?.data?.message === 'string'
) {
return (error as any).response.data.message;
}
if (error instanceof Error) {
return error.message;
@@ -192,7 +196,7 @@ export function ServerExperienceProvider({ children }: { children: ReactNode })
(
await apiClient.get<{ totalUsers?: number }>(
'/api/v1/proprietary/ui-data/admin-settings',
{ suppressErrorToast: true },
{ suppressErrorToast: true } as any,
)
).data;
const totalUsers =
@@ -215,7 +219,7 @@ export function ServerExperienceProvider({ children }: { children: ReactNode })
(
await apiClient.get<WeeklyActiveUsersResponse>('/api/v1/info/wau', {
suppressErrorToast: true,
})
} as any)
).data;
const weeklyActiveUsers =
typeof responseData?.weeklyActiveUsers === 'number'
@@ -1,5 +1,4 @@
import { useState, useCallback, useEffect } from 'react';
import { isAxiosError } from 'axios';
import workflowService, {
WorkflowSessionResponse,
ParticipantResponse,
@@ -36,10 +35,9 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
]);
setSession(sessionData);
setParticipant(participantData);
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to load session';
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to load session';
setError(errorMsg);
} finally {
setLoading(false);
@@ -57,10 +55,9 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
if (request.participantToken) {
await loadSession(request.participantToken);
}
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to submit signature';
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to submit signature';
setError(errorMsg);
throw new Error(errorMsg, { cause: err });
} finally {
@@ -82,10 +79,9 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
setParticipant(updatedParticipant);
// Reload session
await loadSession(token);
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to decline';
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to decline';
setError(errorMsg);
throw new Error(errorMsg, { cause: err });
} finally {
@@ -108,10 +104,9 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to download document';
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to download document';
setError(errorMsg);
} finally {
setLoading(false);
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Stack, Text, Paper, Center, Loader, TextInput, PasswordInput, Anchor } from '@mantine/core';
@@ -57,14 +56,14 @@ export default function InviteAccept() {
setLoading(true);
const response = await apiClient.get<InviteData>(`/api/v1/invite/validate/${token}`, {
suppressErrorToast: true,
});
} as any);
setInviteData(response.data);
setError(null);
} catch (err: unknown) {
const errorMessage = isAxiosError(err)
? (err.response?.data?.error || err.message)
: (err instanceof Error ? err.message : undefined) ||
t('invite.validationError', 'Failed to validate invitation link');
} catch (err: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.validationError', 'Failed to validate invitation link');
setError(errorMessage);
} finally {
setLoading(false);
@@ -109,15 +108,15 @@ export default function InviteAccept() {
await apiClient.post(`/api/v1/invite/accept/${token}`, formData, {
suppressErrorToast: true,
});
} as any);
// Success - redirect to login
navigate('/login?messageType=accountCreated');
} catch (err: unknown) {
const errorMessage = isAxiosError(err)
? (err.response?.data?.error || err.message)
: (err instanceof Error ? err.message : undefined) ||
t('invite.acceptError', 'Failed to create account');
} catch (err: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.acceptError', 'Failed to create account');
setError(errorMessage);
} finally {
setSubmitting(false);
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useRef } from 'react';
import { isAxiosError } from 'axios';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import apiClient from '@app/services/apiClient';
@@ -100,7 +99,7 @@ export default function ShareLinkLoader({ token }: ShareLinkLoaderProps) {
const idMap = new Map<string, FileId>();
for (let i = 0; i < stirlingFiles.length; i += 1) {
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId as FileId);
}
const rootIdMap = new Map<string, FileId>();
@@ -200,9 +199,9 @@ export default function ShareLinkLoader({ token }: ShareLinkLoaderProps) {
navActions.setWorkbench('viewer');
navigate('/', { replace: true });
} catch (error: unknown) {
} catch (error: any) {
if (signal.aborted) return;
const status = isAxiosError(error) ? error.response?.status : undefined;
const status = error?.response?.status;
if (status === 401 || status === 403) {
if (!isAuthenticated && !authLoading) {
alert({
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useNavigate, useParams } from 'react-router-dom';
import { Alert, Badge, Button, Group, Loader, Paper, Stack, Text, Title } from '@mantine/core';
import { useTranslation } from 'react-i18next';
@@ -46,8 +45,8 @@ export default function ShareLinkPage() {
const data = await fetchShareLinkMetadata(normalizedToken);
setMetadata(data);
setStatus('ready');
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : undefined;
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
if (statusCode === 401) {
setStatus('login');
} else if (statusCode === 403) {
@@ -84,8 +83,8 @@ export default function ShareLinkPage() {
link.click();
link.remove();
URL.revokeObjectURL(url);
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : undefined;
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
if (statusCode === 401) {
setStatus('login');
} else if (statusCode === 403) {
@@ -119,8 +118,8 @@ export default function ShareLinkPage() {
}
navActions.setWorkbench('viewer');
navigate('/', { replace: true });
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : undefined;
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
if (statusCode === 401) {
setStatus('login');
} else if (statusCode === 403) {
@@ -24,7 +24,7 @@ export interface ShareLinkMetadata {
export async function fetchShareLinkMetadata(token: string): Promise<ShareLinkMetadata> {
const response = await apiClient.get<ShareLinkMetadata>(
`/api/v1/storage/share-links/${token}/metadata`,
{ suppressErrorToast: true, skipAuthRedirect: true }
{ suppressErrorToast: true, skipAuthRedirect: true } as any
);
return response.data || {};
}
@@ -38,7 +38,7 @@ export async function downloadShareLink(token: string): Promise<{
responseType: 'blob',
suppressErrorToast: true,
skipAuthRedirect: true,
});
} as any);
const contentType =
(response.headers && (response.headers['content-type'] || response.headers['Content-Type'])) ||
'';
@@ -73,7 +73,7 @@ export async function importShareLinkToWorkbench(
const idMap = new Map<string, FileId>();
for (let i = 0; i < stirlingFiles.length; i += 1) {
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId as FileId);
}
const rootIdMap = new Map<string, FileId>();
@@ -141,7 +141,7 @@ export async function importShareLinkToWorkbench(
autoUnzip: false,
skipAutoUnzip: false,
});
const ids = stirlingFiles.map((stirlingFile: StirlingFile) => stirlingFile.fileId);
const ids = stirlingFiles.map((stirlingFile: StirlingFile) => stirlingFile.fileId as FileId);
if (ids.length > 0) {
const sharedUpdates = {
remoteStorageId: shareMetadata?.fileId,
@@ -1,5 +1,4 @@
import apiClient from '@app/services/apiClient';
import type { User } from '@app/services/userManagementService';
export interface Team {
id: number;
@@ -26,13 +25,6 @@ export interface TeamDetailsResponse {
availableUsers: TeamMember[];
}
export interface TeamDetailsUIResponse {
team: Team;
teamUsers: User[];
availableUsers: User[];
userLastRequest?: Record<string, number>;
}
/**
* Team Management Service
* Provides functions to interact with team-related backend APIs
@@ -49,8 +41,8 @@ export const teamService = {
/**
* Get team details including members
*/
async getTeamDetails(teamId: number): Promise<TeamDetailsUIResponse> {
const response = await apiClient.get<TeamDetailsUIResponse>(`/api/v1/proprietary/ui-data/teams/${teamId}`);
async getTeamDetails(teamId: number): Promise<any> {
const response = await apiClient.get(`/api/v1/proprietary/ui-data/teams/${teamId}`);
return response.data;
},
@@ -62,7 +54,7 @@ export const teamService = {
formData.append('name', name);
await apiClient.post('/api/v1/team/create', formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -74,7 +66,7 @@ export const teamService = {
formData.append('newName', newName);
await apiClient.post('/api/v1/team/rename', formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -85,7 +77,7 @@ export const teamService = {
formData.append('teamId', teamId.toString());
await apiClient.post('/api/v1/team/delete', formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -97,7 +89,7 @@ export const teamService = {
formData.append('userId', userId.toString());
await apiClient.post('/api/v1/team/addUser', formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -110,6 +102,6 @@ export const teamService = {
formData.append('teamId', teamId.toString());
await apiClient.post('/api/v1/user/admin/changeRole', formData, {
suppressErrorToast: true,
});
} as any);
},
};
@@ -30,7 +30,7 @@ export interface AdminSettingsData {
disabledUsers: number;
currentUsername?: string;
roleDetails?: Record<string, string>;
teams?: unknown[];
teams?: any[];
maxPaidUsers?: number;
// License information
maxAllowedUsers: number;
@@ -39,8 +39,7 @@ export interface AdminSettingsData {
licenseMaxUsers: number;
premiumEnabled: boolean;
mailEnabled: boolean;
userSettings?: Record<string, unknown>;
lockedUsers?: string[];
userSettings?: Record<string, any>;
}
export interface CreateUserRequest {
@@ -155,7 +154,7 @@ export const userManagementService = {
}
await apiClient.post('/api/v1/user/admin/saveUser', formData, {
suppressErrorToast: true, // Component will handle error display
});
} as any);
},
/**
@@ -170,7 +169,7 @@ export const userManagementService = {
}
await apiClient.post('/api/v1/user/admin/changeRole', formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -181,7 +180,7 @@ export const userManagementService = {
formData.append('enabled', enabled.toString());
await apiClient.post(`/api/v1/user/admin/changeUserEnabled/${username}`, formData, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -190,7 +189,7 @@ export const userManagementService = {
async deleteUser(username: string): Promise<void> {
await apiClient.post(`/api/v1/user/admin/deleteUser/${username}`, null, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -211,7 +210,7 @@ export const userManagementService = {
formData,
{
suppressErrorToast: true, // Component will handle error display
}
} as any
);
return response.data;
@@ -245,7 +244,7 @@ export const userManagementService = {
formData,
{
suppressErrorToast: true,
}
} as any
);
return response.data;
@@ -265,7 +264,7 @@ export const userManagementService = {
async revokeInviteLink(inviteId: number): Promise<void> {
await apiClient.delete(`/api/v1/invite/revoke/${inviteId}`, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -300,16 +299,7 @@ export const userManagementService = {
await apiClient.post('/api/v1/user/admin/changePasswordForUser', formData, {
suppressErrorToast: true, // Component will handle error display
});
},
/**
* Unlock a locked user account (admin only)
*/
async unlockUser(username: string): Promise<void> {
await apiClient.post(`/api/v1/user/admin/unlockUser/${username}`, null, {
suppressErrorToast: true,
});
} as any);
},
/**
@@ -37,7 +37,7 @@ export const TOOL_CREDIT_COSTS: Record<ToolId, number> = {
reorganizePages: CREDIT_COSTS.SMALL,
scalePages: CREDIT_COSTS.SMALL,
editTableOfContents: CREDIT_COSTS.SMALL,
sign: CREDIT_COSTS.SMALL,
sign: CREDIT_COSTS.LARGE,
removeAnnotations: CREDIT_COSTS.SMALL,
removeImage: CREDIT_COSTS.SMALL,
scannerImageSplit: CREDIT_COSTS.SMALL,
@@ -76,7 +76,6 @@ export const TOOL_CREDIT_COSTS: Record<ToolId, number> = {
compress: CREDIT_COSTS.LARGE,
convert: CREDIT_COSTS.LARGE,
ocr: CREDIT_COSTS.LARGE,
certSign: CREDIT_COSTS.LARGE,
timestampPdf: CREDIT_COSTS.LARGE,
// Extra large operations (10 credits)
+13 -16
View File
@@ -176,6 +176,13 @@ UNOSERVER_PIDS=()
UNOSERVER_PORTS=()
UNOSERVER_UNO_PORTS=()
SU_EXEC_BIN=""
if command_exists su-exec; then
SU_EXEC_BIN="su-exec"
elif command_exists gosu; then
SU_EXEC_BIN="gosu"
fi
CURRENT_USER="$(id -un)"
CURRENT_UID="$(id -u)"
SWITCH_USER_WARNING_EMITTED=false
@@ -190,8 +197,8 @@ warn_switch_user_once() {
run_as_runtime_user() {
if [ "$CURRENT_USER" = "$RUNTIME_USER" ]; then
"$@"
elif [ "$CURRENT_UID" -eq 0 ] && command_exists setpriv; then
setpriv --reuid="$RUNTIME_USER" --regid="$(id -gn "$RUNTIME_USER")" --init-groups -- "$@"
elif [ "$CURRENT_UID" -eq 0 ] && [ -n "$SU_EXEC_BIN" ]; then
"$SU_EXEC_BIN" "$RUNTIME_USER" "$@"
else
warn_switch_user_once
"$@"
@@ -287,20 +294,10 @@ start_unoserver_watchdog() {
if [ "$needs_restart" = true ]; then
log "Restarting unoserver on 127.0.0.1:${port} (uno-port ${uno_port})"
# Kill the old process and its children (soffice) if it exists.
# Capture child PIDs first, then send TERM to children before parent
# so the PPID relationship is still visible. After sleep, use the
# saved PIDs for SIGKILL since the parent may have already exited
# and children would be reparented to init.
# Kill the old process if it exists
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
local child_pids
child_pids=$(pgrep -P "$pid" 2>/dev/null || true)
pkill -TERM -P "$pid" 2>/dev/null || true
kill -TERM "$pid" 2>/dev/null || true
sleep 3
if [ -n "$child_pids" ]; then
kill -KILL $child_pids 2>/dev/null || true
fi
sleep 1
kill -KILL "$pid" 2>/dev/null || true
fi
start_unoserver_instance "$port" "$uno_port"
@@ -918,8 +915,8 @@ fi
if [ "$CURRENT_USER" = "$RUNTIME_USER" ]; then
"${JAVA_CMD[@]}" &
elif [ "$CURRENT_UID" -eq 0 ] && command_exists setpriv; then
setpriv --reuid="$RUNTIME_USER" --regid="$(id -gn "$RUNTIME_USER")" --init-groups -- "${JAVA_CMD[@]}" &
elif [ "$CURRENT_UID" -eq 0 ] && [ -n "$SU_EXEC_BIN" ]; then
"$SU_EXEC_BIN" "$RUNTIME_USER" "${JAVA_CMD[@]}" &
else
warn_switch_user_once
"${JAVA_CMD[@]}" &
+2 -14
View File
@@ -88,7 +88,6 @@ capture_failure_logs() {
capture_build_failure() {
local build_name=$1
local log_file="$REPORT_DIR/${build_name//[^a-zA-Z0-9_-]/_}.failure.log"
local build_log="$REPORT_DIR/${build_name//[^a-zA-Z0-9_-]/_}.build.log"
local gradle_report_dirs=(
"$PROJECT_ROOT/app/core/build/reports/tests"
"$PROJECT_ROOT/app/common/build/reports/tests"
@@ -100,13 +99,6 @@ capture_build_failure() {
echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "---"
# Include Docker/command build output if captured
if [ -f "$build_log" ]; then
echo "--- Build output (last 100 lines) ---"
tail -100 "$build_log"
echo ""
fi
for report_dir in "${gradle_report_dirs[@]}"; do
if [ -d "$report_dir" ]; then
local txt_index="$report_dir/test/index.html"
@@ -707,14 +699,12 @@ main() {
else
DOCKER_CACHE_ARGS_ULTRA_LITE=""
fi
local ultra_lite_build_log="$REPORT_DIR/Build-Ultra-Lite-Docker.build.log"
if ! docker buildx build --build-arg VERSION_TAG=alpha \
-t docker.stirlingpdf.com/stirlingtools/stirling-pdf:ultra-lite \
-f ./docker/embedded/Dockerfile.ultra-lite \
--load \
${DOCKER_CACHE_ARGS_ULTRA_LITE} . 2>&1 | tee "$ultra_lite_build_log"; then
${DOCKER_CACHE_ARGS_ULTRA_LITE} .; then
failed_tests+=("Build-Ultra-Lite-Docker")
capture_build_failure "Build-Ultra-Lite-Docker"
gha_endgroup
exit 1
fi
@@ -793,15 +783,13 @@ main() {
else
DOCKER_CACHE_ARGS_FAT=""
fi
local fat_build_log="$REPORT_DIR/Build-Fat-Docker.build.log"
if ! docker buildx build --build-arg VERSION_TAG=alpha \
${BASE_IMAGE_ARG} \
-t docker.stirlingpdf.com/stirlingtools/stirling-pdf:fat \
-f ./docker/embedded/Dockerfile.fat \
--load \
${DOCKER_CACHE_ARGS_FAT} . 2>&1 | tee "$fat_build_log"; then
${DOCKER_CACHE_ARGS_FAT} .; then
failed_tests+=("Build-Fat-Docker")
capture_build_failure "Build-Fat-Docker"
gha_endgroup
exit 1
fi