Compare commits

...
Author SHA1 Message Date
Anthony Stirling b5e950bc12 remove gosu, mad merge 2026-04-01 14:38:55 +01:00
Anthony Stirling a3d5141a04 version bump 2026-04-01 14:29:57 +01:00
Anthony StirlingandClaude Opus 4.6 76e0611a1e Merge origin/main into useLatestFFMPEG
Resolve conflict in docker/base/Dockerfile: keep custom ffmpeg-build
stage approach (build from source + runtime shared libs) instead of
packaged ffmpeg from main.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 12:00:24 +01:00
Anthony StirlingandGitHub ecd1d3cad3 fix new line in redact (#6035) 2026-04-01 11:58:38 +01:00
Anthony StirlingandGitHub 0a098cf7b7 idle cpu fix test (#6015) 2026-04-01 11:58:10 +01:00
Anthony StirlingandGitHub cfa8d1e5d7 qr split fixes (#6043) 2026-04-01 11:54:33 +01:00
Anthony StirlingandGitHub 5ffa808c0f Remove gosu (#6036) 2026-04-01 11:54:12 +01:00
Matheus SaitoandGitHub 212f12a81f Added back ctrl+r as rotate if on desktop (#5982) (#5993)
Fix #5982

Behaviour of ctrl+r altered to support rotate on desktop, while the web
version continue to use refresh as default.
2026-04-01 11:48:53 +01:00
James BruntonandGitHub c31e4253dd Fix any type usage in proprietary/ (#5949)
# Description of Changes
Follow on from #5934, expanding `any` type usage ban to the
`proprietary/` folder
2026-04-01 08:21:26 +00:00
Anthony Stirling a6448e8732 update ffmpeg 2026-03-31 09:43:59 +01:00
Peter Dave HelloandGitHub a96b95e198 Update and improve zh-TW Traditional Chinese locale (#6034) 2026-03-30 21:10:49 +01:00
Anthony StirlingandGitHub a06b6a4bac pdf layer toggle (#6028) 2026-03-30 17:04:53 +01:00
cdc288e78d nonpdf-viewer (#6024)
Co-authored-by: a <a>
2026-03-30 16:39:11 +01:00
Anthony StirlingandGitHub 82a3b8c770 Unlock account (#5984) 2026-03-30 16:07:57 +01:00
ConnorYohandGitHub 1e97a32d4b feat(desktop): gate shared signing behind self-hosted auth (#6002)
## Summary

This PR adds full desktop (Tauri) support for the shared signing feature
when connected to a self-hosted server, and fixes several bugs
discovered during that work.

### Feature gating

Shared signing, file sharing, and share links are proprietary server
features that require an authenticated self-hosted session. Previously
these were read directly from `config` with no awareness of connection
mode or auth state, meaning the UI could appear in SaaS/local mode or
when logged out.

- Introduce `useGroupSigningEnabled` and `useSharingEnabled` hooks with
core implementations (web behaviour unchanged) and desktop overrides
that require `selfhosted` mode + an active authenticated session
- Extract shared subscription logic into `useSelfHostedAuth` (connection
mode + auth state + config refetch)
- `QuickAccessBar` now derives all three flags from the hooks instead of
raw config

### Config timing fix

When a user logs in via the SetupWizard, the `jwt-available` event fires
a config fetch *before* the mode is switched to `selfhosted`. This meant
the config was fetched from the local bundled backend (port ~59567)
which has no knowledge of `storageGroupSigningEnabled`, causing the
group signing button to stay hidden until a full page refresh.
`useSelfHostedAuth` detects the mode transition and triggers a fresh
config fetch at the correct moment, after the self-hosted URL is active.

### Bug fixes

**`SignPopout.tsx`** — Manually setting `Content-Type:
multipart/form-data` on two `FormData` POST requests stripped the
auto-generated boundary, causing a `400 bad multipart` from the server.
Removed the explicit headers so Axios sets them correctly.

**`tauriHttpClient.ts`** — `response.json()` was called before
`response.ok` was checked. A plain-text error body from the server (e.g.
`"Cannot sign..."`) caused a `SyntaxError` that fell into the network
error catch block and was reported as `ERR_NETWORK`, hiding the real
failure. The fix checks `response.ok` first, reads error bodies as text,
and handles empty 200 bodies (returning `null` instead of throwing).

---

## Testing

### Prerequisites
- Desktop app running in self-hosted mode pointed at a local
Stirling-PDF instance (`http://localhost:8080`)
- The self-hosted instance has group signing and storage enabled in
settings
- At least two user accounts on the self-hosted instance

### 1. Feature gating — group signing button

| Step | Expected |
|---|---|
| Open the desktop app in **local mode** (no server configured) | Group
signing button absent from QuickAccessBar |
| Switch to self-hosted mode but **do not log in** | Group signing
button absent |
| Log in to the self-hosted server | Group signing button appears
without requiring a page refresh |
| Log out | Group signing button disappears immediately |
| Log back in | Group signing button reappears without a page refresh |

### 2. Feature gating — file sharing

Repeat the same steps above, verifying the share and share-link buttons
in the file manager follow the same visibility rules.

### 3. Create a signing session

1. Log in, open the group signing panel from QuickAccessBar
2. Select a PDF, add a participant, configure signature defaults and
submit
3. Verify the session is created successfully (no `400 bad multipart`
error)

### 4. Participant signing

1. As the invited participant, open the signing request from
QuickAccessBar
2. Upload or draw a signature and submit
3. Verify signing completes successfully (no `ERR_NETWORK` error)

### 5. Error surfacing

1. Attempt an action that the server rejects (e.g. sign a document with
an invalid certificate)
2. Verify the actual server error message is shown rather than a generic
network error
2026-03-30 14:37:45 +00:00
James BruntonandGitHub 4a6b426651 Only allow Tauri imports in the desktop app (#5995)
# Description of Changes
Adds an eslint rule to disallow importing any Tauri APIs outside the
desktop folder to help hint to developers that they should be following
the frontend architecture.

While doing this, I also discovered that you can provide a custom
message in the `no-restricted-imports` rule, which is nicer than the
comments that I'd previously added to the eslint config file to explain
why they weren't allowed:

```text
/Users/jamesbrunton/Dev/spdf1/frontend/src/core/components/shared/config/configSections/GeneralSection.tsx
  19:1  error  'src/core/contexts/PreferencesContext' import is restricted from being used by a pattern. Use @app/* imports instead of absolute src/ imports              no-restricted-imports
  20:1  error  '../../../../../core/contexts/AppConfigContext' import is restricted from being used by a pattern. Use @app/* imports instead of relative imports          no-restricted-imports
  21:1  error  '@tauri-apps/core' import is restricted from being used by a pattern. Tauri APIs are desktop-only. Review frontend/DeveloperGuide.md for structure advice  no-restricted-imports
```
2026-03-30 14:24:16 +00:00
ConnorYohandGitHub 0e29640766 fix: get all Playwright E2E tests loading and expand CI to run full suite (#6009)
## Fix Playwright E2E tests and expand CI to run full suite

### Problem

The full Playwright suite was broken in two ways:

1. **`ConvertE2E.spec.ts` crashed at import time** —
`conversionEndpointDiscovery.ts` imported a React hook at the top level,
which pulled in the entire component tree. That chain eventually
required `material-symbols-icons.json` (a generated file that didn't
exist), crashing module resolution before any tests ran.

2. **CI only ran cert validation tests** — both `build.yml` and
`nightly.yml` hardcoded `src/core/tests/certValidation` as the test
path, silently ignoring everything else.

### Changes

**`ConvertE2E.spec.ts` — complete rewrite**
The old tests were useless in practice: all 9 dynamic conversion tests
were permanently skipped unless a real Spring Boot backend was running
(they called a live `/api/v1/config/endpoints-enabled` endpoint at
module load time). Replaced with 4 focused tests that use `page.route()`
mocking — no backend required, same pattern as
`CertificateValidationE2E`.

New tests cover:
- Convert button absent before a format pair is selected
- Successful PDF→PNG conversion shows a download button (mocked API
response)
- API error surfaces as an error notification
- Convert button appears and is enabled after selecting valid formats

**`conversionEndpointDiscovery.ts` — deleted**
Only existed to support the old tests. The `useConversionEndpoints`
React hook it exported was never imported anywhere else.

**`ReviewToolStep.tsx`**
Added `data-testid="download-result-button"` to the download button —
required for the happy-path test assertion.

**CI workflows (`build.yml`, `nightly.yml`)**
- Added a `Generate icons` step before Playwright runs (`node
scripts/generate-icons.js`) — the icon JSON is generated by `npm run
dev` locally but skipped by `npm ci` in CI
- Removed the `src/core/tests/certValidation` path filter so the full
suite runs
2026-03-30 11:27:55 +01:00
95 changed files with 4392 additions and 1888 deletions
+4 -2
View File
@@ -236,10 +236,12 @@ 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 src/core/tests/certValidation --project=chromium
run: cd frontend && npx playwright test --project=chromium
- name: Upload Playwright report
if: always()
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
@@ -511,7 +513,7 @@ jobs:
echo "base_image=stirling-pdf-base:pr-test" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
else
echo "base_image=ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "base_image=stirlingtools/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64,linux/arm64/v8" >> $GITHUB_OUTPUT
fi
+4 -1
View File
@@ -35,11 +35,14 @@ 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 src/core/tests/certValidation
run: cd frontend && npx playwright test
- name: Upload Playwright report
if: always()
@@ -112,8 +112,6 @@ 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.");
@@ -129,8 +127,17 @@ public class FileMonitor {
}
}
WatchKey key;
while ((key = watchService.poll()) != null) {
// 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) {
final Path watchingDir = (Path) key.watchable();
key.pollEvents()
.forEach(
@@ -167,6 +174,7 @@ 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,19 +1,22 @@
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.HashSet;
import java.util.EnumMap;
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;
@@ -21,6 +24,7 @@ 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;
@@ -35,7 +39,6 @@ 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;
@@ -48,61 +51,219 @@ import stirling.software.common.util.WebResponseUtils;
public class AutoSplitPdfController {
private static final Set<String> VALID_QR_CONTENTS =
new HashSet<>(
Set.of(
"https://github.com/Stirling-Tools/Stirling-PDF",
"https://github.com/Frooodle/Stirling-PDF",
"https://stirlingpdf.com"));
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));
}
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private final ApplicationProperties applicationProperties;
private static String decodeQRCode(BufferedImage bufferedImage) {
LuminanceSource source;
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");
/**
* 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;
}
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
/**
* 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 {
Result result = new MultiFormatReader().decode(bitmap);
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) {
return null; // there is no QR code in the image
// 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);
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++;
}
}
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;
}
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)
@@ -111,42 +272,56 @@ 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 < document.getNumberOfPages(); ++page) {
BufferedImage bim;
for (int page = 0; page < totalPages; ++page) {
PDPage pdPage = document.getPage(page);
int imageCount = countPageImages(pdPage);
// 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();
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);
}
final int dpi = renderDpi;
final int pageNum = page;
bim =
ExceptionUtils.handleOomRendering(
pageNum + 1,
dpi,
() -> pdfRenderer.renderImageWithDPI(pageNum, dpi));
String result = decodeQRCode(bim);
boolean isValidQrCode = qrResult != null && VALID_QR_CONTENTS.contains(qrResult);
if (isValidQrCode) {
log.info(
"Page {}/{} contains QR divider ('{}')",
page + 1,
totalPages,
qrResult);
}
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());
}
@@ -159,32 +334,25 @@ public class AutoSplitPdfController {
splitDocuments.add(firstDocument);
}
// If duplexMode is true and current page is a divider, then skip next page
if (duplexMode && isValidQrCode) {
page++;
page++; // skip back of divider 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()));
try (ZipOutputStream zipOut =
new ZipOutputStream(Files.newOutputStream(outputTempFile.getPath()))) {
// Stream split documents directly into zip — avoids holding all PDFs in memory
try (OutputStream fileOut = Files.newOutputStream(outputTempFile.getPath());
ZipOutputStream zipOut = new ZipOutputStream(fileOut)) {
for (int i = 0; i < splitDocuments.size(); i++) {
String fileName = filename + "_" + (i + 1) + ".pdf";
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.putNextEntry(new ZipEntry(fileName));
splitDocuments.get(i).save(zipOut);
zipOut.closeEntry();
}
}
@@ -197,7 +365,6 @@ 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,6 +47,7 @@ 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;
@@ -71,6 +72,7 @@ public class ProprietaryUIDataController {
private final UserLicenseSettingsService licenseSettingsService;
private final PersistentAuditEventRepository auditRepository;
private final MfaService mfaService;
private final LoginAttemptService loginAttemptService;
public ProprietaryUIDataController(
ApplicationProperties applicationProperties,
@@ -84,7 +86,8 @@ public class ProprietaryUIDataController {
@Qualifier("runningEE") boolean runningEE,
UserLicenseSettingsService licenseSettingsService,
PersistentAuditEventRepository auditRepository,
MfaService mfaService) {
MfaService mfaService,
LoginAttemptService loginAttemptService) {
this.applicationProperties = applicationProperties;
this.auditConfig = auditConfig;
this.sessionPersistentRegistry = sessionPersistentRegistry;
@@ -97,6 +100,7 @@ public class ProprietaryUIDataController {
this.licenseSettingsService = licenseSettingsService;
this.auditRepository = auditRepository;
this.mfaService = mfaService;
this.loginAttemptService = loginAttemptService;
}
/**
@@ -387,6 +391,7 @@ public class ProprietaryUIDataController {
data.setPremiumEnabled(premiumEnabled);
data.setMailEnabled(applicationProperties.getMail().isEnabled());
data.setUserSettings(userSettings);
data.setLockedUsers(loginAttemptService.getAllBlockedUsers());
return ResponseEntity.ok(data);
}
@@ -605,6 +610,7 @@ public class ProprietaryUIDataController {
private boolean premiumEnabled;
private boolean mailEnabled;
private Map<String, Map<String, String>> userSettings;
private List<String> lockedUsers;
}
@Data
@@ -159,10 +159,13 @@ public class SecurityConfiguration {
firewall.setAllowedHeaderValues(
headerValue -> headerValue != null && allowedChars.matcher(headerValue).matches());
// Apply the same rules to parameter values for consistency.
// Allow non-ASCII characters and newlines in parameter values.
Pattern allowedParamChars =
Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]\\r\\n]*");
firewall.setAllowedParameterValues(
parameterValue ->
parameterValue != null && allowedChars.matcher(parameterValue).matches());
parameterValue != null
&& allowedParamChars.matcher(parameterValue).matches());
return firewall;
}
@@ -48,6 +48,7 @@ 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;
@@ -67,6 +68,7 @@ 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")
@@ -775,6 +777,14 @@ 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,8 +1,11 @@
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;
@@ -79,6 +82,28 @@ 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,6 +29,7 @@ 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;
@@ -47,6 +48,7 @@ class ProprietaryUIDataControllerTest {
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private PersistentAuditEventRepository auditRepository;
@Mock private MfaService mfaService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private AuditConfigurationProperties auditConfig;
@@ -79,7 +81,8 @@ class ProprietaryUIDataControllerTest {
false,
licenseSettingsService,
auditRepository,
mfaService);
mfaService,
loginAttemptService);
}
@Test
@@ -28,6 +28,7 @@ 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;
@@ -47,6 +48,7 @@ class UserControllerTest {
@Mock private UserRepository userRepository;
@Mock private EmailService emailService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private MockMvc mockMvc;
@@ -65,7 +67,8 @@ class UserControllerTest {
teamRepository,
userRepository,
Optional.of(emailService),
licenseSettingsService);
licenseSettingsService,
loginAttemptService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@@ -138,4 +141,13 @@ 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,6 +6,7 @@ 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;
@@ -236,4 +237,145 @@ 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");
}
}
+47 -5
View File
@@ -338,7 +338,43 @@ RUN mkdir -p /magick-export/usr/bin \
cp -a /usr/local/etc/ImageMagick-7 /magick-export/usr/local/etc/
# Stage 4: Build Python venv
# 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
FROM ubuntu:noble AS python-venv-build
ARG TARGETPLATFORM
ARG UNOSERVER_VERSION=3.6
@@ -385,8 +421,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 \
ffmpeg poppler-utils fontforge \
gosu unpaper pngquant \
poppler-utils fontforge \
unpaper pngquant \
# Fonts: full coverage for standard + fat variants
fonts-dejavu \
fonts-liberation2 \
@@ -596,6 +632,13 @@ 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
@@ -622,8 +665,7 @@ 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; \
ln -sf /usr/sbin/gosu /usr/local/bin/su-exec
fi
# Application directories
RUN set -eux; \
+11
View File
@@ -0,0 +1,11 @@
-----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.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/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.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/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 \
su-exec && \
util-linux && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /tmp/stirling-pdf/heap_dumps && \
mkdir -p /usr/share/fonts/opentype/noto && \
# User permissions
+78
View File
@@ -45,6 +45,84 @@ 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:
+30 -5
View File
@@ -13,6 +13,11 @@ 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
@@ -30,10 +35,7 @@ export default defineConfig(
'no-restricted-imports': [
'error',
{
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)
],
patterns: baseRestrictedImportPatterns,
},
],
'@typescript-eslint/no-empty-object-type': [
@@ -59,9 +61,32 @@ 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/saas/**/*.{js,mjs,jsx,ts,tsx}'],
files: [
'src/proprietary/**/*.{js,mjs,jsx,ts,tsx}',
'src/saas/**/*.{js,mjs,jsx,ts,tsx}',
],
languageOptions: {
parserOptions: {
project: true,
+23 -1
View File
@@ -4856,7 +4856,7 @@ enableSepiaFilter = "Enable Sepia Filter"
firstPage = "First Page"
lastPage = "Last Page"
nextPage = "Next Page"
onlyPdfSupported = "The viewer only supports PDF files. This file appears to be a different format."
onlyPdfSupported = "This file format is not supported for preview."
previousPage = "Previous Page"
singlePageView = "Single Page View"
unknownFile = "Unknown file"
@@ -4864,6 +4864,21 @@ 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"
@@ -4881,6 +4896,7 @@ 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"
@@ -7978,6 +7994,7 @@ 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"
@@ -7986,6 +8003,8 @@ disable = "Disable"
disabled = "Disabled"
editRole = "Edit Role"
enable = "Enable"
locked = "locked"
lockedBadge = "Locked"
loading = "Loading people..."
loginRequired = "Enable login mode first"
member = "Member"
@@ -7995,6 +8014,9 @@ searchMembers = "Search members..."
status = "Status"
team = "Team"
title = "People"
unlockAccount = "Unlock Account"
unlockUserError = "Failed to unlock user account"
unlockUserSuccess = "User account unlocked successfully"
user = "User"
[workspace.people.actions]
File diff suppressed because it is too large Load Diff
@@ -5,6 +5,7 @@ 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';
@@ -51,6 +52,9 @@ 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();
@@ -345,13 +349,14 @@ const FileEditor = ({
}, [activeStirlingFileStubs, selectors, fileActions, removeFiles]);
const handleViewFile = useCallback((fileId: FileId) => {
const record = activeStirlingFileStubs.find(r => r.id === fileId);
if (record) {
// Set the file as selected in context and switch to viewer for preview
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
setSelectedFiles([fileId]);
setActiveFileIndex(index);
navActions.setWorkbench('viewer');
}
}, [activeStirlingFileStubs, setSelectedFiles, navActions.setWorkbench]);
}, [activeStirlingFileStubs, setSelectedFiles, setActiveFileIndex, navActions.setWorkbench]);
const handleLoadFromStorage = useCallback(async (selectedFiles: File[]) => {
if (selectedFiles.length === 0) return;
@@ -19,6 +19,8 @@ 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';
@@ -77,9 +79,8 @@ 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 = config?.storageSharingEnabled === true;
const shareLinksEnabled = config?.storageShareLinksEnabled === true;
const groupSigningEnabled = config?.storageGroupSigningEnabled === true;
const { sharingEnabled, shareLinksEnabled } = useSharingEnabled();
const groupSigningEnabled = useGroupSigningEnabled();
const isSignWorkbenchActive =
currentWorkbench === SIGN_REQUEST_WORKBENCH_TYPE ||
currentWorkbench === SESSION_DETAIL_WORKBENCH_TYPE;
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useMemo } from "react";
import React, { useState, useEffect } from "react";
import {
Paper,
Stack,
@@ -22,8 +22,7 @@ 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 { getVersion } from "@tauri-apps/api/app";
import { isTauri } from "@tauri-apps/api/core";
import { useFrontendVersionInfo } from "@app/hooks/useFrontendVersionInfo";
const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;
const BANNER_DISMISSED_KEY = "stirlingpdf_features_banner_dismissed";
@@ -46,10 +45,8 @@ 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 [mismatchVersion, setMismatchVersion] = useState(false);
const isTauriApp = useMemo(() => isTauri(), []);
const [appVersion, setAppVersion] = useState<string | null>(null);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading...");
const { appVersion, mismatchVersion } = useFrontendVersionInfo(config?.appVersion);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading..."); // null = loading, shown only when appVersion !== undefined
// Sync local state with preference changes
useEffect(() => {
@@ -91,52 +88,6 @@ 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;
@@ -239,7 +190,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
)}
</Group>
</div>
{isTauriApp && (
{appVersion !== undefined && (
<Group justify="space-between" align="center">
<div>
<Text size="sm" c="dimmed">
@@ -335,9 +335,7 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
formData.append('workflowMetadata', workflowMetadata);
}
await apiClient.post('/api/v1/security/cert-sign/sessions', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
await apiClient.post('/api/v1/security/cert-sign/sessions', formData);
alert({
alertType: 'success',
@@ -493,9 +491,7 @@ 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, {
headers: { 'Content-Type': 'multipart/form-data' },
});
await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`, certificateData);
alert({
alertType: 'success',
title: t('success'),
@@ -123,6 +123,7 @@ function ReviewStepContent<TParams = unknown>({
)}
{operation.downloadUrl && (
<Button
data-testid="download-result-button"
leftSection={<DownloadIcon />}
color="blue"
fullWidth
@@ -1,63 +1,4 @@
/* 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 Sidebar - Attachment-specific styles (base styles in SidebarBase.css) */
/* Attachment List */
.attachment-list {
@@ -6,6 +6,7 @@ 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 {
@@ -284,7 +285,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
return (
<Box
className="attachment-sidebar"
className="sidebar-base attachment-sidebar"
style={{
position: 'fixed',
right: `${(thumbnailVisible ? 15 : 0) + (bookmarkVisible ? 15 : 0)}rem`,
@@ -294,9 +295,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
zIndex: 998,
}}
>
<div className="attachment-sidebar__header">
<div className="attachment-sidebar__header-title">
<span className="attachment-sidebar__header-icon">
<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">
<AttachmentIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -305,7 +306,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</div>
</div>
<Box px="sm" pb="sm" className="attachment-sidebar__search">
<Box px="sm" pb="sm" className="sidebar-base__search attachment-sidebar__search">
<TextInput
value={searchTerm}
placeholder={t('viewer.attachments.searchPlaceholder', 'Search attachments')}
@@ -316,9 +317,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="attachment-sidebar__content">
<Box p="sm" className="sidebar-base__content attachment-sidebar__content">
{!attachmentSupport && (
<div className="attachment-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noSupport', 'Attachment support is unavailable for this viewer.')}
</Text>
@@ -326,7 +327,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && showNoDocument && (
<div className="attachment-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noDocument', 'Open a PDF to view its attachments.')}
</Text>
@@ -334,7 +335,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="attachment-sidebar__error">
<Stack gap="xs" align="center" className="sidebar-base__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -345,7 +346,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="attachment-sidebar__loading">
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
{t('viewer.attachments.loading', 'Loading attachments...')}
@@ -354,7 +355,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showEmptyState && (
<div className="attachment-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.empty', 'No attachments in this document')}
</Text>
@@ -368,7 +369,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showSearchEmpty && (
<div className="attachment-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noMatch', 'No attachments match your search')}
</Text>
@@ -1,63 +1,4 @@
/* 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 Sidebar - Bookmark-specific styles (base styles in SidebarBase.css) */
/* Bookmark List */
.bookmark-list {
@@ -193,4 +134,3 @@
animation: none;
}
}
@@ -4,6 +4,7 @@ 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 {
@@ -429,7 +430,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
return (
<Box
className="bookmark-sidebar"
className="sidebar-base bookmark-sidebar"
style={{
position: 'fixed',
right: thumbnailVisible ? SIDEBAR_WIDTH : 0,
@@ -439,9 +440,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
zIndex: 998,
}}
>
<div className="bookmark-sidebar__header">
<div className="bookmark-sidebar__header-title">
<span className="bookmark-sidebar__header-icon">
<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">
<BookmarksIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -475,7 +476,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
</div>
<Box px="sm" pb="sm" className="bookmark-sidebar__search">
<Box px="sm" pb="sm" className="sidebar-base__search bookmark-sidebar__search">
<TextInput
value={searchTerm}
placeholder="Search bookmarks"
@@ -486,9 +487,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="bookmark-sidebar__content">
<Box p="sm" className="sidebar-base__content bookmark-sidebar__content">
{!bookmarkSupport && (
<div className="bookmark-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
Bookmark support is unavailable for this viewer.
</Text>
@@ -496,7 +497,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && showNoDocument && (
<div className="bookmark-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
Open a PDF to view its bookmarks.
</Text>
@@ -504,7 +505,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="bookmark-sidebar__error">
<Stack gap="xs" align="center" className="sidebar-base__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -515,7 +516,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="bookmark-sidebar__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 bookmarks...
@@ -524,7 +525,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showEmptyState && (
<div className="bookmark-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks in this document
</Text>
@@ -538,7 +539,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showSearchEmpty && (
<div className="bookmark-sidebar__empty-state">
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks match your search
</Text>
@@ -10,6 +10,7 @@ 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';
@@ -24,6 +25,7 @@ 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 ────────────────────────────────────────────
@@ -125,6 +127,8 @@ const EmbedPdfViewerContent = ({
toggleThumbnailSidebar,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
setHasLayers,
isCommentsSidebarVisible,
isSearchInterfaceVisible,
searchInterfaceActions,
@@ -377,15 +381,19 @@ 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) and Ctrl+R (rotate) must be intercepted unconditionally
// Ctrl+P (print) 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 =
@@ -394,12 +402,15 @@ const EmbedPdfViewerContent = ({
(target as HTMLElement).isContentEditable;
if (!isInTextInput) {
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
const wasOverridden = viewerKeyCommand(event)
if (!wasOverridden){
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
}
}
}
}
@@ -506,7 +517,7 @@ const EmbedPdfViewerContent = ({
}, [
isViewerHovered, isSearchInterfaceVisible, zoomActions, searchInterfaceActions,
scrollActions, printActions, exportActions, rotationActions, historyApiRef,
viewerApplyChanges, cyclePdfRenderMode,
viewerApplyChanges, cyclePdfRenderMode, viewerKeyCommand,
]);
// Watch the annotation history API to detect when the document becomes "dirty".
@@ -700,6 +711,46 @@ 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)
@@ -919,6 +970,7 @@ const EmbedPdfViewerContent = ({
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) +
(isBookmarkSidebarVisible ? sidebarWidthRem : 0) +
(isAttachmentSidebarVisible ? sidebarWidthRem : 0) +
(isLayerSidebarVisible ? sidebarWidthRem : 0) +
(isCommentsSidebarVisible ? commentsSidebarWidthRem : 0);
return (
@@ -987,7 +1039,7 @@ const EmbedPdfViewerContent = ({
redactionTrackerRef={redactionTrackerRef as React.RefObject<RedactionPendingTrackerAPI>}
fileId={currentFileId}
isCommentsSidebarVisible={isCommentsSidebarVisible}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0)}rem`}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0) + (isLayerSidebarVisible ? sidebarWidthRem : 0)}rem`}
onSignatureAdded={() => {
// Handle signature added - for debugging, enable console logs as needed
// Future: Handle signature completion
@@ -1057,6 +1109,18 @@ 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 && (
@@ -0,0 +1,140 @@
/* 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;
}
}
@@ -0,0 +1,377 @@
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,6 +4,7 @@ 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';
@@ -94,15 +95,17 @@ 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(() => {
@@ -0,0 +1,113 @@
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;
@@ -0,0 +1,61 @@
/* 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;
}
+20 -9
View File
@@ -1,16 +1,27 @@
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 interface ViewerProps {
sidebarsVisible: boolean;
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
activeFileIndex?: number;
setActiveFileIndex?: (index: number) => void;
}
export type { ViewerProps };
const Viewer = (props: ViewerProps) => {
// Default to EmbedPDF viewer
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} />;
}
return <EmbedPdfViewer {...props} />;
};
@@ -0,0 +1,228 @@
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;
}
@@ -0,0 +1,191 @@
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>
);
}
@@ -0,0 +1,36 @@
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>
);
}
@@ -0,0 +1,44 @@
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>
);
}
@@ -0,0 +1,57 @@
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>
);
}
@@ -0,0 +1,53 @@
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>
);
}
@@ -0,0 +1,192 @@
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>
);
}
@@ -0,0 +1,51 @@
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,6 +16,7 @@ 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';
@@ -26,7 +27,7 @@ export function useViewerRightRailButtons(
) {
const { t, i18n } = useTranslation();
const viewer = useViewer();
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isLayerSidebarVisible, hasLayers, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const [isPanning, setIsPanning] = useState<boolean>(() => viewer.getPanState()?.isPanning ?? false);
const { sidebarRefs } = useSidebarContext();
const { position: tooltipPosition } = useRightRailTooltipSide(sidebarRefs, 12);
@@ -83,6 +84,7 @@ 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');
@@ -236,6 +238,18 @@ 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" />,
@@ -424,6 +438,8 @@ export function useViewerRightRailButtons(
isThumbnailSidebarVisible,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
hasLayers,
isSearchInterfaceVisible,
isPanning,
searchLabel,
@@ -434,6 +450,7 @@ export function useViewerRightRailButtons(
sidebarLabel,
bookmarkLabel,
attachmentLabel,
layersLabel,
printLabel,
tooltipPosition,
annotationsLabel,
@@ -86,6 +86,10 @@ 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;
@@ -188,6 +192,8 @@ 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;
@@ -289,6 +295,10 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
setIsAttachmentSidebarVisible(prev => !prev);
};
const toggleLayerSidebar = () => {
setIsLayerSidebarVisible(prev => !prev);
};
const setCommentsSidebarVisible = (visible: boolean) => {
setIsCommentsSidebarVisible(visible);
};
@@ -454,6 +464,10 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
toggleBookmarkSidebar,
isAttachmentSidebarVisible,
toggleAttachmentSidebar,
isLayerSidebarVisible,
toggleLayerSidebar,
hasLayers,
setHasLayers,
isCommentsSidebarVisible,
setCommentsSidebarVisible,
toggleCommentsSidebar,
@@ -0,0 +1,8 @@
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 };
}
@@ -0,0 +1,10 @@
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;
}
@@ -0,0 +1,18 @@
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,
};
}
@@ -0,0 +1,4 @@
// Default implementation for non-desktop environments (overridden in desktop)
export function useViewerKeyCommand(): (event: KeyboardEvent) => boolean {
return () => false;
}
+151 -458
View File
@@ -1,491 +1,184 @@
/**
* End-to-End Tests for Convert Tool
*
* 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
* 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).
*/
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';
import { test, expect, type Page } from '@playwright/test';
import path from 'path';
// Test configuration
const BASE_URL = process.env.BASE_URL || 'http://localhost:5173';
const FIXTURES_DIR = path.join(__dirname, '../test-fixtures');
const SAMPLE_PDF = path.join(FIXTURES_DIR, 'sample.pdf');
/**
* 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();
// ---------------------------------------------------------------------------
// 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 }])
);
// 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;
}
// ---------------------------------------------------------------------------
// 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 src/tests/test-fixtures/ (from frontend directory)
const frontendPath = path.join(cwd, 'src', 'tests', 'test-fixtures', filename);
if (fs.existsSync(frontendPath)) {
return frontendPath;
}
// 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 relative path from current test file location
const relativePath = path.join(__dirname, '..', 'test-fixtures', filename);
if (fs.existsSync(relativePath)) {
return relativePath;
}
// 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'] },
})
);
// Fallback to the original path format (should work from top-level)
return path.join('.', 'frontend', 'src', 'tests', 'test-fixtures', filename);
// 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: {} })
);
}
// 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
// ---------------------------------------------------------------------------
// 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();
await page.waitForSelector('.mantine-Modal-overlay', { state: 'visible', timeout: 5000 });
//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 });
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 });
}
/**
* 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
// ---------------------------------------------------------------------------
// 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();
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(',');
}
}
}
// 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}`);
});
}
});
// ---------------------------------------------------------------------------
// 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();
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe('Convert Tool', () => {
test.beforeEach(async ({ page }) => {
// 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 mockAppApis(page);
await page.goto('/?bypassOnboarding=true');
await page.waitForSelector('[data-testid="files-button"]', { timeout: 10000 });
});
test.describe('Dynamic Conversion Tests', () => {
test('convert button is disabled before a TO format is selected', async ({ page }) => {
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
// 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);
});
// 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();
});
test.describe('Static Tests', () => {
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 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 page.route('**/api/v1/convert/pdf/img', (route) =>
route.fulfill({
status: 200,
contentType: 'image/png',
headers: { 'Content-Disposition': 'attachment; filename="sample.png"' },
body: fakePng,
})
);
// Click the Convert tool button
await page.click('[data-testid="tool-convert"]');
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
await selectToFormat(page, 'png');
await page.getByTestId('convert-button').click();
// Wait for convert mode and select file
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 5000 });
await page.click('[data-testid="file-thumbnail-checkbox"]');
await expect(page.getByTestId('download-result-button')).toBeVisible({ timeout: 10000 });
});
// Don't select any formats - convert button should not exist
const convertButton = page.locator('[data-testid="convert-button"]');
await expect(convertButton).toHaveCount(0);
});
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 });
});
});
@@ -1,325 +0,0 @@
/**
* 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;
const hasResults = convertOperation.files.length > 0 || convertOperation.downloadUrl !== null || !!convertOperation.errorMessage;
const settingsCollapsed = hasResults;
// When operation completes, flag the next selection change to skip reset
+42
View File
@@ -97,3 +97,45 @@ 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';
}
@@ -0,0 +1,44 @@
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 };
}
@@ -0,0 +1,12 @@
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;
}
@@ -0,0 +1,41 @@
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 };
}
@@ -0,0 +1,18 @@
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,
};
}
@@ -0,0 +1,20 @@
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,48 +218,26 @@ 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;
});
const httpResponse: TauriHttpResponse<T> = {
data,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
// Check for HTTP errors
// 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 = '';
}
// Create more descriptive error messages based on status code
let errorMessage = `Request failed with status code ${response.status}`;
let errorMessage = errorBody || `Request failed with status code ${response.status}`;
let errorCode = 'ERR_BAD_REQUEST';
if (response.status === 401) {
@@ -284,13 +262,22 @@ 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,
httpResponse
errorResponse
);
// Run error interceptors
@@ -307,6 +294,39 @@ 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 } from 'axios';
import { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } 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 any);
} as unknown as AxiosResponse);
const result = await springAuth.getSession();
@@ -74,7 +74,7 @@ describe('SpringAuthClient', () => {
statusText: 'Unauthorized',
data: {},
headers: {},
config: {} as any,
config: {} as InternalAxiosRequestConfig,
}
);
@@ -102,7 +102,7 @@ describe('SpringAuthClient', () => {
statusText: 'Forbidden',
data: {},
headers: {},
config: {} as any,
config: {} as InternalAxiosRequestConfig,
}
);
@@ -141,7 +141,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as any);
} as unknown as AxiosResponse);
// 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 any);
} as unknown as AxiosResponse);
const result = await springAuth.signUp(credentials);
@@ -259,7 +259,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: {},
} as any);
} as unknown as AxiosResponse);
const result = await springAuth.signOut();
@@ -308,7 +308,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as any);
} as unknown as AxiosResponse);
const result = await springAuth.refreshSession();
@@ -85,7 +85,7 @@ export interface User {
is_anonymous?: boolean;
isFirstLogin?: boolean;
authenticationType?: string;
app_metadata?: Record<string, any>;
app_metadata?: Record<string, unknown>;
}
export interface Session {
@@ -447,7 +447,7 @@ class SpringAuthClient {
*/
async signInWithOAuth(params: {
provider: OAuthProvider;
options?: { redirectTo?: string; queryParams?: Record<string, any> };
options?: { redirectTo?: string; queryParams?: Record<string, string> };
}): Promise<{ error: AuthError | null }> {
try {
const redirectPath = normalizeRedirectPath(params.options?.redirectTo);
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
ActionIcon,
@@ -125,8 +126,10 @@ export default function ChangeUserPasswordModal({ opened, onClose, user, onSucce
alert({ alertType: 'success', title: t('workspace.people.changePassword.success', 'Password updated successfully') });
onSuccess();
handleClose();
} catch (error: any) {
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.changePassword.error', 'Failed to update password');
} 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');
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 any]: opacity } : style;
const styleWithOpacity = opacity !== undefined ? { ...(style || {}), ['--text-divider-opacity' as string]: opacity } : style;
if (text) {
return (
@@ -1,4 +1,5 @@
import { useState, useEffect, useRef } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Modal,
@@ -158,9 +159,11 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
forceChange: false,
forceMFA: false,
});
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to invite user:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.addMember.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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -211,12 +214,11 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
body: response.errors || response.error
});
}
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to invite users:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.emailInvite.error', 'Failed to send invites');
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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -239,9 +241,11 @@ 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: any) {
} catch (error: unknown) {
console.error('Failed to generate invite link:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.inviteLink.error', 'Failed to generate invite link');
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');
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: any) {
} catch (error: unknown) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: error.message || 'Please try again or contact support.',
body: (error instanceof Error ? error.message : undefined) || '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,4 +1,5 @@
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';
@@ -72,7 +73,7 @@ export default function AdminAdvancedSection() {
isFieldPending,
} = useAdminSettings<AdvancedSettingsData>({
sectionName: 'advanced',
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, any> }> => {
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, unknown> }> => {
const [systemResponse, processExecutorResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/system'),
apiClient.get('/api/v1/admin/settings/section/processExecutor')
@@ -81,7 +82,7 @@ export default function AdminAdvancedSection() {
const systemData = systemResponse.data || {};
const processExecutorData = processExecutorResponse.data || {};
const result: AdvancedSettingsData & { _pending?: Record<string, any> } = {
const result: AdvancedSettingsData & { _pending?: Record<string, unknown> } = {
enableAlphaFunctionality: systemData.enableAlphaFunctionality || false,
maxDPI: systemData.maxDPI || 0,
enableUrlToPDF: systemData.enableUrlToPDF || false,
@@ -101,7 +102,7 @@ export default function AdminAdvancedSection() {
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, any> = {};
const pendingBlock: Record<string, unknown> = {};
if (systemData._pending?.enableAlphaFunctionality !== undefined) {
pendingBlock.enableAlphaFunctionality = systemData._pending.enableAlphaFunctionality;
}
@@ -131,7 +132,7 @@ export default function AdminAdvancedSection() {
return result;
},
saveTransformer: (settings) => {
const deltaSettings: Record<string, any> = {
const deltaSettings: Record<string, unknown> = {
'system.enableAlphaFunctionality': settings.enableAlphaFunctionality,
'system.maxDPI': settings.maxDPI,
'system.enableUrlToPDF': settings.enableUrlToPDF,
@@ -281,9 +282,8 @@ export default function AdminAdvancedSection() {
setManualDownloadLinks([]);
} catch (error) {
console.error('[AdminAdvancedSection] Download tessdata languages failed', error);
const response = (error as any)?.response;
const status = response?.status;
const serverMessage = response?.data?.message;
const status = isAxiosError(error) ? error.response?.status : undefined;
const serverMessage = isAxiosError(error) ? error.response?.data?.message : undefined;
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 (!response) {
if (!isAxiosError(error) || !error.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 >= 500) {
} else if (status !== undefined && status >= 500) {
message = t(
'admin.settings.advanced.tessdataDir.downloadErrorServer',
'The server encountered an error while downloading tessdata languages. Please try again later.'
@@ -1,4 +1,5 @@
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';
@@ -35,9 +36,9 @@ const AdminAuditSection: React.FC = () => {
setError(null);
const status = await auditService.getSystemStatus();
setSystemStatus(status);
} catch (err: any) {
} catch (err: unknown) {
// Check if this is a permission/license error (403/404)
const status = err?.response?.status;
const status = isAxiosError(err) ? err.response?.status : undefined;
if (status === 403 || status === 404) {
setError('enterprise-license-required');
} else {
@@ -44,6 +44,66 @@ 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;
@@ -55,22 +115,10 @@ interface ConnectionsSettingsData {
blockRegistration?: boolean;
useAsUsername?: string;
scopes?: string;
client?: {
[key: string]: any;
};
};
saml2?: {
[key: string]: any;
};
mail?: {
enabled?: boolean;
enableInvites?: boolean;
host?: string;
port?: number;
username?: string;
password?: string;
from?: string;
client?: Record<string, OAuth2ClientSettings>;
};
saml2?: Saml2Settings;
mail?: MailSettings;
telegram?: TelegramSettingsData;
ssoAutoLogin?: boolean;
enableMobileScanner?: boolean;
@@ -93,7 +141,7 @@ export default function AdminConnectionsSection() {
const adminSettings = useAdminSettings<ConnectionsSettingsData>({
sectionName: 'connections',
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, any> }> => {
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, unknown> }> => {
// Fetch security settings (oauth2, saml2)
const securityResponse = await apiClient.get('/api/v1/admin/settings/section/security');
const securityData = securityResponse.data || {};
@@ -114,7 +162,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, any> } = {
const result: ConnectionsSettingsData & { _pending?: Record<string, unknown> } = {
oauth2: securityData.oauth2 || {},
saml2: securityData.saml2 || {},
mail: mailData || {},
@@ -132,7 +180,7 @@ export default function AdminConnectionsSection() {
};
// Merge pending blocks from all endpoints
const pendingBlock: Record<string, any> = {};
const pendingBlock: Record<string, unknown> = {};
if (securityData._pending?.oauth2) {
pendingBlock.oauth2 = securityData._pending.oauth2;
}
@@ -183,13 +231,13 @@ export default function AdminConnectionsSection() {
return result;
},
saveTransformer: (currentSettings: ConnectionsSettingsData) => {
const deltaSettings: Record<string, any> = {};
const deltaSettings: Record<string, unknown> = {};
// 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, any>)[key];
deltaSettings[`security.oauth2.${key}`] = (currentSettings.oauth2 as Record<string, unknown>)[key];
}
});
@@ -197,7 +245,7 @@ export default function AdminConnectionsSection() {
const oauth2Client = currentSettings.oauth2.client;
if (oauth2Client) {
Object.keys(oauth2Client).forEach((providerId) => {
const providerSettings = oauth2Client[providerId];
const providerSettings = oauth2Client[providerId] as Record<string, unknown>;
Object.keys(providerSettings).forEach((key) => {
deltaSettings[`security.oauth2.client.${providerId}.${key}`] = providerSettings[key];
});
@@ -207,22 +255,25 @@ export default function AdminConnectionsSection() {
// Build delta for saml2 settings
if (currentSettings.saml2) {
Object.keys(currentSettings.saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = (currentSettings.saml2 as Record<string, any>)[key];
const saml2 = currentSettings.saml2 as Record<string, unknown>;
Object.keys(saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = saml2[key];
});
}
// Mail settings
if (currentSettings.mail) {
Object.keys(currentSettings.mail).forEach((key) => {
deltaSettings[`mail.${key}`] = (currentSettings.mail as Record<string, any>)[key];
const mail = currentSettings.mail as Record<string, unknown>;
Object.keys(mail).forEach((key) => {
deltaSettings[`mail.${key}`] = mail[key];
});
}
// Telegram settings
if (currentSettings.telegram) {
Object.keys(currentSettings.telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = (currentSettings.telegram as Record<string, any>)[key];
const telegram = currentSettings.telegram as Record<string, unknown>;
Object.keys(telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = telegram[key];
});
}
@@ -332,7 +383,7 @@ export default function AdminConnectionsSection() {
return !!(providerSettings?.clientId);
};
const getProviderSettings = (provider: Provider): Record<string, any> => {
const getProviderSettings = (provider: Provider): ProviderSettings => {
if (provider.id === 'saml2') {
return settings?.saml2 || {};
}
@@ -346,17 +397,17 @@ export default function AdminConnectionsSection() {
}
if (provider.id === 'googledrive') {
return {
const gd: GoogleDriveSettings = {
enabled: settings?.googleDriveEnabled,
clientId: settings?.googleDriveClientId,
apiKey: settings?.googleDriveApiKey,
appId: settings?.googleDriveAppId,
};
return gd;
}
if (provider.id === 'oauth2-generic') {
// Generic OAuth2 settings are at the root oauth2 level
return {
const generic: OAuth2GenericSettings = {
enabled: settings?.oauth2?.enabled,
provider: settings?.oauth2?.provider,
issuer: settings?.oauth2?.issuer,
@@ -367,6 +418,7 @@ export default function AdminConnectionsSection() {
autoCreateUser: settings?.oauth2?.autoCreateUser,
blockRegistration: settings?.oauth2?.blockRegistration,
};
return generic;
}
// Specific OAuth2 provider settings
@@ -386,32 +438,35 @@ 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, any>) => {
const updateProviderSettings = (provider: Provider, updatedSettings: Record<string, unknown>) => {
if (provider.id === 'smtp') {
setSettings({ ...settings, mail: updatedSettings });
setSettings({ ...settings, mail: updatedSettings as MailSettings });
} else if (provider.id === 'telegram') {
setSettings({ ...settings, telegram: updatedSettings });
setSettings({ ...settings, telegram: updatedSettings as TelegramSettingsData });
} else if (provider.id === 'googledrive') {
const gd = updatedSettings as GoogleDriveSettings;
setSettings({
...settings,
googleDriveEnabled: updatedSettings.enabled,
googleDriveClientId: updatedSettings.clientId,
googleDriveApiKey: updatedSettings.apiKey,
googleDriveAppId: updatedSettings.appId,
googleDriveEnabled: gd.enabled,
googleDriveClientId: gd.clientId,
googleDriveApiKey: gd.apiKey,
googleDriveAppId: gd.appId,
});
} else if (provider.id === 'saml2') {
setSettings({ ...settings, saml2: updatedSettings });
setSettings({ ...settings, saml2: updatedSettings as Saml2Settings });
} else if (provider.id === 'oauth2-generic') {
setSettings({ ...settings, oauth2: updatedSettings });
const generic = updatedSettings as OAuth2GenericSettings;
setSettings({ ...settings, oauth2: { ...settings.oauth2, ...generic } });
} else {
// Specific OAuth2 provider
const clientSettings = updatedSettings as OAuth2ClientSettings;
setSettings({
...settings,
oauth2: {
...settings.oauth2,
client: {
...settings.oauth2?.client,
[provider.id]: updatedSettings
[provider.id]: clientSettings,
}
}
});
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { isAxiosError } from "axios";
import { useTranslation } from "react-i18next";
import {
NumberInput,
@@ -68,7 +69,7 @@ export default function AdminDatabaseSection() {
const { settings, setSettings, loading, saving, fetchSettings, saveSettings, isFieldPending } =
useAdminSettings<DatabaseSettingsData>({
sectionName: "database",
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, any> }> => {
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, unknown> }> => {
const response = await apiClient.get("/api/v1/admin/settings/section/system");
const systemData = response.data || {};
@@ -85,7 +86,7 @@ export default function AdminDatabaseSection() {
};
// Map pending changes from system._pending.datasource to root level
const result: DatabaseSettingsData & { _pending?: Record<string, any> } = { ...datasource };
const result: DatabaseSettingsData & { _pending?: Record<string, unknown> } = { ...datasource };
if (systemData._pending?.datasource) {
result._pending = systemData._pending.datasource;
}
@@ -94,7 +95,7 @@ export default function AdminDatabaseSection() {
},
saveTransformer: (settings: DatabaseSettingsData) => {
// Convert flat settings to dot-notation for delta endpoint
const deltaSettings: Record<string, any> = {
const deltaSettings: Record<string, unknown> = {
"system.datasource.enableCustomDatabase": settings.enableCustomDatabase,
"system.datasource.customDatabaseUrl": settings.customDatabaseUrl,
"system.datasource.username": settings.username,
@@ -141,8 +142,8 @@ export default function AdminDatabaseSection() {
const data = await databaseManagementService.getDatabaseData();
setBackupFiles(data.backupFiles || []);
setDatabaseVersion(data.databaseVersion || null);
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
alert({
alertType: "error",
title: t("admin.settings.database.loadError", "Failed to load database backups"),
@@ -189,8 +190,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.createBackup();
alert({ alertType: "success", title: t("admin.settings.database.backupCreated", "Backup created successfully") });
await loadBackupData();
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
alert({
alertType: "error",
title: t("admin.settings.database.backupFailed", "Failed to create backup"),
@@ -209,8 +210,8 @@ export default function AdminDatabaseSection() {
alert({ alertType: "success", title: t("admin.settings.database.importSuccess", "Backup imported successfully") });
setUploadFile(null);
await loadBackupData();
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -270,8 +271,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: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -289,8 +290,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.deleteBackup(fileName);
alert({ alertType: "success", title: t("admin.settings.database.deleteSuccess", "Backup deleted") });
await loadBackupData();
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
alert({
alertType: "error",
title: t("admin.settings.database.deleteFailed", "Failed to delete backup"),
@@ -320,8 +321,8 @@ export default function AdminDatabaseSection() {
link.download = fileName;
document.body.appendChild(link);
link.click();
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
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, any> }> => {
fetchTransformer: async (): Promise<FeaturesSettingsData & { _pending?: Record<string, unknown> }> => {
const systemResponse = await apiClient.get('/api/v1/admin/settings/section/system');
const systemData = systemResponse.data || {};
const result: FeaturesSettingsData & { _pending?: Record<string, any> } = {
const result: FeaturesSettingsData & { _pending?: Record<string, unknown> } = {
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, any> = {};
const deltaSettings: Record<string, unknown> = {};
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, any> }> => {
fetchTransformer: async (): Promise<GeneralSettingsData & { _pending?: Record<string, unknown> }> => {
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, any> } = {
const result: GeneralSettingsData & { _pending?: Record<string, unknown> } = {
ui,
system,
customPaths: {
@@ -140,7 +140,7 @@ export default function AdminGeneralSection() {
};
// Merge pending blocks from all three endpoints
const pendingBlock: Record<string, any> = {};
const pendingBlock: Record<string, unknown> = {};
if (ui._pending) {
pendingBlock.ui = ui._pending;
}
@@ -161,7 +161,7 @@ export default function AdminGeneralSection() {
return result;
},
saveTransformer: (settings: GeneralSettingsData) => {
const deltaSettings: Record<string, any> = {
const deltaSettings: Record<string, unknown> = {
// 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: any) {
} catch (error: unknown) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: error.message || 'Please try again or contact support.',
body: (error instanceof Error ? error.message : undefined) || '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, any> }> => {
fetchTransformer: async (): Promise<PrivacySettingsData & { _pending?: Record<string, unknown> }> => {
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, any> } = {
const result: PrivacySettingsData & { _pending?: Record<string, unknown> } = {
enableAnalytics: system.enableAnalytics || false,
googleVisibility: system.googlevisibility || false,
metricsEnabled: metrics.enabled || false
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, any> = {};
const pendingBlock: Record<string, unknown> = {};
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, any> }> => {
fetchTransformer: async (): Promise<SecuritySettingsData & { _pending?: Record<string, unknown> }> => {
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, any> } = {
const combined: SecuritySettingsData & { _pending?: Record<string, unknown> } = {
...securityActive
};
@@ -108,7 +108,7 @@ export default function AdminSecuritySection() {
}
// Merge all _pending blocks
const mergedPending: Record<string, any> = {};
const mergedPending: Record<string, unknown> = {};
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, any> = {
const deltaSettings: Record<string, unknown> = {
// 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 as number)
? Math.max(0, data?.totalVisits ?? 0)
: displayedVisits;
const totalEndpoints = Number.isFinite(data?.totalEndpoints)
? Math.max(0, data?.totalEndpoints as number)
? Math.max(0, data?.totalEndpoints ?? 0)
: endpoints.length;
const displayedPercentage = totalVisits > 0
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -17,6 +18,7 @@ import {
CloseButton,
Avatar,
Box,
type ComboboxItem,
} from '@mantine/core';
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
@@ -51,6 +53,7 @@ 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<{
@@ -80,6 +83,7 @@ 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({
@@ -112,7 +116,7 @@ export default function PeopleSection() {
...user,
isActive: adminData.userSessions[user.username] || false,
lastRequest: adminData.userLastRequest[user.username] || undefined,
mfaEnabled: adminData.userSettings?.[user.username]?.mfaEnabled === 'true',
mfaEnabled: (adminData.userSettings?.[user.username] as Record<string, unknown> | undefined)?.mfaEnabled === 'true',
}));
setUsers(enrichedUsers);
@@ -128,6 +132,7 @@ export default function PeopleSection() {
totalUsers: adminData.totalUsers,
});
setMailEnabled(adminData.mailEnabled);
setLockedUsers(adminData.lockedUsers || []);
} else {
// Provide example data when login is disabled
const exampleUsers: User[] = [
@@ -189,6 +194,7 @@ export default function PeopleSection() {
setUsers(exampleUsers);
setTeams(exampleTeams);
setMailEnabled(false);
setLockedUsers([]);
// Example license information
setLicenseInfo({
@@ -221,12 +227,11 @@ export default function PeopleSection() {
alert({ alertType: 'success', title: t('workspace.people.editMember.success') });
closeEditModal();
fetchData();
} catch (error: any) {
} catch (error: unknown) {
console.error('[PeopleSection] Failed to update user:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.editMember.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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -238,12 +243,11 @@ export default function PeopleSection() {
await userManagementService.toggleUserEnabled(user.username, !user.enabled);
alert({ alertType: 'success', title: t('workspace.people.toggleEnabled.success') });
fetchData();
} catch (error: any) {
} catch (error: unknown) {
console.error('[PeopleSection] Failed to toggle user status:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.toggleEnabled.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');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -258,12 +262,31 @@ export default function PeopleSection() {
await userManagementService.deleteUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.deleteUserSuccess', 'User deleted successfully') });
fetchData();
} catch (error: any) {
} catch (error: unknown) {
console.error('[PeopleSection] Failed to delete user:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
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');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -315,9 +338,9 @@ export default function PeopleSection() {
},
];
const renderRoleOption = ({ option }: { option: any }) => (
const renderRoleOption = ({ option }: { option: ComboboxItem & { icon?: string; description?: string } }) => (
<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 }}>
@@ -389,6 +412,12 @@ 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')}
@@ -497,22 +526,29 @@ export default function PeopleSection() {
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<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>
<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>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -612,6 +648,15 @@ 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 />
@@ -622,12 +667,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: any) {
} catch (error: unknown) {
console.error('[PeopleSection] Failed to disable MFA for user:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.mfa.adminDisableError', 'Failed to disable MFA for user');
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');
alert({ alertType: 'error', title: errorMessage });
}
}}
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -51,6 +52,9 @@ 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();
@@ -75,6 +79,7 @@ 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') });
@@ -106,12 +111,11 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setAddMemberModalOpened(false);
setSelectedUserId('');
fetchTeamDetails();
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to add member:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.addMemberToTeam.error', 'Failed to add user to team');
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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -136,12 +140,11 @@ 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: any) {
} catch (error: unknown) {
console.error('Failed to remove member:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.removeMemberError', 'Failed to remove user from team');
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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -159,18 +162,37 @@ 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: any) {
} catch (error: unknown) {
console.error('Failed to delete user:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
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 });
} 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() || '');
@@ -201,12 +223,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setSelectedUser(null);
setSelectedTeamId('');
fetchTeamDetails();
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to change team:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.changeTeam.error', 'Failed to change team');
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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -335,22 +357,29 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<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>
<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>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -420,6 +449,15 @@ 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,4 +1,5 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -83,12 +84,11 @@ export default function TeamsSection() {
setNewTeamName('');
setCreateModalOpened(false);
await fetchTeams();
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to create team:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.createTeam.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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -109,12 +109,11 @@ export default function TeamsSection() {
setSelectedTeam(null);
setRenameModalOpened(false);
await fetchTeams();
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to rename team:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.renameTeam.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');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -135,12 +134,12 @@ export default function TeamsSection() {
await teamService.deleteTeam(team.id);
alert({ alertType: 'success', title: t('workspace.teams.deleteTeam.success') });
await fetchTeams();
} catch (error: any) {
} catch (error: unknown) {
console.error('Failed to delete team:', error);
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.deleteTeam.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');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -15,7 +15,7 @@ import {
UnstyledButton,
} from '@mantine/core';
import { useTranslation } from 'react-i18next';
import auditService, { AuditEvent } from '@app/services/auditService';
import auditService, { AuditEvent, AuditFilters } 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 typeof filters, value: any) => {
const handleFilterChangeWithReset = (key: keyof AuditFilters, value: AuditFilters[keyof AuditFilters]) => {
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: any;
let bVal: any;
let aVal: string | number | undefined;
let bVal: string | number | undefined;
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, any>;
const details = event.details as Record<string, unknown>;
const files = details.files;
if (Array.isArray(files) && files.length > 0) {
const firstFile = files[0] as Record<string, any>;
documentName = firstFile.name || '';
const firstFile = files[0] as Record<string, unknown>;
documentName = typeof firstFile.name === 'string' ? firstFile.name : '';
if (showAuthor || showFileHash) {
author = firstFile.pdfAuthor || '';
fileHash = firstFile.fileHash ? firstFile.fileHash.substring(0, 16) + '...' : '';
author = typeof firstFile.pdfAuthor === 'string' ? firstFile.pdfAuthor : '';
fileHash = typeof firstFile.fileHash === 'string' ? 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 as keyof typeof selectedFields]).join(',');
const fieldsParam = Object.keys(selectedFields).filter(k => selectedFields[k]).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: any) => void;
onFilterChange: (key: keyof AuditFilters, value: AuditFilters[keyof AuditFilters]) => 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: any) => {
onFilterChange('startDate', value ? formatDateToYMD(value as Date) : undefined);
onChange={(value) => {
onFilterChange('startDate', value ? formatDateToYMD(new Date(value)) : 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: any) => {
onFilterChange('endDate', value ? formatDateToYMD(value as Date) : undefined);
onChange={(value) => {
onFilterChange('endDate', value ? formatDateToYMD(new Date(value)) : 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!,
isMounted: () => isMountedRef.current ?? false,
onStatusChange: setPollingStatus,
});
@@ -23,7 +23,7 @@ export const useLicensePolling = (
// Activate the license key
const activation = await activateLicenseKey(result.licenseKey, {
isMounted: () => isMountedRef.current!,
isMounted: () => isMountedRef.current ?? false,
onActivated: onLicenseActivated,
});
@@ -112,8 +112,8 @@ const ParticipantView: React.FC<ParticipantViewProps> = ({ token }) => {
showLogo: true,
});
setNotification({ type: 'success', message: 'Signature submitted successfully!' });
} catch (err: any) {
setNotification({ type: 'error', message: `Failed to submit signature: ${err.message}` });
} catch (err: unknown) {
setNotification({ type: 'error', message: `Failed to submit signature: ${err instanceof Error ? err.message : String(err)}` });
} 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: any) {
setNotification({ type: 'error', message: `Failed to decline: ${err.message}` });
} catch (err: unknown) {
setNotification({ type: 'error', message: `Failed to decline: ${err instanceof Error ? err.message : String(err)}` });
}
}
};
@@ -8,6 +8,7 @@ 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';
@@ -95,13 +96,8 @@ function getErrorMessage(error: unknown): string {
if (typeof error === 'string') {
return error;
}
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 (isAxiosError(error) && typeof error.response?.data?.message === 'string') {
return error.response.data.message;
}
if (error instanceof Error) {
return error.message;
@@ -196,7 +192,7 @@ export function ServerExperienceProvider({ children }: { children: ReactNode })
(
await apiClient.get<{ totalUsers?: number }>(
'/api/v1/proprietary/ui-data/admin-settings',
{ suppressErrorToast: true } as any,
{ suppressErrorToast: true },
)
).data;
const totalUsers =
@@ -219,7 +215,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,4 +1,5 @@
import { useState, useCallback, useEffect } from 'react';
import { isAxiosError } from 'axios';
import workflowService, {
WorkflowSessionResponse,
ParticipantResponse,
@@ -35,9 +36,10 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
]);
setSession(sessionData);
setParticipant(participantData);
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to load session';
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to load session';
setError(errorMsg);
} finally {
setLoading(false);
@@ -55,9 +57,10 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
if (request.participantToken) {
await loadSession(request.participantToken);
}
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to submit signature';
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to submit signature';
setError(errorMsg);
throw new Error(errorMsg, { cause: err });
} finally {
@@ -79,9 +82,10 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
setParticipant(updatedParticipant);
// Reload session
await loadSession(token);
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to decline';
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to decline';
setError(errorMsg);
throw new Error(errorMsg, { cause: err });
} finally {
@@ -104,9 +108,10 @@ export const useParticipantSession = (token?: string): UseParticipantSessionResu
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err: any) {
const errorMsg =
err.response?.data?.message || err.message || 'Failed to download document';
} catch (err: unknown) {
const errorMsg = isAxiosError(err)
? (err.response?.data?.message || err.message)
: (err instanceof Error ? err.message : undefined) || 'Failed to download document';
setError(errorMsg);
} finally {
setLoading(false);
@@ -1,4 +1,5 @@
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';
@@ -56,14 +57,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: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.validationError', 'Failed to validate invitation link');
} 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');
setError(errorMessage);
} finally {
setLoading(false);
@@ -108,15 +109,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: any) {
const errorMessage =
err.response?.data?.error ||
err.message ||
t('invite.acceptError', 'Failed to create account');
} 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');
setError(errorMessage);
} finally {
setSubmitting(false);
@@ -1,4 +1,5 @@
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';
@@ -99,7 +100,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 as FileId);
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);
}
const rootIdMap = new Map<string, FileId>();
@@ -199,9 +200,9 @@ export default function ShareLinkLoader({ token }: ShareLinkLoaderProps) {
navActions.setWorkbench('viewer');
navigate('/', { replace: true });
} catch (error: any) {
} catch (error: unknown) {
if (signal.aborted) return;
const status = error?.response?.status;
const status = isAxiosError(error) ? error.response?.status : undefined;
if (status === 401 || status === 403) {
if (!isAuthenticated && !authLoading) {
alert({
@@ -1,4 +1,5 @@
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';
@@ -45,8 +46,8 @@ export default function ShareLinkPage() {
const data = await fetchShareLinkMetadata(normalizedToken);
setMetadata(data);
setStatus('ready');
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : undefined;
if (statusCode === 401) {
setStatus('login');
} else if (statusCode === 403) {
@@ -83,8 +84,8 @@ export default function ShareLinkPage() {
link.click();
link.remove();
URL.revokeObjectURL(url);
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : undefined;
if (statusCode === 401) {
setStatus('login');
} else if (statusCode === 403) {
@@ -118,8 +119,8 @@ export default function ShareLinkPage() {
}
navActions.setWorkbench('viewer');
navigate('/', { replace: true });
} catch (error: any) {
const statusCode = error?.response?.status as number | undefined;
} catch (error: unknown) {
const statusCode = isAxiosError(error) ? error.response?.status : 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 } as any
{ suppressErrorToast: true, skipAuthRedirect: true }
);
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 as FileId);
idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].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 as FileId);
const ids = stirlingFiles.map((stirlingFile: StirlingFile) => stirlingFile.fileId);
if (ids.length > 0) {
const sharedUpdates = {
remoteStorageId: shareMetadata?.fileId,
@@ -1,4 +1,5 @@
import apiClient from '@app/services/apiClient';
import type { User } from '@app/services/userManagementService';
export interface Team {
id: number;
@@ -25,6 +26,13 @@ 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
@@ -41,8 +49,8 @@ export const teamService = {
/**
* Get team details including members
*/
async getTeamDetails(teamId: number): Promise<any> {
const response = await apiClient.get(`/api/v1/proprietary/ui-data/teams/${teamId}`);
async getTeamDetails(teamId: number): Promise<TeamDetailsUIResponse> {
const response = await apiClient.get<TeamDetailsUIResponse>(`/api/v1/proprietary/ui-data/teams/${teamId}`);
return response.data;
},
@@ -54,7 +62,7 @@ export const teamService = {
formData.append('name', name);
await apiClient.post('/api/v1/team/create', formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -66,7 +74,7 @@ export const teamService = {
formData.append('newName', newName);
await apiClient.post('/api/v1/team/rename', formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -77,7 +85,7 @@ export const teamService = {
formData.append('teamId', teamId.toString());
await apiClient.post('/api/v1/team/delete', formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -89,7 +97,7 @@ export const teamService = {
formData.append('userId', userId.toString());
await apiClient.post('/api/v1/team/addUser', formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -102,6 +110,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?: any[];
teams?: unknown[];
maxPaidUsers?: number;
// License information
maxAllowedUsers: number;
@@ -39,7 +39,8 @@ export interface AdminSettingsData {
licenseMaxUsers: number;
premiumEnabled: boolean;
mailEnabled: boolean;
userSettings?: Record<string, any>;
userSettings?: Record<string, unknown>;
lockedUsers?: string[];
}
export interface CreateUserRequest {
@@ -154,7 +155,7 @@ export const userManagementService = {
}
await apiClient.post('/api/v1/user/admin/saveUser', formData, {
suppressErrorToast: true, // Component will handle error display
} as any);
});
},
/**
@@ -169,7 +170,7 @@ export const userManagementService = {
}
await apiClient.post('/api/v1/user/admin/changeRole', formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -180,7 +181,7 @@ export const userManagementService = {
formData.append('enabled', enabled.toString());
await apiClient.post(`/api/v1/user/admin/changeUserEnabled/${username}`, formData, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -189,7 +190,7 @@ export const userManagementService = {
async deleteUser(username: string): Promise<void> {
await apiClient.post(`/api/v1/user/admin/deleteUser/${username}`, null, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -210,7 +211,7 @@ export const userManagementService = {
formData,
{
suppressErrorToast: true, // Component will handle error display
} as any
}
);
return response.data;
@@ -244,7 +245,7 @@ export const userManagementService = {
formData,
{
suppressErrorToast: true,
} as any
}
);
return response.data;
@@ -264,7 +265,7 @@ export const userManagementService = {
async revokeInviteLink(inviteId: number): Promise<void> {
await apiClient.delete(`/api/v1/invite/revoke/${inviteId}`, {
suppressErrorToast: true,
} as any);
});
},
/**
@@ -299,7 +300,16 @@ export const userManagementService = {
await apiClient.post('/api/v1/user/admin/changePasswordForUser', formData, {
suppressErrorToast: true, // Component will handle error display
} as any);
});
},
/**
* 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,
});
},
/**
+16 -13
View File
@@ -176,13 +176,6 @@ UNOSERVER_PIDS=()
UNOSERVER_PORTS=()
UNOSERVER_UNO_PORTS=()
SU_EXEC_BIN=""
if command_exists su-exec; then
SU_EXEC_BIN="su-exec"
elif command_exists gosu; then
SU_EXEC_BIN="gosu"
fi
CURRENT_USER="$(id -un)"
CURRENT_UID="$(id -u)"
SWITCH_USER_WARNING_EMITTED=false
@@ -197,8 +190,8 @@ warn_switch_user_once() {
run_as_runtime_user() {
if [ "$CURRENT_USER" = "$RUNTIME_USER" ]; then
"$@"
elif [ "$CURRENT_UID" -eq 0 ] && [ -n "$SU_EXEC_BIN" ]; then
"$SU_EXEC_BIN" "$RUNTIME_USER" "$@"
elif [ "$CURRENT_UID" -eq 0 ] && command_exists setpriv; then
setpriv --reuid="$RUNTIME_USER" --regid="$(id -gn "$RUNTIME_USER")" --init-groups -- "$@"
else
warn_switch_user_once
"$@"
@@ -294,10 +287,20 @@ start_unoserver_watchdog() {
if [ "$needs_restart" = true ]; then
log "Restarting unoserver on 127.0.0.1:${port} (uno-port ${uno_port})"
# Kill the old process if it exists
# Kill the old process and its children (soffice) if it exists.
# Capture child PIDs first, then send TERM to children before parent
# so the PPID relationship is still visible. After sleep, use the
# saved PIDs for SIGKILL since the parent may have already exited
# and children would be reparented to init.
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
local child_pids
child_pids=$(pgrep -P "$pid" 2>/dev/null || true)
pkill -TERM -P "$pid" 2>/dev/null || true
kill -TERM "$pid" 2>/dev/null || true
sleep 1
sleep 3
if [ -n "$child_pids" ]; then
kill -KILL $child_pids 2>/dev/null || true
fi
kill -KILL "$pid" 2>/dev/null || true
fi
start_unoserver_instance "$port" "$uno_port"
@@ -915,8 +918,8 @@ fi
if [ "$CURRENT_USER" = "$RUNTIME_USER" ]; then
"${JAVA_CMD[@]}" &
elif [ "$CURRENT_UID" -eq 0 ] && [ -n "$SU_EXEC_BIN" ]; then
"$SU_EXEC_BIN" "$RUNTIME_USER" "${JAVA_CMD[@]}" &
elif [ "$CURRENT_UID" -eq 0 ] && command_exists setpriv; then
setpriv --reuid="$RUNTIME_USER" --regid="$(id -gn "$RUNTIME_USER")" --init-groups -- "${JAVA_CMD[@]}" &
else
warn_switch_user_once
"${JAVA_CMD[@]}" &
+14 -2
View File
@@ -88,6 +88,7 @@ capture_failure_logs() {
capture_build_failure() {
local build_name=$1
local log_file="$REPORT_DIR/${build_name//[^a-zA-Z0-9_-]/_}.failure.log"
local build_log="$REPORT_DIR/${build_name//[^a-zA-Z0-9_-]/_}.build.log"
local gradle_report_dirs=(
"$PROJECT_ROOT/app/core/build/reports/tests"
"$PROJECT_ROOT/app/common/build/reports/tests"
@@ -99,6 +100,13 @@ capture_build_failure() {
echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "---"
# Include Docker/command build output if captured
if [ -f "$build_log" ]; then
echo "--- Build output (last 100 lines) ---"
tail -100 "$build_log"
echo ""
fi
for report_dir in "${gradle_report_dirs[@]}"; do
if [ -d "$report_dir" ]; then
local txt_index="$report_dir/test/index.html"
@@ -699,12 +707,14 @@ main() {
else
DOCKER_CACHE_ARGS_ULTRA_LITE=""
fi
local ultra_lite_build_log="$REPORT_DIR/Build-Ultra-Lite-Docker.build.log"
if ! docker buildx build --build-arg VERSION_TAG=alpha \
-t docker.stirlingpdf.com/stirlingtools/stirling-pdf:ultra-lite \
-f ./docker/embedded/Dockerfile.ultra-lite \
--load \
${DOCKER_CACHE_ARGS_ULTRA_LITE} .; then
${DOCKER_CACHE_ARGS_ULTRA_LITE} . 2>&1 | tee "$ultra_lite_build_log"; then
failed_tests+=("Build-Ultra-Lite-Docker")
capture_build_failure "Build-Ultra-Lite-Docker"
gha_endgroup
exit 1
fi
@@ -783,13 +793,15 @@ main() {
else
DOCKER_CACHE_ARGS_FAT=""
fi
local fat_build_log="$REPORT_DIR/Build-Fat-Docker.build.log"
if ! docker buildx build --build-arg VERSION_TAG=alpha \
${BASE_IMAGE_ARG} \
-t docker.stirlingpdf.com/stirlingtools/stirling-pdf:fat \
-f ./docker/embedded/Dockerfile.fat \
--load \
${DOCKER_CACHE_ARGS_FAT} .; then
${DOCKER_CACHE_ARGS_FAT} . 2>&1 | tee "$fat_build_log"; then
failed_tests+=("Build-Fat-Docker")
capture_build_failure "Build-Fat-Docker"
gha_endgroup
exit 1
fi