Compare commits

..
Author SHA1 Message Date
Anthony Stirling 0e2f57a9db align winget manifest: stirling.com homepage, compound license 2026-04-17 17:45:30 +01:00
a 797c7f99ec Merge origin/main into branch 2026-03-29 23:36:45 +01:00
aandClaude Opus 4.6 9ddbf4c9b4 feat(distro): add multi-OS release workflow, WinGet and AppImage manifests
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 23:21:13 +01:00
106 changed files with 2269 additions and 4408 deletions
+2 -4
View File
@@ -236,12 +236,10 @@ jobs:
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
run: cd frontend && npm ci
- name: Generate icons
run: cd frontend && node scripts/generate-icons.js
- name: Install Playwright (chromium only)
run: cd frontend && npx playwright install chromium --with-deps
- name: Run E2E tests (chromium)
run: cd frontend && npx playwright test --project=chromium
run: cd frontend && npx playwright test src/core/tests/certValidation --project=chromium
- name: Upload Playwright report
if: always()
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
@@ -513,7 +511,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
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Run Labeler
uses: crazy-max/ghaction-github-labeler@548a7c3603594ec17c819e1239f281a3b801ab4d # v6.0.0
uses: crazy-max/ghaction-github-labeler@24d110aa46a59976b8a7f35518cb7f14f434c916 # v5.3.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
yaml-file: .github/labels.yml
+2
View File
@@ -541,6 +541,7 @@ jobs:
find . -name "*.app" -exec cp -r {} "../../../dist/Stirling-PDF-${{ matrix.name }}.app" \;
else
find . -name "*.deb" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.deb" \;
find . -name "*.rpm" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.rpm" \;
find . -name "*.AppImage" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.AppImage" \;
fi
@@ -600,6 +601,7 @@ jobs:
./artifacts/**/*.msi
./artifacts/**/*.dmg
./artifacts/**/*.deb
./artifacts/**/*.rpm
./artifacts/**/*.AppImage
draft: false
prerelease: false
+1 -4
View File
@@ -35,14 +35,11 @@ jobs:
- name: Install frontend dependencies
run: cd frontend && npm ci
- name: Generate icons
run: cd frontend && node scripts/generate-icons.js
- name: Install all Playwright browsers
run: cd frontend && npx playwright install --with-deps
- name: Run E2E tests (all browsers)
run: cd frontend && npx playwright test
run: cd frontend && npx playwright test src/core/tests/certValidation
- name: Upload Playwright report
if: always()
+24
View File
@@ -0,0 +1,24 @@
name: Publish to winget
on:
release:
types: [released]
permissions:
contents: read
jobs:
publish:
runs-on: windows-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@v2
with:
egress-policy: audit
- name: Submit to winget
uses: vedantmgoyal9/winget-releaser@v2
with:
identifier: StirlingTools.StirlingPDF
installers-regex: 'Stirling-PDF-windows-x86_64\.msi$'
token: ${{ secrets.WINGET_TOKEN }}
@@ -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
+87
View File
@@ -0,0 +1,87 @@
# AppImage — local testing
The AppImage build is produced automatically by Tauri when `"appimage"` is listed in the
`targets` array of `frontend/src-tauri/tauri.conf.json`. It is uploaded to GitHub Releases
alongside the `.deb` artifact.
---
## Prerequisites
- A Linux machine or WSL2 instance (Ubuntu 22.04+ recommended).
- `libfuse2` — required by all AppImages built with the current AppImage runtime:
```bash
sudo apt-get install libfuse2 # Debian / Ubuntu
sudo dnf install fuse-libs # Fedora / RHEL
```
On Ubuntu 22.04+ `libfuse2` is no longer installed by default; this is the single most
common reason an AppImage fails to launch.
---
## Running the AppImage
```bash
# 1. Download (or build) the AppImage
# From a GitHub Release:
curl -L -O https://github.com/Stirling-Tools/Stirling-PDF/releases/download/vX.Y.Z/Stirling-PDF_X.Y.Z_amd64.AppImage
# 2. Make it executable (only needed once)
chmod +x Stirling-PDF_*.AppImage
# 3. Launch
./Stirling-PDF_*.AppImage
```
The app should open a browser window (or system tray icon) pointing at `http://localhost:8080`.
---
## Smoke-test checklist
| Check | Expected result |
|-------|-----------------|
| Launch without arguments | App starts, UI loads at `http://localhost:8080` |
| Upload a PDF and convert | Operation completes successfully |
| Close the window / tray | Process exits cleanly (no zombie) |
| Re-launch immediately | Port is free, app starts again without errors |
---
## Local build (without a full release)
If you want to test an AppImage from a local Tauri build rather than a published release:
```bash
cd frontend
npm run tauri build
# Output is at:
# src-tauri/target/release/bundle/appimage/Stirling-PDF_*.AppImage
chmod +x src-tauri/target/release/bundle/appimage/Stirling-PDF_*.AppImage
./src-tauri/target/release/bundle/appimage/Stirling-PDF_*.AppImage
```
---
## Common gotchas
| Symptom | Likely cause | Fix |
|---------|-------------|-----|
| `fuse: device not found` or `FUSE library not found` | `libfuse2` missing | `sudo apt-get install libfuse2` |
| AppImage exits immediately with no output | Missing shared library | Run with `./Stirling-PDF_*.AppImage --appimage-extract-and-run` to bypass FUSE and surface the real error |
| Port 8080 already in use | Another process bound to the port | `lsof -i :8080` to identify and kill it, then re-launch |
| Blank window / white screen | Webview renderer issue | Ensure `libwebkit2gtk-4.0` or `libwebkit2gtk-4.1` is installed |
| Works in terminal but not double-click from file manager | Executable bit lost on download | Re-run `chmod +x` on the file |
---
## Extracting the AppImage for inspection
To inspect the contents without running the app (useful for debugging or verifying bundled files):
```bash
./Stirling-PDF_*.AppImage --appimage-extract
# Creates a ./squashfs-root/ directory with the full app tree
```
+186
View File
@@ -0,0 +1,186 @@
# Publishing Stirling-PDF to winget
This document explains how to get Stirling-PDF listed in the Windows Package Manager (winget)
and how to keep releases automatically in sync.
---
## One-time setup
### 1. Submit the initial PR to microsoft/winget-pkgs
The very first submission must be done manually so the winget team can review the package.
1. Fork [microsoft/winget-pkgs](https://github.com/microsoft/winget-pkgs).
2. Copy the three manifest files from `manifests/winget/` into the correct path inside the fork:
```
manifests/s/StirlingTools/StirlingPDF/2.7.3/
├── StirlingTools.StirlingPDF.yaml
├── StirlingTools.StirlingPDF.locale.en-US.yaml
└── StirlingTools.StirlingPDF.installer.yaml
```
3. Before opening the PR, update `InstallerSha256` in the installer manifest with the real
SHA-256 of the published `.msi` file:
```powershell
Get-FileHash .\Stirling-PDF-windows-x86_64.msi -Algorithm SHA256
```
Or on Linux/macOS:
```bash
sha256sum Stirling-PDF-windows-x86_64.msi
```
4. Open a pull request against `microsoft/winget-pkgs`. The title should follow the required
format: `New package: StirlingTools.StirlingPDF version 2.7.3`.
5. The winget validation bot will run automated checks. Fix any reported issues, then wait for
human review. Initial reviews usually take a few days to a couple of weeks.
6. Once the PR is merged, `winget install StirlingTools.StirlingPDF` will work for all Windows
users.
---
### 2. Create the WINGET_TOKEN secret
After the initial package is accepted, subsequent releases are submitted automatically by the
`winget-publish.yml` workflow using `vedantmgoyal9/winget-releaser`.
The workflow needs a GitHub Personal Access Token (PAT) with permission to open pull requests
against `microsoft/winget-pkgs`.
**Steps:**
1. Go to <https://github.com/settings/tokens> and generate a **Classic** PAT with the
`public_repo` scope (or a fine-grained token scoped to `microsoft/winget-pkgs` with
*Contents: read & write* and *Pull requests: read & write*).
2. In the Stirling-PDF repository, go to
**Settings → Secrets and variables → Actions → New repository secret**.
3. Name the secret `WINGET_TOKEN` and paste the PAT as the value.
4. Save.
From this point on, every time a GitHub Release is published the workflow will:
- Download the release's `.msi` asset.
- Compute its SHA-256.
- Open a PR to `microsoft/winget-pkgs` with an updated manifest.
---
## How the automation works
The workflow file is at `.github/workflows/winget-publish.yml`. It triggers on the
`release: published` event and calls the
[vedantmgoyal9/winget-releaser](https://github.com/vedantmgoyal9/winget-releaser) action, which:
1. Finds the `.msi` asset in the release that matches `Stirling-PDF-windows-x86_64.msi`.
2. Builds a new set of manifests with the correct version and SHA-256.
3. Opens a PR against `microsoft/winget-pkgs` using the `WINGET_TOKEN`.
No manual steps are needed after the initial submission.
---
## License notes
Stirling-PDF uses an **Open Core** model. The canonical license URL for all manifests is:
```
https://github.com/Stirling-Tools/Stirling-PDF/blob/main/LICENSE
```
Never use `stirlingpdf.com/terms` as the license URL in any manifest.
For the license identifier, use whichever option the platform supports best:
| Platform supports | Use |
|-------------------|-----|
| Free-text / custom field | `Open Core` |
| SPDX identifiers only | `LicenseRef-OpenCore` |
| Known identifiers only (e.g. winget fallback) | `Proprietary` for desktop, `MIT` for server JAR |
The desktop app (`frontend/src/desktop/`) is proprietary. The server JAR (`app/core/`) is
MIT-licensed. Winget's `License` field is free-text, so the manifest uses `Open Core`.
---
## Local testing
Validate manifests locally before opening a PR to `microsoft/winget-pkgs` to catch errors
that would otherwise stall the review.
### Prerequisites
```powershell
# Install the winget client (already present on Windows 11; on Windows 10 install from the Store)
# Install wingetcreate
winget install Microsoft.WingetCreate
```
### 1. Validate manifest structure
`winget validate` checks syntax, required fields, and schema conformance:
```powershell
# From the repo root — point at the folder containing the three YAML files
winget validate manifests\winget\
```
A clean run prints `Manifest validation succeeded.` with no errors.
**Common gotchas:**
- `PackageVersion` must be a pure semver string (`2.7.3`, not `v2.7.3`).
- `InstallerUrl` must be HTTPS and publicly reachable. If you are testing against a pre-release
or a local build, temporarily host the `.msi` somewhere public (e.g. a GitHub release draft).
- `InstallerSha256` must match the file at `InstallerUrl` exactly. Recompute it whenever the
`.msi` changes.
- Trailing whitespace in YAML causes schema errors that can be hard to spot — run your editor's
"trim trailing whitespace" pass before validating.
### 2. Dry-run a PR submission
`wingetcreate submit --test` generates the updated manifests and opens a **test** PR against a
sandbox fork instead of the real `microsoft/winget-pkgs`:
```powershell
wingetcreate submit `
--token "$env:WINGET_TOKEN" `
--test `
StirlingTools.StirlingPDF
```
This lets you see exactly what the PR will look like, including the diff, without touching the
real repository.
**Note:** `--test` requires the `WINGET_TOKEN` PAT (same one used by the CI workflow). If the
token is not set as an environment variable, pass it directly with `--token <your-pat>`.
### 3. Install from a local manifest (end-to-end smoke test)
Once `winget validate` passes, install the package directly from the local manifest files to
confirm the installer actually runs:
```powershell
# Requires running as Administrator or in a dev environment with Developer Mode enabled
winget install --manifest manifests\winget\
```
This downloads the `.msi` from `InstallerUrl`, verifies the hash, and runs the installer — the
same path a real user would follow.
---
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|-------------|-----|
| Workflow fails with `403` | `WINGET_TOKEN` expired or missing | Regenerate and update the secret |
| winget-pkgs PR blocked by validation | Manifest field formatting | Check the PR comments from the `winget-bot` and update the manifests in `manifests/winget/` |
| `InstallerSha256` mismatch | Stale placeholder in manifests | The automation recalculates the hash; the placeholder in-repo only matters for the initial manual PR |
-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,
+1 -23
View File
@@ -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"
@@ -7994,7 +7978,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 +7986,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 +7995,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]
@@ -1612,7 +1612,7 @@ fieldDocumentName = "Nome documento"
fieldFileHash = "Hash del file (SHA-256)"
fieldIpAddress = "Indirizzo IP"
fieldOperationResults = "Risultati dell'operazione"
fieldOutcome = "Esito (Successo/non riuscito)"
fieldOutcome = "Esito (Successo/Fallimento)"
fieldTool = "Strumento"
fieldUsername = "Nome utente"
filterByType = "Filtra per tipo"
@@ -5303,10 +5303,10 @@ name = "Team"
siteLicense = "Licenza sito"
[plan.api]
large = "5,000 Crediti"
medium = "1,000 Crediti"
small = "500 Crediti"
xsmall = "100 Crediti"
large = "5,000 Credits"
medium = "1,000 Credits"
small = "500 Credits"
xsmall = "100 Credits"
[plan.apiPackages]
subtitle = "Acquista crediti API per le tue applicazioni"
File diff suppressed because it is too large Load Diff
+1
View File
@@ -27,6 +27,7 @@
"targets": [
"deb",
"rpm",
"appimage",
"dmg",
"msi"
],
@@ -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'),
@@ -123,7 +123,6 @@ function ReviewStepContent<TParams = unknown>({
)}
{operation.downloadUrl && (
<Button
data-testid="download-result-button"
leftSection={<DownloadIcon />}
color="blue"
fullWidth
@@ -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,
@@ -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,
@@ -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;
}
+458 -151
View File
@@ -1,184 +1,491 @@
/**
* End-to-End Tests for Convert Tool
*
* All backend API calls are mocked via page.route() — no real backend required.
* The Vite dev server must be running (handled by playwright.config.ts webServer).
* These tests dynamically discover available conversion endpoints and test them.
* Tests are automatically skipped if the backend endpoint is not available.
*
* Run with: npm run test:e2e or npx playwright test
*/
import { test, expect, type Page } from '@playwright/test';
import path from 'path';
import { test, expect, Page } from '@playwright/test';
import {
conversionDiscovery,
type ConversionEndpoint
} from '@app/tests/helpers/conversionEndpointDiscovery';
import * as path from 'path';
import * as fs from 'fs';
const FIXTURES_DIR = path.join(__dirname, '../test-fixtures');
const SAMPLE_PDF = path.join(FIXTURES_DIR, 'sample.pdf');
// Test configuration
const BASE_URL = process.env.BASE_URL || 'http://localhost:5173';
// ---------------------------------------------------------------------------
// Endpoint availability map — all conversion endpoints enabled
// ---------------------------------------------------------------------------
const MOCK_ENDPOINTS_AVAILABILITY = Object.fromEntries(
[
'pdf-to-img', 'img-to-pdf', 'pdf-to-word', 'file-to-pdf', 'pdf-to-text',
'pdf-to-html', 'pdf-to-xml', 'pdf-to-csv', 'pdf-to-xlsx', 'pdf-to-pdfa',
'pdf-to-pdfx', 'pdf-to-presentation', 'pdf-to-markdown', 'pdf-to-cbz',
'pdf-to-cbr', 'pdf-to-epub', 'html-to-pdf', 'svg-to-pdf', 'markdown-to-pdf',
'eml-to-pdf', 'cbz-to-pdf', 'cbr-to-pdf',
].map((k) => [k, { enabled: true }])
);
/**
* Resolves test fixture paths dynamically based on current working directory.
* Works from both top-level project directory and frontend subdirectory.
*/
function resolveTestFixturePath(filename: string): string {
const cwd = process.cwd();
// ---------------------------------------------------------------------------
// Helper: mock all standard app APIs needed to load the main UI
// ---------------------------------------------------------------------------
async function mockAppApis(page: Page) {
// Backend probe — must return UP so Landing shows app in anonymous mode
await page.route('**/api/v1/info/status', (route) =>
route.fulfill({ json: { status: 'UP' } })
);
// Try frontend/src/tests/test-fixtures/ first (from top-level)
const topLevelPath = path.join(cwd, 'frontend', 'src', 'tests', 'test-fixtures', filename);
if (fs.existsSync(topLevelPath)) {
return topLevelPath;
}
// App config — enableLogin:false puts the app in anonymous mode
await page.route('**/api/v1/config/app-config', (route) =>
route.fulfill({
json: { enableLogin: false, languages: ['en-GB'], defaultLocale: 'en-GB' },
})
);
// Try src/tests/test-fixtures/ (from frontend directory)
const frontendPath = path.join(cwd, 'src', 'tests', 'test-fixtures', filename);
if (fs.existsSync(frontendPath)) {
return frontendPath;
}
// Auth — fallback if anything calls auth/me
await page.route('**/api/v1/auth/me', (route) =>
route.fulfill({
json: { id: 1, username: 'testuser', email: 'test@example.com', roles: ['ROLE_USER'] },
})
);
// Try relative path from current test file location
const relativePath = path.join(__dirname, '..', 'test-fixtures', filename);
if (fs.existsSync(relativePath)) {
return relativePath;
}
// Endpoint availability — queried by ConvertSettings
await page.route('**/api/v1/config/endpoints-availability', (route) =>
route.fulfill({ json: MOCK_ENDPOINTS_AVAILABILITY })
);
// Single-endpoint check — queried by Convert.tsx for the execute button
await page.route('**/api/v1/config/endpoint-enabled*', (route) =>
route.fulfill({ json: true })
);
// Group-enabled check
await page.route('**/api/v1/config/group-enabled*', (route) =>
route.fulfill({ json: true })
);
// Footer info — non-critical
await page.route('**/api/v1/ui-data/footer-info', (route) =>
route.fulfill({ json: {} })
);
// Proprietary endpoints — silence proxy errors in the Vite dev server
await page.route('**/api/v1/proprietary/**', (route) =>
route.fulfill({ json: {} })
);
// Fallback to the original path format (should work from top-level)
return path.join('.', 'frontend', 'src', 'tests', 'test-fixtures', filename);
}
// ---------------------------------------------------------------------------
// Helper: upload a file through the Files modal
// Uses the HiddenFileInput (data-testid="file-input") which has the correct
// onChange handler. Waits for the modal to auto-close after upload.
// ---------------------------------------------------------------------------
async function uploadFile(page: Page, filePath: string) {
await page.getByTestId('files-button').click();
// Test file paths (dynamically resolved based on current working directory)
const TEST_FILES = {
pdf: resolveTestFixturePath('sample.pdf'),
docx: resolveTestFixturePath('sample.docx'),
doc: resolveTestFixturePath('sample.doc'),
pptx: resolveTestFixturePath('sample.pptx'),
ppt: resolveTestFixturePath('sample.ppt'),
xlsx: resolveTestFixturePath('sample.xlsx'),
xls: resolveTestFixturePath('sample.xls'),
png: resolveTestFixturePath('sample.png'),
jpg: resolveTestFixturePath('sample.jpg'),
jpeg: resolveTestFixturePath('sample.jpeg'),
gif: resolveTestFixturePath('sample.gif'),
bmp: resolveTestFixturePath('sample.bmp'),
tiff: resolveTestFixturePath('sample.tiff'),
webp: resolveTestFixturePath('sample.webp'),
md: resolveTestFixturePath('sample.md'),
eml: resolveTestFixturePath('sample.eml'),
html: resolveTestFixturePath('sample.html'),
txt: resolveTestFixturePath('sample.txt'),
xml: resolveTestFixturePath('sample.xml'),
csv: resolveTestFixturePath('sample.csv')
};
// File format to test file mapping
const getTestFileForFormat = (format: string): string => {
const formatMap: Record<string, string> = {
'pdf': TEST_FILES.pdf,
'docx': TEST_FILES.docx,
'doc': TEST_FILES.doc,
'pptx': TEST_FILES.pptx,
'ppt': TEST_FILES.ppt,
'xlsx': TEST_FILES.xlsx,
'xls': TEST_FILES.xls,
'office': TEST_FILES.docx, // Default office file
'image': TEST_FILES.png, // Default image file
'png': TEST_FILES.png,
'jpg': TEST_FILES.jpg,
'jpeg': TEST_FILES.jpeg,
'gif': TEST_FILES.gif,
'bmp': TEST_FILES.bmp,
'tiff': TEST_FILES.tiff,
'webp': TEST_FILES.webp,
'md': TEST_FILES.md,
'eml': TEST_FILES.eml,
'html': TEST_FILES.html,
'txt': TEST_FILES.txt,
'xml': TEST_FILES.xml,
'csv': TEST_FILES.csv
};
return formatMap[format] || TEST_FILES.pdf; // Fallback to PDF
};
// Expected file extensions for target formats
const getExpectedExtension = (toFormat: string): string => {
const extensionMap: Record<string, string> = {
'pdf': '.pdf',
'docx': '.docx',
'pptx': '.pptx',
'txt': '.txt',
'html': '.zip', // HTML is zipped
'xml': '.xml',
'csv': '.csv',
'md': '.md',
'image': '.png', // Default for image conversion
'png': '.png',
'jpg': '.jpg',
'jpeg': '.jpeg',
'gif': '.gif',
'bmp': '.bmp',
'tiff': '.tiff',
'webp': '.webp',
'pdfa': '.pdf'
};
return extensionMap[toFormat] || '.pdf';
};
/**
* Helper function to upload files through the modal system
*/
async function uploadFileViaModal(page: Page, filePath: string) {
// Click the Files button in the QuickAccessBar to open the modal
await page.click('[data-testid="files-button"]');
// Wait for the modal to open
await page.waitForSelector('.mantine-Modal-overlay', { state: 'visible', timeout: 5000 });
await page.locator('[data-testid="file-input"]').setInputFiles(filePath);
// Modal auto-closes after file is selected
await page.waitForSelector('.mantine-Modal-overlay', { state: 'hidden', timeout: 10000 });
//await page.waitForSelector('[data-testid="file-upload-modal"]', { timeout: 5000 });
// Upload the file through the modal's file input
await page.setInputFiles('input[type="file"]', filePath);
// Wait for the file to be processed and the modal to close
await page.waitForSelector('[data-testid="file-upload-modal"]', { state: 'hidden' });
// Wait for the file thumbnail to appear in the main interface
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 10000 });
}
// ---------------------------------------------------------------------------
// Helper: navigate to the Convert tool panel
// Tools use data-tour="tool-button-{key}" anchors in the ToolPanel.
// After clicking, the URL changes to /convert and the settings appear.
// ---------------------------------------------------------------------------
async function navigateToConvert(page: Page) {
await page.locator('[data-tour="tool-button-convert"]').click();
/**
* Generic test function for any conversion
*/
async function testConversion(page: Page, conversion: ConversionEndpoint) {
const expectedExtension = getExpectedExtension(conversion.toFormat);
console.log(`Testing ${conversion.endpoint}: ${conversion.fromFormat} → ${conversion.toFormat}`);
// File should already be uploaded, click the Convert tool button
await page.click('[data-testid="tool-convert"]');
// Wait for the FileEditor to load in convert mode with file thumbnails
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 5000 });
// Click the file thumbnail checkbox to select it in the FileEditor
await page.click('[data-testid="file-thumbnail-checkbox"]');
// Wait for the conversion settings to appear after file selection
await page.waitForSelector('[data-testid="convert-from-dropdown"]', { timeout: 5000 });
// Select FROM format
await page.click('[data-testid="convert-from-dropdown"]');
const fromFormatOption = page.locator(`[data-testid="format-option-${conversion.fromFormat}"]`);
await fromFormatOption.scrollIntoViewIfNeeded();
await fromFormatOption.click();
// Select TO format
await page.click('[data-testid="convert-to-dropdown"]');
const toFormatOption = page.locator(`[data-testid="format-option-${conversion.toFormat}"]`);
await toFormatOption.scrollIntoViewIfNeeded();
await toFormatOption.click();
// Handle format-specific options
if (conversion.toFormat === 'image' || ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'webp'].includes(conversion.toFormat)) {
// Set image conversion options if they appear
const imageOptionsVisible = await page.locator('[data-testid="image-options-section"]').isVisible().catch(() => false);
if (imageOptionsVisible) {
// Click the color type dropdown and select "Color"
await page.click('[data-testid="color-type-select"]');
await page.getByRole('option', { name: 'Color' }).click();
// Set DPI value
await page.fill('[data-testid="dpi-input"]', '150');
// Click the output type dropdown and select "Multiple"
await page.click('[data-testid="output-type-select"]');
await page.getByRole('option', { name: 'single' }).click();
}
}
if (conversion.fromFormat === 'image' && conversion.toFormat === 'pdf') {
// Set PDF creation options if they appear
const pdfOptionsVisible = await page.locator('[data-testid="pdf-options-section"]').isVisible().catch(() => false);
if (pdfOptionsVisible) {
// Click the color type dropdown and select "Color"
await page.click('[data-testid="color-type-select"]');
await page.locator('[data-value="color"]').click();
}
}
if (conversion.fromFormat === 'pdf' && conversion.toFormat === 'csv') {
// Set CSV extraction options if they appear
const csvOptionsVisible = await page.locator('[data-testid="csv-options-section"]').isVisible().catch(() => false);
if (csvOptionsVisible) {
// Set specific page numbers for testing (test pages 1-2)
await page.fill('[data-testid="page-numbers-input"]', '1-2');
}
}
// Start conversion
await page.click('[data-testid="convert-button"]');
// Wait for conversion to complete (with generous timeout)
await page.waitForSelector('[data-testid="download-button"]', { timeout: 60000 });
// Verify download is available
const downloadButton = page.locator('[data-testid="download-button"]');
await expect(downloadButton).toBeVisible();
// Start download and verify file
const downloadPromise = page.waitForEvent('download');
await downloadButton.click();
const download = await downloadPromise;
// Verify file extension
expect(download.suggestedFilename()).toMatch(new RegExp(`\\${expectedExtension}$`));
// Save and verify file is not empty
const path = await download.path();
if (path) {
const fs = require('fs');
const stats = fs.statSync(path);
expect(stats.size).toBeGreaterThan(0);
// Format-specific validations
if (conversion.toFormat === 'pdf' || conversion.toFormat === 'pdfa') {
// Verify PDF header
const buffer = fs.readFileSync(path);
const header = buffer.toString('utf8', 0, 4);
expect(header).toBe('%PDF');
}
if (conversion.toFormat === 'txt') {
// Verify text content exists
const content = fs.readFileSync(path, 'utf8');
expect(content.length).toBeGreaterThan(0);
}
if (conversion.toFormat === 'csv') {
// Verify CSV content contains separators
const content = fs.readFileSync(path, 'utf8');
expect(content).toContain(',');
}
}
}
// ---------------------------------------------------------------------------
// Helper: select the TO format in the convert dropdown
// The FROM format is auto-detected from the uploaded file (e.g. PDF → "Document (PDF)").
// Opening the TO dropdown renders format-option-{value} buttons in a portal.
// ---------------------------------------------------------------------------
async function selectToFormat(page: Page, toValue: string) {
await page.getByTestId('convert-to-dropdown').click();
await page.getByTestId(`format-option-${toValue}`).click();
}
// Discover conversions at module level before tests are defined
let availableConversions: ConversionEndpoint[] = [];
let unavailableConversions: ConversionEndpoint[] = [];
// Pre-populate conversions synchronously for test generation
(async () => {
try {
availableConversions = await conversionDiscovery.getAvailableConversions();
unavailableConversions = await conversionDiscovery.getUnavailableConversions();
} catch (error) {
console.error('Failed to discover conversions during module load:', error);
}
})();
test.describe('Convert Tool E2E Tests', () => {
test.beforeAll(async () => {
// Re-discover to ensure fresh data at test time
console.log('Re-discovering available conversion endpoints...');
availableConversions = await conversionDiscovery.getAvailableConversions();
unavailableConversions = await conversionDiscovery.getUnavailableConversions();
console.log(`Found ${availableConversions.length} available conversions:`);
availableConversions.forEach(conv => {
console.log(` ✓ ${conv.endpoint}: ${conv.fromFormat} → ${conv.toFormat}`);
});
if (unavailableConversions.length > 0) {
console.log(`Found ${unavailableConversions.length} unavailable conversions:`);
unavailableConversions.forEach(conv => {
console.log(` ✗ ${conv.endpoint}: ${conv.fromFormat} → ${conv.toFormat}`);
});
}
});
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe('Convert Tool', () => {
test.beforeEach(async ({ page }) => {
await mockAppApis(page);
await page.goto('/?bypassOnboarding=true');
// Navigate to the homepage
await page.goto(`${BASE_URL}`);
// Wait for the page to load
await page.waitForLoadState('networkidle');
// Wait for the QuickAccessBar to appear
await page.waitForSelector('[data-testid="files-button"]', { timeout: 10000 });
});
test('convert button is disabled before a TO format is selected', async ({ page }) => {
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
test.describe('Dynamic Conversion Tests', () => {
// FROM is auto-detected as PDF; TO not selected → button visible but disabled
const convertBtn = page.getByTestId('convert-button');
await expect(convertBtn).toBeVisible({ timeout: 3000 });
await expect(convertBtn).toBeDisabled();
// Generate a test for each potentially available conversion
// We'll discover all possible conversions and then skip unavailable ones at runtime
test('PDF to PNG conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/img',
fromFormat: 'pdf',
toFormat: 'png',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to DOCX conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/word',
fromFormat: 'pdf',
toFormat: 'docx',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('DOCX to PDF conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/file/pdf',
fromFormat: 'docx',
toFormat: 'pdf',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('Image to PDF conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/img/pdf',
fromFormat: 'png',
toFormat: 'pdf',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to TXT conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/text',
fromFormat: 'pdf',
toFormat: 'txt',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to HTML conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/html',
fromFormat: 'pdf',
toFormat: 'html',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to XML conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/xml',
fromFormat: 'pdf',
toFormat: 'xml',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to CSV conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/csv',
fromFormat: 'pdf',
toFormat: 'csv',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to PDFA conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/pdfa',
fromFormat: 'pdf',
toFormat: 'pdfa',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
});
test('successful PDF to PNG conversion shows download option', async ({ page }) => {
// Minimal valid PNG header (8 bytes signature + padding)
const fakePng = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
...Array(504).fill(0),
]);
test.describe('Static Tests', () => {
await page.route('**/api/v1/convert/pdf/img', (route) =>
route.fulfill({
status: 200,
contentType: 'image/png',
headers: { 'Content-Disposition': 'attachment; filename="sample.png"' },
body: fakePng,
})
);
// Test that disabled conversions don't appear in dropdowns when they shouldn't
test('should not show conversion button when no valid conversions available', async ({ page }) => {
// This test ensures the convert button is disabled when no valid conversion is possible
await uploadFileViaModal(page, TEST_FILES.pdf);
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
await selectToFormat(page, 'png');
await page.getByTestId('convert-button').click();
// Click the Convert tool button
await page.click('[data-testid="tool-convert"]');
await expect(page.getByTestId('download-result-button')).toBeVisible({ timeout: 10000 });
});
// Wait for convert mode and select file
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 5000 });
await page.click('[data-testid="file-thumbnail-checkbox"]');
test('conversion API error shows error notification', async ({ page }) => {
await page.route('**/api/v1/convert/pdf/img', (route) =>
route.fulfill({
status: 500,
contentType: 'text/plain',
body: 'Internal server error: conversion failed',
})
);
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
await selectToFormat(page, 'png');
await page.getByTestId('convert-button').click();
// Mantine Notification renders as role="alert"
await expect(page.getByRole('alert').first()).toBeVisible({ timeout: 5000 });
});
test('convert button becomes enabled after selecting a valid TO format', async ({ page }) => {
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
// Before selecting TO format — button visible but disabled
const convertBtn = page.getByTestId('convert-button');
await expect(convertBtn).toBeVisible({ timeout: 3000 });
await expect(convertBtn).toBeDisabled();
// After selecting PNG as TO format — button enabled
await selectToFormat(page, 'png');
await expect(convertBtn).toBeEnabled({ timeout: 3000 });
// Don't select any formats - convert button should not exist
const convertButton = page.locator('[data-testid="convert-button"]');
await expect(convertButton).toHaveCount(0);
});
});
});
@@ -0,0 +1,325 @@
/**
* Conversion Endpoint Discovery for E2E Testing
*
* Uses the backend's endpoint configuration API to discover available conversions
*/
import { useMultipleEndpointsEnabled } from '@app/hooks/useEndpointConfig';
export interface ConversionEndpoint {
endpoint: string;
fromFormat: string;
toFormat: string;
description: string;
apiPath: string;
}
// Complete list of conversion endpoints based on EndpointConfiguration.java
const ALL_CONVERSION_ENDPOINTS: ConversionEndpoint[] = [
{
endpoint: 'pdf-to-img',
fromFormat: 'pdf',
toFormat: 'image',
description: 'Convert PDF to images (PNG, JPG, GIF, etc.)',
apiPath: '/api/v1/convert/pdf/img'
},
{
endpoint: 'img-to-pdf',
fromFormat: 'image',
toFormat: 'pdf',
description: 'Convert images to PDF',
apiPath: '/api/v1/convert/img/pdf'
},
{
endpoint: 'pdf-to-pdfa',
fromFormat: 'pdf',
toFormat: 'pdfa',
description: 'Convert PDF to PDF/A',
apiPath: '/api/v1/convert/pdf/pdfa'
},
{
endpoint: 'file-to-pdf',
fromFormat: 'office',
toFormat: 'pdf',
description: 'Convert office files to PDF',
apiPath: '/api/v1/convert/file/pdf'
},
{
endpoint: 'pdf-to-word',
fromFormat: 'pdf',
toFormat: 'docx',
description: 'Convert PDF to Word document',
apiPath: '/api/v1/convert/pdf/word'
},
{
endpoint: 'pdf-to-presentation',
fromFormat: 'pdf',
toFormat: 'pptx',
description: 'Convert PDF to PowerPoint presentation',
apiPath: '/api/v1/convert/pdf/presentation'
},
{
endpoint: 'pdf-to-text',
fromFormat: 'pdf',
toFormat: 'txt',
description: 'Convert PDF to plain text',
apiPath: '/api/v1/convert/pdf/text'
},
{
endpoint: 'pdf-to-html',
fromFormat: 'pdf',
toFormat: 'html',
description: 'Convert PDF to HTML',
apiPath: '/api/v1/convert/pdf/html'
},
{
endpoint: 'pdf-to-xml',
fromFormat: 'pdf',
toFormat: 'xml',
description: 'Convert PDF to XML',
apiPath: '/api/v1/convert/pdf/xml'
},
{
endpoint: 'html-to-pdf',
fromFormat: 'html',
toFormat: 'pdf',
description: 'Convert HTML to PDF',
apiPath: '/api/v1/convert/html/pdf'
},
{
endpoint: 'url-to-pdf',
fromFormat: 'url',
toFormat: 'pdf',
description: 'Convert web page to PDF',
apiPath: '/api/v1/convert/url/pdf'
},
{
endpoint: 'markdown-to-pdf',
fromFormat: 'md',
toFormat: 'pdf',
description: 'Convert Markdown to PDF',
apiPath: '/api/v1/convert/markdown/pdf'
},
{
endpoint: 'pdf-to-csv',
fromFormat: 'pdf',
toFormat: 'csv',
description: 'Extract CSV data from PDF',
apiPath: '/api/v1/convert/pdf/csv'
},
{
endpoint: 'pdf-to-xlsx',
fromFormat: 'pdf',
toFormat: 'xlsx',
description: 'Extract Excel spreadsheet from PDF',
apiPath: '/api/v1/convert/pdf/xlsx'
},
{
endpoint: 'pdf-to-markdown',
fromFormat: 'pdf',
toFormat: 'md',
description: 'Convert PDF to Markdown',
apiPath: '/api/v1/convert/pdf/markdown'
},
{
endpoint: 'eml-to-pdf',
fromFormat: 'eml',
toFormat: 'pdf',
description: 'Convert email (EML) to PDF',
apiPath: '/api/v1/convert/eml/pdf'
},
{
endpoint: 'pdf-to-epub',
fromFormat: 'pdf',
toFormat: 'epub',
description: 'Convert PDF to EPUB/AZW3',
apiPath: '/api/v1/convert/pdf/epub'
},
{
endpoint: 'eml-to-pdf', // MSG uses same endpoint as EML
fromFormat: 'msg',
toFormat: 'pdf',
description: 'Convert Outlook email (MSG) to PDF',
apiPath: '/api/v1/convert/eml/pdf'
}
];
export class ConversionEndpointDiscovery {
private baseUrl: string;
private cache: Map<string, boolean> | null = null;
private cacheExpiry: number = 0;
private readonly CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
constructor(baseUrl: string = process.env.BACKEND_URL || 'http://localhost:8080') {
this.baseUrl = baseUrl;
}
/**
* Get all available conversion endpoints by checking with backend
*/
async getAvailableConversions(): Promise<ConversionEndpoint[]> {
const endpointStatuses = await this.getEndpointStatuses();
return ALL_CONVERSION_ENDPOINTS.filter(conversion =>
endpointStatuses.get(conversion.endpoint) === true
);
}
/**
* Get all unavailable conversion endpoints
*/
async getUnavailableConversions(): Promise<ConversionEndpoint[]> {
const endpointStatuses = await this.getEndpointStatuses();
return ALL_CONVERSION_ENDPOINTS.filter(conversion =>
endpointStatuses.get(conversion.endpoint) === false
);
}
/**
* Check if a specific conversion is available
*/
async isConversionAvailable(endpoint: string): Promise<boolean> {
const endpointStatuses = await this.getEndpointStatuses();
return endpointStatuses.get(endpoint) === true;
}
/**
* Get available conversions grouped by source format
*/
async getConversionsByFormat(): Promise<Record<string, ConversionEndpoint[]>> {
const availableConversions = await this.getAvailableConversions();
const grouped: Record<string, ConversionEndpoint[]> = {};
availableConversions.forEach(conversion => {
if (!grouped[conversion.fromFormat]) {
grouped[conversion.fromFormat] = [];
}
grouped[conversion.fromFormat].push(conversion);
});
return grouped;
}
/**
* Get supported target formats for a given source format
*/
async getSupportedTargetFormats(fromFormat: string): Promise<string[]> {
const availableConversions = await this.getAvailableConversions();
return availableConversions
.filter(conversion => conversion.fromFormat === fromFormat)
.map(conversion => conversion.toFormat);
}
/**
* Get all supported source formats
*/
async getSupportedSourceFormats(): Promise<string[]> {
const availableConversions = await this.getAvailableConversions();
const sourceFormats = new Set(
availableConversions.map(conversion => conversion.fromFormat)
);
return Array.from(sourceFormats);
}
/**
* Get endpoint statuses from backend using batch API
*/
private async getEndpointStatuses(): Promise<Map<string, boolean>> {
// Return cached result if still valid
if (this.cache && Date.now() < this.cacheExpiry) {
return this.cache;
}
try {
const endpointNames = ALL_CONVERSION_ENDPOINTS.map(conv => conv.endpoint);
const endpointsParam = endpointNames.join(',');
const response = await fetch(
`${this.baseUrl}/api/v1/config/endpoints-enabled?endpoints=${encodeURIComponent(endpointsParam)}`
);
if (!response.ok) {
throw new Error(`Failed to fetch endpoint statuses: ${response.status} ${response.statusText}`);
}
const statusMap: Record<string, boolean> = await response.json();
// Convert to Map and cache
this.cache = new Map(Object.entries(statusMap));
this.cacheExpiry = Date.now() + this.CACHE_DURATION;
console.log(`Retrieved status for ${Object.keys(statusMap).length} conversion endpoints`);
return this.cache;
} catch (error) {
console.error('Failed to get endpoint statuses:', error);
// Fallback: assume all endpoints are disabled
const fallbackMap = new Map<string, boolean>();
ALL_CONVERSION_ENDPOINTS.forEach(conv => {
fallbackMap.set(conv.endpoint, false);
});
return fallbackMap;
}
}
/**
* Utility to create a skipping condition for tests
*/
static createSkipCondition(endpoint: string, discovery: ConversionEndpointDiscovery) {
return async () => {
const available = await discovery.isConversionAvailable(endpoint);
return !available;
};
}
/**
* Get detailed conversion info by endpoint name
*/
getConversionInfo(endpoint: string): ConversionEndpoint | undefined {
return ALL_CONVERSION_ENDPOINTS.find(conv => conv.endpoint === endpoint);
}
/**
* Get all conversion endpoints (regardless of availability)
*/
getAllConversions(): ConversionEndpoint[] {
return [...ALL_CONVERSION_ENDPOINTS];
}
}
// Export singleton instance for reuse across tests
export const conversionDiscovery = new ConversionEndpointDiscovery();
/**
* React hook version for use in components (wraps the class)
*/
export function useConversionEndpoints() {
const endpointNames = ALL_CONVERSION_ENDPOINTS.map(conv => conv.endpoint);
const { endpointStatus, loading, error, refetch } = useMultipleEndpointsEnabled(endpointNames);
const availableConversions = ALL_CONVERSION_ENDPOINTS.filter(
conv => endpointStatus[conv.endpoint] === true
);
const unavailableConversions = ALL_CONVERSION_ENDPOINTS.filter(
conv => endpointStatus[conv.endpoint] === false
);
return {
availableConversions,
unavailableConversions,
allConversions: ALL_CONVERSION_ENDPOINTS,
endpointStatus,
loading,
error,
refetch,
isConversionAvailable: (endpoint: string) => endpointStatus[endpoint] === true
};
}
+1 -1
View File
@@ -37,7 +37,7 @@ const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
};
const hasFiles = selectedFiles.length > 0;
const hasResults = convertOperation.files.length > 0 || convertOperation.downloadUrl !== null || !!convertOperation.errorMessage;
const hasResults = convertOperation.files.length > 0 || convertOperation.downloadUrl !== null;
const settingsCollapsed = hasResults;
// When operation completes, flag the next selection change to skip reset
-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';
}
@@ -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);
},
/**

Some files were not shown because too many files have changed in this diff Show More