Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5b0c9c0ec | ||
|
|
a1317f0e01 | ||
|
|
3529849bca |
+1
-1
@@ -59,7 +59,7 @@ repositories {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.1.4'
|
||||
version = '2.1.5'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
|
||||
Generated
+45
-112
@@ -51,6 +51,7 @@
|
||||
"@tauri-apps/plugin-http": "^2.5.4",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.12.2",
|
||||
"framer-motion": "^12.23.26",
|
||||
"globals": "^16.4.0",
|
||||
"i18next": "^25.5.2",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
@@ -102,7 +103,6 @@
|
||||
"postcss-preset-mantine": "^1.18.0",
|
||||
"postcss-simple-vars": "^7.0.1",
|
||||
"puppeteer": "^24.25.0",
|
||||
"rollup-plugin-visualizer": "^6.0.5",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
@@ -6743,16 +6743,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/define-lazy-prop": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
|
||||
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/define-properties": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
|
||||
@@ -8266,6 +8256,37 @@
|
||||
"url": "https://github.com/sponsors/rawify"
|
||||
}
|
||||
},
|
||||
"node_modules/framer-motion": {
|
||||
"version": "12.23.26",
|
||||
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.23.26.tgz",
|
||||
"integrity": "sha512-cPcIhgR42xBn1Uj+PzOyheMtZ73H927+uWPDVhUMqxy8UHt6Okavb6xIz9J/phFUHUj0OncR6UvMfJTXoc/LKA==",
|
||||
"dependencies": {
|
||||
"motion-dom": "^12.23.23",
|
||||
"motion-utils": "^12.23.6",
|
||||
"tslib": "^2.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emotion/is-prop-valid": "*",
|
||||
"react": "^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@emotion/is-prop-valid": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/framer-motion/node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "11.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz",
|
||||
@@ -9215,22 +9236,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-docker": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
|
||||
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"is-docker": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
@@ -9590,19 +9595,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-wsl": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
|
||||
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-docker": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
@@ -10701,6 +10693,19 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/motion-dom": {
|
||||
"version": "12.23.23",
|
||||
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.23.23.tgz",
|
||||
"integrity": "sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==",
|
||||
"dependencies": {
|
||||
"motion-utils": "^12.23.6"
|
||||
}
|
||||
},
|
||||
"node_modules/motion-utils": {
|
||||
"version": "12.23.6",
|
||||
"resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.23.6.tgz",
|
||||
"integrity": "sha512-eAWoPgr4eFEOFfg2WjIsMoqJTW6Z8MTUCgn/GZ3VRpClWBdnbjryiA3ZSNLyxCTmCQx4RmYX6jX1iWHbenUPNQ=="
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
@@ -10984,24 +10989,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/open": {
|
||||
"version": "8.4.2",
|
||||
"resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz",
|
||||
"integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"define-lazy-prop": "^2.0.0",
|
||||
"is-docker": "^2.1.1",
|
||||
"is-wsl": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
@@ -12765,60 +12752,6 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup-plugin-visualizer": {
|
||||
"version": "6.0.5",
|
||||
"resolved": "https://registry.npmjs.org/rollup-plugin-visualizer/-/rollup-plugin-visualizer-6.0.5.tgz",
|
||||
"integrity": "sha512-9+HlNgKCVbJDs8tVtjQ43US12eqaiHyyiLMdBwQ7vSZPiHMysGNo2E88TAp1si5wx8NAoYriI2A5kuKfIakmJg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"open": "^8.0.0",
|
||||
"picomatch": "^4.0.2",
|
||||
"source-map": "^0.7.4",
|
||||
"yargs": "^17.5.1"
|
||||
},
|
||||
"bin": {
|
||||
"rollup-plugin-visualizer": "dist/bin/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"rolldown": "1.x || ^1.0.0-beta",
|
||||
"rollup": "2.x || 3.x || 4.x"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"rolldown": {
|
||||
"optional": true
|
||||
},
|
||||
"rollup": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/rollup-plugin-visualizer/node_modules/picomatch": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup-plugin-visualizer/node_modules/source-map": {
|
||||
"version": "0.7.6",
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
|
||||
"integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
}
|
||||
},
|
||||
"node_modules/run-parallel": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"@tauri-apps/plugin-http": "^2.5.4",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.12.2",
|
||||
"framer-motion": "^12.23.26",
|
||||
"globals": "^16.4.0",
|
||||
"i18next": "^25.5.2",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
@@ -68,7 +69,6 @@
|
||||
"scripts": {
|
||||
"predev": "npm run generate-icons",
|
||||
"dev": "vite",
|
||||
"clean": "rm -rf dist",
|
||||
"prebuild": "npm run generate-icons",
|
||||
"lint": "eslint --max-warnings=0",
|
||||
"build": "vite build",
|
||||
@@ -150,7 +150,6 @@
|
||||
"postcss-preset-mantine": "^1.18.0",
|
||||
"postcss-simple-vars": "^7.0.1",
|
||||
"puppeteer": "^24.25.0",
|
||||
"rollup-plugin-visualizer": "^6.0.5",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
|
||||
@@ -736,6 +736,11 @@ tags = "signature,autograph"
|
||||
title = "Sign"
|
||||
desc = "Adds signature to PDF by drawing, text or image"
|
||||
|
||||
[home.annotate]
|
||||
tags = "annotate,highlight,draw"
|
||||
title = "Annotate"
|
||||
desc = "Highlight, draw, add notes and shapes in the viewer"
|
||||
|
||||
[home.flatten]
|
||||
tags = "simplify,remove,interactive"
|
||||
title = "Flatten"
|
||||
@@ -4013,23 +4018,92 @@ deleteSelected = "Delete Selected Pages"
|
||||
closePdf = "Close PDF"
|
||||
exportAll = "Export PDF"
|
||||
downloadSelected = "Download Selected Files"
|
||||
downloadAll = "Download All"
|
||||
saveAll = "Save All"
|
||||
annotations = "Annotations"
|
||||
exportSelected = "Export Selected Pages"
|
||||
saveChanges = "Save Changes"
|
||||
toggleTheme = "Toggle Theme"
|
||||
toggleBookmarks = "Toggle Bookmarks"
|
||||
language = "Language"
|
||||
toggleAnnotations = "Toggle Annotations Visibility"
|
||||
search = "Search PDF"
|
||||
panMode = "Pan Mode"
|
||||
rotateLeft = "Rotate Left"
|
||||
rotateRight = "Rotate Right"
|
||||
toggleSidebar = "Toggle Sidebar"
|
||||
exportSelected = "Export Selected Pages"
|
||||
toggleAnnotations = "Toggle Annotations Visibility"
|
||||
annotationMode = "Toggle Annotation Mode"
|
||||
toggleBookmarks = "Toggle Bookmarks"
|
||||
print = "Print PDF"
|
||||
draw = "Draw"
|
||||
save = "Save"
|
||||
saveChanges = "Save Changes"
|
||||
downloadAll = "Download All"
|
||||
saveAll = "Save All"
|
||||
|
||||
[textAlign]
|
||||
left = "Left"
|
||||
center = "Center"
|
||||
right = "Right"
|
||||
|
||||
[annotation]
|
||||
title = "Annotate"
|
||||
desc = "Use highlight, pen, text, and notes. Changes stay live—no flattening required."
|
||||
highlight = "Highlight"
|
||||
pen = "Pen"
|
||||
text = "Text box"
|
||||
note = "Note"
|
||||
rectangle = "Rectangle"
|
||||
ellipse = "Ellipse"
|
||||
select = "Select"
|
||||
exit = "Exit annotation mode"
|
||||
strokeWidth = "Width"
|
||||
opacity = "Opacity"
|
||||
strokeOpacity = "Stroke Opacity"
|
||||
fillOpacity = "Fill Opacity"
|
||||
fontSize = "Font size"
|
||||
chooseColor = "Choose colour"
|
||||
color = "Colour"
|
||||
strokeColor = "Stroke Colour"
|
||||
fillColor = "Fill Colour"
|
||||
underline = "Underline"
|
||||
strikeout = "Strikeout"
|
||||
squiggly = "Squiggly"
|
||||
inkHighlighter = "Freehand Highlighter"
|
||||
freehandHighlighter = "Freehand Highlighter"
|
||||
square = "Square"
|
||||
circle = "Circle"
|
||||
polygon = "Polygon"
|
||||
line = "Line"
|
||||
stamp = "Add Image"
|
||||
textMarkup = "Text Markup"
|
||||
drawing = "Drawing"
|
||||
shapes = "Shapes"
|
||||
notesStamps = "Notes & Stamps"
|
||||
settings = "Settings"
|
||||
borderOn = "Border: On"
|
||||
borderOff = "Border: Off"
|
||||
editInk = "Edit Pen"
|
||||
editLine = "Edit Line"
|
||||
editNote = "Edit Note"
|
||||
editText = "Edit Text Box"
|
||||
editTextMarkup = "Edit Text Markup"
|
||||
editSelected = "Edit Annotation"
|
||||
editSquare = "Edit Square"
|
||||
editCircle = "Edit Circle"
|
||||
editPolygon = "Edit Polygon"
|
||||
unsupportedType = "This annotation type is not fully supported for editing."
|
||||
textAlignment = "Text Alignment"
|
||||
noteIcon = "Note Icon"
|
||||
imagePreview = "Preview"
|
||||
contents = "Text"
|
||||
backgroundColor = "Background colour"
|
||||
clearBackground = "Remove background"
|
||||
noBackground = "No background"
|
||||
stampSettings = "Stamp Settings"
|
||||
savingCopy = "Preparing download..."
|
||||
saveFailed = "Unable to save copy"
|
||||
saveReady = "Download ready"
|
||||
selectAndMove = "Select and Edit"
|
||||
editSelectDescription = "Click an existing annotation to edit its colour, opacity, text, or size."
|
||||
editStampHint = "To change the image, delete this stamp and add a new one."
|
||||
editSwitchToSelect = "Switch to Select & Edit to edit this annotation."
|
||||
undo = "Undo"
|
||||
redo = "Redo"
|
||||
applyChanges = "Apply Changes"
|
||||
|
||||
[search]
|
||||
title = "Search PDF"
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AppConfigProvider, AppConfigProviderProps, AppConfigRetryOptions } from
|
||||
import { RightRailProvider } from "@app/contexts/RightRailContext";
|
||||
import { ViewerProvider } from "@app/contexts/ViewerContext";
|
||||
import { SignatureProvider } from "@app/contexts/SignatureContext";
|
||||
import { AnnotationProvider } from "@app/contexts/AnnotationContext";
|
||||
import { TourOrchestrationProvider } from "@app/contexts/TourOrchestrationContext";
|
||||
import { AdminTourOrchestrationProvider } from "@app/contexts/AdminTourOrchestrationContext";
|
||||
import { PageEditorProvider } from "@app/contexts/PageEditorContext";
|
||||
@@ -95,13 +96,15 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
|
||||
<ViewerProvider>
|
||||
<PageEditorProvider>
|
||||
<SignatureProvider>
|
||||
<RightRailProvider>
|
||||
<TourOrchestrationProvider>
|
||||
<AdminTourOrchestrationProvider>
|
||||
{children}
|
||||
</AdminTourOrchestrationProvider>
|
||||
</TourOrchestrationProvider>
|
||||
</RightRailProvider>
|
||||
<AnnotationProvider>
|
||||
<RightRailProvider>
|
||||
<TourOrchestrationProvider>
|
||||
<AdminTourOrchestrationProvider>
|
||||
{children}
|
||||
</AdminTourOrchestrationProvider>
|
||||
</TourOrchestrationProvider>
|
||||
</RightRailProvider>
|
||||
</AnnotationProvider>
|
||||
</SignatureProvider>
|
||||
</PageEditorProvider>
|
||||
</ViewerProvider>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { Modal, Stack, ColorPicker as MantineColorPicker, Group, Button, ColorSwatch } from '@mantine/core';
|
||||
import { Modal, Stack, ColorPicker as MantineColorPicker, Group, Button, ColorSwatch, Slider, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface ColorPickerProps {
|
||||
@@ -8,6 +8,10 @@ interface ColorPickerProps {
|
||||
selectedColor: string;
|
||||
onColorChange: (color: string) => void;
|
||||
title?: string;
|
||||
opacity?: number;
|
||||
onOpacityChange?: (opacity: number) => void;
|
||||
showOpacity?: boolean;
|
||||
opacityLabel?: string;
|
||||
}
|
||||
|
||||
export const ColorPicker: React.FC<ColorPickerProps> = ({
|
||||
@@ -15,10 +19,15 @@ export const ColorPicker: React.FC<ColorPickerProps> = ({
|
||||
onClose,
|
||||
selectedColor,
|
||||
onColorChange,
|
||||
title
|
||||
title,
|
||||
opacity,
|
||||
onOpacityChange,
|
||||
showOpacity = false,
|
||||
opacityLabel,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const resolvedTitle = title ?? t('colorPicker.title', 'Choose colour');
|
||||
const resolvedOpacityLabel = opacityLabel ?? t('annotation.opacity', 'Opacity');
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -38,6 +47,23 @@ export const ColorPicker: React.FC<ColorPickerProps> = ({
|
||||
size="lg"
|
||||
fullWidth
|
||||
/>
|
||||
{showOpacity && onOpacityChange && opacity !== undefined && (
|
||||
<Stack gap="xs">
|
||||
<Text size="sm" fw={500}>{resolvedOpacityLabel}</Text>
|
||||
<Slider
|
||||
min={10}
|
||||
max={100}
|
||||
value={opacity}
|
||||
onChange={onOpacityChange}
|
||||
marks={[
|
||||
{ value: 25, label: '25%' },
|
||||
{ value: 50, label: '50%' },
|
||||
{ value: 75, label: '75%' },
|
||||
{ value: 100, label: '100%' },
|
||||
]}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
<Group justify="flex-end">
|
||||
<Button onClick={onClose}>
|
||||
{t('common.done', 'Done')}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Stack, TextInput, Select, Combobox, useCombobox, Group, Box } from '@mantine/core';
|
||||
import { Stack, TextInput, Select, Combobox, useCombobox, Group, Box, SegmentedControl } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ColorPicker } from '@app/components/annotation/shared/ColorPicker';
|
||||
|
||||
interface TextInputWithFontProps {
|
||||
@@ -11,6 +12,8 @@ interface TextInputWithFontProps {
|
||||
onFontFamilyChange: (family: string) => void;
|
||||
textColor?: string;
|
||||
onTextColorChange?: (color: string) => void;
|
||||
textAlign?: 'left' | 'center' | 'right';
|
||||
onTextAlignChange?: (align: 'left' | 'center' | 'right') => void;
|
||||
disabled?: boolean;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
@@ -30,6 +33,8 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
||||
onFontFamilyChange,
|
||||
textColor = '#000000',
|
||||
onTextColorChange,
|
||||
textAlign = 'left',
|
||||
onTextAlignChange,
|
||||
disabled = false,
|
||||
label,
|
||||
placeholder,
|
||||
@@ -39,6 +44,7 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
||||
colorLabel,
|
||||
onAnyChange
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [fontSizeInput, setFontSizeInput] = useState(fontSize.toString());
|
||||
const fontSizeCombobox = useCombobox();
|
||||
const [isColorPickerOpen, setIsColorPickerOpen] = useState(false);
|
||||
@@ -212,6 +218,23 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Text Alignment */}
|
||||
{onTextAlignChange && (
|
||||
<SegmentedControl
|
||||
value={textAlign}
|
||||
onChange={(value: string) => {
|
||||
onTextAlignChange(value as 'left' | 'center' | 'right');
|
||||
onAnyChange?.();
|
||||
}}
|
||||
disabled={disabled}
|
||||
data={[
|
||||
{ label: t('textAlign.left', 'Left'), value: 'left' },
|
||||
{ label: t('textAlign.center', 'Center'), value: 'center' },
|
||||
{ label: t('textAlign.right', 'Right'), value: 'right' },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useMorphElement } from '@app/hooks/useMorphElement';
|
||||
|
||||
interface FileCardMorphProps {
|
||||
fileId: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for file cards that registers them for morphing animations
|
||||
*/
|
||||
export function FileCardMorph({ fileId, children, className }: FileCardMorphProps) {
|
||||
const morphRef = useMorphElement<HTMLDivElement>(
|
||||
`file-${fileId}`,
|
||||
{ fileId, type: 'file' },
|
||||
{ onlyIn: ['fileEditor'] }
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={morphRef}
|
||||
className={className}
|
||||
data-morph-id={`file-${fileId}`}
|
||||
data-morph-file-id={fileId}
|
||||
data-morph-type="file"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -399,3 +399,20 @@
|
||||
font-size: 0.875rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
Grid Animation Styles
|
||||
========================= */
|
||||
|
||||
.gridContainer {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
row-gap: 1.5rem;
|
||||
padding: 1rem;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.fileCardItem {
|
||||
/* Target for stagger animations */
|
||||
will-change: transform, opacity;
|
||||
}
|
||||
|
||||
@@ -5,16 +5,19 @@ import {
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { useFileSelection, useFileState, useFileManagement, useFileActions, useFileContext } from '@app/contexts/FileContext';
|
||||
import { useNavigationActions } from '@app/contexts/NavigationContext';
|
||||
import { useMorphElement } from '@app/hooks/useMorphElement';
|
||||
import { zipFileService } from '@app/services/zipFileService';
|
||||
import { detectFileExtension } from '@app/utils/fileUtils';
|
||||
import FileEditorThumbnail from '@app/components/fileEditor/FileEditorThumbnail';
|
||||
import AddFileCard from '@app/components/fileEditor/AddFileCard';
|
||||
import FilePickerModal from '@app/components/shared/FilePickerModal';
|
||||
import { FileCardMorph } from '@app/components/fileEditor/FileCardMorph';
|
||||
import { FileId, StirlingFile } from '@app/types/fileContext';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { downloadBlob } from '@app/utils/downloadUtils';
|
||||
import { useFileEditorRightRailButtons } from '@app/components/fileEditor/fileEditorRightRailButtons';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import styles from '@app/components/fileEditor/FileEditor.module.css';
|
||||
|
||||
|
||||
interface FileEditorProps {
|
||||
@@ -379,42 +382,37 @@ const FileEditor = ({
|
||||
</Stack>
|
||||
</Center>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
|
||||
rowGap: '1.5rem',
|
||||
padding: '1rem',
|
||||
pointerEvents: 'auto'
|
||||
}}
|
||||
>
|
||||
<div className={styles.gridContainer}>
|
||||
{/* Add File Card - only show when files exist */}
|
||||
{activeStirlingFileStubs.length > 0 && (
|
||||
<AddFileCard
|
||||
key="add-file-card"
|
||||
onFileSelect={handleFileUpload}
|
||||
/>
|
||||
<div className={styles.fileCardItem}>
|
||||
<AddFileCard
|
||||
key="add-file-card"
|
||||
onFileSelect={handleFileUpload}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeStirlingFileStubs.map((record, index) => {
|
||||
return (
|
||||
<FileEditorThumbnail
|
||||
key={record.id}
|
||||
file={record}
|
||||
index={index}
|
||||
totalFiles={activeStirlingFileStubs.length}
|
||||
selectedFiles={localSelectedIds}
|
||||
selectionMode={selectionMode}
|
||||
onToggleFile={toggleFile}
|
||||
onCloseFile={handleCloseFile}
|
||||
onViewFile={handleViewFile}
|
||||
_onSetStatus={showStatus}
|
||||
onReorderFiles={handleReorderFiles}
|
||||
onDownloadFile={handleDownloadFile}
|
||||
onUnzipFile={handleUnzipFile}
|
||||
toolMode={toolMode}
|
||||
isSupported={isFileSupported(record.name)}
|
||||
/>
|
||||
<FileCardMorph key={record.id} fileId={record.id} className={styles.fileCardItem}>
|
||||
<FileEditorThumbnail
|
||||
file={record}
|
||||
index={index}
|
||||
totalFiles={activeStirlingFileStubs.length}
|
||||
selectedFiles={localSelectedIds}
|
||||
selectionMode={selectionMode}
|
||||
onToggleFile={toggleFile}
|
||||
onCloseFile={handleCloseFile}
|
||||
onViewFile={handleViewFile}
|
||||
_onSetStatus={showStatus}
|
||||
onReorderFiles={handleReorderFiles}
|
||||
onDownloadFile={handleDownloadFile}
|
||||
onUnzipFile={handleUnzipFile}
|
||||
toolMode={toolMode}
|
||||
isSupported={isFileSupported(record.name)}
|
||||
/>
|
||||
</FileCardMorph>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { Box } from '@mantine/core';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useRainbowThemeContext } from '@app/components/shared/RainbowThemeProvider';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import { useFileHandler } from '@app/hooks/useFileHandler';
|
||||
import { useFileState } from '@app/contexts/FileContext';
|
||||
import { useNavigationState, useNavigationActions } from '@app/contexts/NavigationContext';
|
||||
import { isBaseWorkbench } from '@app/types/workbench';
|
||||
import { isBaseWorkbench, type BaseWorkbenchType } from '@app/types/workbench';
|
||||
import { useViewer } from '@app/contexts/ViewerContext';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { useWorkbenchMorphTransition } from '@app/hooks/useWorkbenchMorphTransition';
|
||||
import { useWorkbenchTransition } from '@app/contexts/WorkbenchTransitionContext';
|
||||
import styles from '@app/components/layout/Workbench.module.css';
|
||||
|
||||
import TopControls from '@app/components/shared/TopControls';
|
||||
@@ -28,6 +32,14 @@ export default function Workbench() {
|
||||
const { workbench: currentView } = useNavigationState();
|
||||
const { actions: navActions } = useNavigationActions();
|
||||
const setCurrentView = navActions.setWorkbench;
|
||||
|
||||
// Track the displayed workbench (for transitions)
|
||||
const [displayedView, setDisplayedView] = useState(currentView);
|
||||
const [isTransitioning, setIsTransitioning] = useState(false);
|
||||
|
||||
// Workbench morphing transition hook
|
||||
const { transition } = useWorkbenchMorphTransition();
|
||||
const { transitionState } = useWorkbenchTransition();
|
||||
const activeFiles = selectors.getFiles();
|
||||
const {
|
||||
previewFile,
|
||||
@@ -52,6 +64,33 @@ export default function Workbench() {
|
||||
// Get active file index from ViewerContext
|
||||
const { activeFileIndex, setActiveFileIndex } = useViewer();
|
||||
|
||||
// Trigger morphing transition when workbench changes
|
||||
useEffect(() => {
|
||||
if (currentView === displayedView || isTransitioning) return;
|
||||
|
||||
const performTransition = async () => {
|
||||
if (isBaseWorkbench(currentView) && isBaseWorkbench(displayedView)) {
|
||||
// Both are base workbenches - perform morphing transition
|
||||
setIsTransitioning(true);
|
||||
|
||||
await transition(displayedView as BaseWorkbenchType, currentView as BaseWorkbenchType, () => {
|
||||
// Swap content after source snapshots are captured
|
||||
setDisplayedView(currentView);
|
||||
});
|
||||
|
||||
// Transition completes automatically after animation
|
||||
setTimeout(() => {
|
||||
setIsTransitioning(false);
|
||||
}, 550);
|
||||
} else {
|
||||
// One is custom view - just swap without morph
|
||||
setDisplayedView(currentView);
|
||||
}
|
||||
};
|
||||
|
||||
performTransition();
|
||||
}, [currentView, displayedView, isTransitioning, transition]);
|
||||
|
||||
const handlePreviewClose = () => {
|
||||
setPreviewFile(null);
|
||||
const previousMode = sessionStorage.getItem('previousMode');
|
||||
@@ -71,12 +110,15 @@ export default function Workbench() {
|
||||
};
|
||||
|
||||
const renderMainContent = () => {
|
||||
// Use displayedView for rendering (sync with transition)
|
||||
const viewToRender = displayedView;
|
||||
|
||||
// Check for custom workbench views first
|
||||
if (!isBaseWorkbench(currentView)) {
|
||||
const customView = customWorkbenchViews.find((view) => view.workbenchId === currentView && view.data != null);
|
||||
if (!isBaseWorkbench(viewToRender)) {
|
||||
const customView = customWorkbenchViews.find((view) => view.workbenchId === viewToRender && view.data != null);
|
||||
if (customView) {
|
||||
// PDF text editor handles its own empty state (shows dropzone when no document)
|
||||
const handlesOwnEmptyState = currentView === 'custom:pdfTextEditor';
|
||||
const handlesOwnEmptyState = viewToRender === 'custom:pdfTextEditor';
|
||||
if (handlesOwnEmptyState || activeFiles.length > 0) {
|
||||
const CustomComponent = customView.component;
|
||||
return <CustomComponent data={customView.data} />;
|
||||
@@ -92,7 +134,7 @@ export default function Workbench() {
|
||||
);
|
||||
}
|
||||
|
||||
switch (currentView) {
|
||||
switch (viewToRender) {
|
||||
case "fileEditor":
|
||||
|
||||
return (
|
||||
@@ -189,15 +231,20 @@ export default function Workbench() {
|
||||
{/* Dismiss All Errors Button */}
|
||||
<DismissAllErrorsButton />
|
||||
|
||||
{/* Main content area */}
|
||||
<Box
|
||||
className={`flex-1 min-h-0 relative z-10 ${styles.workbenchScrollable}`}
|
||||
style={{
|
||||
transition: 'opacity 0.15s ease-in-out',
|
||||
}}
|
||||
>
|
||||
{renderMainContent()}
|
||||
</Box>
|
||||
{/* Main content area with workbench transitions */}
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={displayedView}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: transitionState.isTransitioning ? 0 : 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
className={`flex-1 min-h-0 relative z-10 ${styles.workbenchScrollable}`}
|
||||
style={{ display: 'flex', flexDirection: 'column' }}
|
||||
>
|
||||
{renderMainContent()}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
<Footer
|
||||
analyticsEnabled={config?.enableAnalytics === true}
|
||||
|
||||
@@ -469,6 +469,7 @@ const PageEditor = ({
|
||||
index={index}
|
||||
totalPages={displayDocument.pages.length}
|
||||
originalFile={(page as any).originalFileId ? selectors.getFile((page as any).originalFileId) : undefined}
|
||||
fileId={page.originalFileId || displayDocument.id}
|
||||
fileColorIndex={fileColorIndex}
|
||||
selectedPageIds={selectedPageIds}
|
||||
selectionMode={selectionMode}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useCallback, useState, useEffect, useRef, useMemo } from 'react';
|
||||
import { Text, Checkbox } from '@mantine/core';
|
||||
import { useIsMobile } from '@app/hooks/useIsMobile';
|
||||
import { useMorphElement } from '@app/hooks/useMorphElement';
|
||||
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
|
||||
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
|
||||
import RotateLeftIcon from '@mui/icons-material/RotateLeft';
|
||||
@@ -23,6 +24,7 @@ interface PageThumbnailProps {
|
||||
index: number;
|
||||
totalPages: number;
|
||||
originalFile?: File;
|
||||
fileId: string;
|
||||
fileColorIndex: number;
|
||||
selectedPageIds: string[];
|
||||
selectionMode: boolean;
|
||||
@@ -56,6 +58,7 @@ const PageThumbnail: React.FC<PageThumbnailProps> = ({
|
||||
index: _index,
|
||||
totalPages,
|
||||
originalFile,
|
||||
fileId,
|
||||
fileColorIndex,
|
||||
selectedPageIds,
|
||||
selectionMode,
|
||||
@@ -82,6 +85,24 @@ const PageThumbnail: React.FC<PageThumbnailProps> = ({
|
||||
}: PageThumbnailProps) => {
|
||||
const pageIndex = page.pageNumber - 1;
|
||||
|
||||
// Register for morphing - ALL pages register for split/merge animations
|
||||
const morphId = page.originalFileId
|
||||
? `page-${page.originalFileId}-${page.pageNumber}`
|
||||
: `page-${page.id}`;
|
||||
|
||||
const morphRef = useMorphElement<HTMLDivElement>(
|
||||
morphId,
|
||||
{
|
||||
pageId: page.id,
|
||||
fileId: fileId || page.originalFileId, // Used for grouping in morph pairs
|
||||
pageNumber: page.pageNumber,
|
||||
type: 'page',
|
||||
},
|
||||
{
|
||||
onlyIn: ['pageEditor'],
|
||||
}
|
||||
);
|
||||
|
||||
const [isMouseDown, setIsMouseDown] = useState(false);
|
||||
const [mouseStartPos, setMouseStartPos] = useState<{x: number, y: number} | null>(null);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
@@ -162,11 +183,16 @@ const PageThumbnail: React.FC<PageThumbnailProps> = ({
|
||||
pageRefs.current.delete(page.id);
|
||||
}
|
||||
|
||||
// Assign to morph ref for animation system
|
||||
if (morphRef) {
|
||||
(morphRef as React.MutableRefObject<HTMLDivElement | null>).current = element;
|
||||
}
|
||||
|
||||
// Call dnd-kit's ref if provided
|
||||
if (dragHandleProps?.ref) {
|
||||
dragHandleProps.ref(element);
|
||||
}
|
||||
}, [page.id, pageRefs, dragHandleProps]);
|
||||
}, [page.id, pageRefs, dragHandleProps, morphRef]);
|
||||
|
||||
|
||||
// DOM command handlers
|
||||
@@ -352,6 +378,10 @@ const PageThumbnail: React.FC<PageThumbnailProps> = ({
|
||||
{...restDragProps}
|
||||
data-page-id={page.id}
|
||||
data-page-number={page.pageNumber}
|
||||
data-morph-id={morphId}
|
||||
data-morph-file-id={fileId || page.originalFileId}
|
||||
data-morph-page-number={page.pageNumber}
|
||||
data-morph-type="page"
|
||||
className={`
|
||||
${styles.pageContainer}
|
||||
!rounded-lg
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { FileId } from '@app/types/file';
|
||||
import { PDFDocument, PDFPage, PageBreakSettings } from '@app/types/pageEditor';
|
||||
import { pdfWorkerManager } from '@app/services/pdfWorkerManager';
|
||||
import { thumbnailGenerationService } from '@app/services/thumbnailGenerationService';
|
||||
|
||||
// V1-style DOM-first command system (replaces the old React state commands)
|
||||
export abstract class DOMCommand {
|
||||
@@ -729,6 +727,8 @@ export class InsertFilesCommand extends DOMCommand {
|
||||
|
||||
private async generateThumbnailsForInsertedPages(updatedDocument: PDFDocument): Promise<void> {
|
||||
try {
|
||||
const { thumbnailGenerationService } = await import('@app/services/thumbnailGenerationService');
|
||||
|
||||
// Group pages by file ID to generate thumbnails efficiently
|
||||
const pagesByFileId = new Map<FileId, PDFPage[]>();
|
||||
|
||||
@@ -809,6 +809,7 @@ export class InsertFilesCommand extends DOMCommand {
|
||||
const clonedArrayBuffer = arrayBuffer.slice(0);
|
||||
|
||||
// Use PDF.js via the worker manager to extract pages
|
||||
const { pdfWorkerManager } = await import('@app/services/pdfWorkerManager');
|
||||
const pdf = await pdfWorkerManager.createDocument(clonedArrayBuffer);
|
||||
|
||||
const pageCount = pdf.numPages;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Dispatch, SetStateAction, useCallback } from "react";
|
||||
import JSZip from "jszip";
|
||||
|
||||
import type {
|
||||
useFileActions,
|
||||
@@ -195,7 +194,8 @@ export const usePageEditorExport = ({
|
||||
);
|
||||
|
||||
if (files.length > 1) {
|
||||
const zip = new JSZip();
|
||||
const JSZip = await import("jszip");
|
||||
const zip = new JSZip.default();
|
||||
|
||||
files.forEach((file) => {
|
||||
zip.file(file.name, file);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useMemo, useState, useEffect, useCallback, Suspense } from 'react';
|
||||
import React, { useMemo, useState, useEffect, useCallback } from 'react';
|
||||
import { Modal, Text, ActionIcon, Tooltip, Group } from '@mantine/core';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
@@ -223,9 +223,7 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({ opened, onClose })
|
||||
</ActionIcon>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
|
||||
{activeComponent}
|
||||
</Suspense>
|
||||
{activeComponent}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import { useWorkbenchTransition } from '@app/contexts/WorkbenchTransitionContext';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
|
||||
/**
|
||||
* MorphOverlay renders animated clones of elements during workbench transitions
|
||||
*
|
||||
* Uses Framer Motion to smoothly morph elements from source to target positions,
|
||||
* creating the illusion that pages/files are transforming between view modes.
|
||||
*/
|
||||
export function MorphOverlay() {
|
||||
const { transitionState, getMorphPairs, completeTransition } = useWorkbenchTransition();
|
||||
|
||||
const morphPairs = getMorphPairs();
|
||||
|
||||
// Debug logging
|
||||
useEffect(() => {
|
||||
if (transitionState.isTransitioning) {
|
||||
console.log('[MorphOverlay] Transition state:', {
|
||||
from: transitionState.fromWorkbench,
|
||||
to: transitionState.toWorkbench,
|
||||
sources: transitionState.sourceSnapshots.length,
|
||||
targets: transitionState.targetSnapshots.length,
|
||||
pairs: morphPairs.length,
|
||||
});
|
||||
|
||||
if (morphPairs.length > 0) {
|
||||
const pairsBySource = new Map<string, number>();
|
||||
morphPairs.forEach(({ source }) => {
|
||||
pairsBySource.set(source.id, (pairsBySource.get(source.id) || 0) + 1);
|
||||
});
|
||||
const hasSplit = Array.from(pairsBySource.values()).some(count => count > 1);
|
||||
const type = hasSplit ? 'SPLIT' : 'MERGE';
|
||||
|
||||
console.log(`[MorphOverlay] ${type} animation with ${morphPairs.length} pairs`);
|
||||
|
||||
// Log first pair details
|
||||
const first = morphPairs[0];
|
||||
console.log('[MorphOverlay] First pair:', {
|
||||
source: first.source.id,
|
||||
target: first.target.id,
|
||||
sourcePos: { x: Math.round(first.source.rect.left), y: Math.round(first.source.rect.top) },
|
||||
targetPos: { x: Math.round(first.target.rect.left), y: Math.round(first.target.rect.top) },
|
||||
});
|
||||
} else {
|
||||
console.log('[MorphOverlay] No morph pairs created!');
|
||||
}
|
||||
}
|
||||
}, [transitionState, morphPairs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!transitionState.isTransitioning) return;
|
||||
|
||||
// Auto-complete transition after animation duration.
|
||||
// Give extra time when pairs are not ready so targets can register.
|
||||
const timeout = setTimeout(() => {
|
||||
completeTransition();
|
||||
}, morphPairs.length > 0 ? 1400 : 3500); // allow time for targets to register
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [transitionState.isTransitioning, morphPairs.length, completeTransition]);
|
||||
|
||||
const isSplit = morphPairs.some(({ source }) => {
|
||||
const sourceFile = source.metadata?.fileId;
|
||||
const counts = morphPairs.filter(p => p.source.metadata?.fileId === sourceFile);
|
||||
return counts.length > 1;
|
||||
});
|
||||
|
||||
// For split animations, we want all outgoing clones to originate near the first page spot
|
||||
const firstTargetRectByFile = useMemo(() => {
|
||||
const map = new Map<string, DOMRect>();
|
||||
morphPairs.forEach(({ source, target }) => {
|
||||
const fileId = source.metadata?.fileId || target.metadata?.fileId;
|
||||
if (fileId && !map.has(fileId)) {
|
||||
map.set(fileId, target.rect);
|
||||
}
|
||||
});
|
||||
return map;
|
||||
}, [morphPairs]);
|
||||
|
||||
const preferSplitTargetOrigin = transitionState.toWorkbench === 'pageEditor';
|
||||
|
||||
if (!transitionState.isTransitioning || morphPairs.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
zIndex: 10000,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{morphPairs.map(({ source, target }, index) => {
|
||||
const sourceRect = source.rect;
|
||||
const targetRect = target.rect;
|
||||
const fileId = source.metadata?.fileId || target.metadata?.fileId;
|
||||
|
||||
// If splitting (file -> pages), start all clones from the first target rect for that file
|
||||
const initialRect =
|
||||
source.metadata?.type === 'file' &&
|
||||
isSplit &&
|
||||
preferSplitTargetOrigin &&
|
||||
fileId &&
|
||||
firstTargetRectByFile.get(fileId)
|
||||
? firstTargetRectByFile.get(fileId)!
|
||||
: sourceRect;
|
||||
|
||||
// Use combination of source and target IDs for unique keys (supports split/merge)
|
||||
const key = `${source.id}-to-${target.id}`;
|
||||
|
||||
// Use page thumbnail when flying pages -> file, and target when file -> pages
|
||||
const thumbnail =
|
||||
source.metadata?.type === 'page'
|
||||
? source.thumbnail || target.thumbnail
|
||||
: target.thumbnail || source.thumbnail;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={key}
|
||||
initial={{
|
||||
position: 'absolute',
|
||||
left: initialRect.left,
|
||||
top: initialRect.top,
|
||||
width: initialRect.width,
|
||||
height: initialRect.height,
|
||||
borderRadius: '4px',
|
||||
overflow: 'hidden',
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||
opacity: 0.9,
|
||||
scale: 0.9,
|
||||
}}
|
||||
animate={{
|
||||
left: targetRect.left,
|
||||
top: targetRect.top,
|
||||
width: targetRect.width,
|
||||
height: targetRect.height,
|
||||
opacity: 1,
|
||||
scale: 1,
|
||||
}}
|
||||
transition={{
|
||||
type: 'spring',
|
||||
stiffness: 220,
|
||||
damping: 26,
|
||||
mass: 1.05,
|
||||
bounce: 0.3,
|
||||
restDelta: 0.1,
|
||||
restSpeed: 0.1,
|
||||
delay: isSplit ? index * 0.05 : 0,
|
||||
}}
|
||||
style={{ willChange: 'transform, width, height, opacity' }}
|
||||
>
|
||||
{/* Render thumbnail if available */}
|
||||
{thumbnail && (
|
||||
<motion.img
|
||||
src={thumbnail}
|
||||
alt=""
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'contain',
|
||||
backgroundColor: 'white',
|
||||
}}
|
||||
initial={{ opacity: 1 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Fallback: render a placeholder */}
|
||||
{!source.thumbnail && (
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
backgroundColor: 'var(--file-card-bg, #f5f5f5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: '24px', opacity: 0.5 }}>📄</span>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useRef, forwardRef, useEffect, lazy, Suspense } from "react";
|
||||
import React, { useState, useRef, forwardRef, useEffect } from "react";
|
||||
import { Stack, Divider, Menu, Indicator } from "@mantine/core";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
@@ -14,10 +14,8 @@ import '@app/components/shared/quickAccessBar/QuickAccessBar.css';
|
||||
import { Tooltip } from '@app/components/shared/Tooltip';
|
||||
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';
|
||||
|
||||
// Lazy-load AppConfigModal
|
||||
const AppConfigModal = lazy(() => import('@app/components/shared/AppConfigModal'));
|
||||
import { useLicenseAlert } from "@app/hooks/useLicenseAlert";
|
||||
import { requestStartTour } from '@app/constants/events';
|
||||
import QuickAccessButton from '@app/components/shared/quickAccessBar/QuickAccessButton';
|
||||
@@ -367,12 +365,10 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Suspense fallback={null}>
|
||||
<AppConfigModal
|
||||
opened={configModalOpen}
|
||||
onClose={() => setConfigModalOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
<AppConfigModal
|
||||
opened={configModalOpen}
|
||||
onClose={() => setConfigModalOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ export default function LoginRequiredBanner({ show }: LoginRequiredBannerProps)
|
||||
|
||||
return (
|
||||
<Alert
|
||||
icon={<LocalIcon icon="lock" width={20} height={20} />}
|
||||
icon={<LocalIcon icon="lock-rounded" width={20} height={20} />}
|
||||
title={t('admin.settings.loginDisabled.title', 'Login Mode Required')}
|
||||
color="blue"
|
||||
variant="light"
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import React, { lazy } from 'react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { NavKey } from '@app/components/shared/config/types';
|
||||
|
||||
// Lazy load config sections
|
||||
const HotkeysSection = lazy(() => import('@app/components/shared/config/configSections/HotkeysSection'));
|
||||
const GeneralSection = lazy(() => import('@app/components/shared/config/configSections/GeneralSection'));
|
||||
import HotkeysSection from '@app/components/shared/config/configSections/HotkeysSection';
|
||||
import GeneralSection from '@app/components/shared/config/configSections/GeneralSection';
|
||||
|
||||
export interface ConfigNavItem {
|
||||
key: NavKey;
|
||||
|
||||
@@ -193,7 +193,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false }) =>
|
||||
size="sm"
|
||||
color={updateSummary.max_priority === 'urgent' ? 'red' : 'blue'}
|
||||
onClick={() => setUpdateModalOpened(true)}
|
||||
leftSection={<LocalIcon icon="system-update-alt-rounded" width="1rem" height="1rem" />}
|
||||
leftSection={<LocalIcon icon="system-update-rounded" width="1rem" height="1rem" />}
|
||||
>
|
||||
{t('settings.general.updates.viewDetails', 'View Details')}
|
||||
</Button>
|
||||
|
||||
@@ -25,6 +25,12 @@ export default function ViewerAnnotationControls({ currentView, disabled = false
|
||||
const { selectedTool } = useNavigationState();
|
||||
const isSignMode = selectedTool === 'sign';
|
||||
|
||||
// Check if we're in any annotation tool that should disable the toggle
|
||||
const isInAnnotationTool = selectedTool === 'annotate' || selectedTool === 'sign' || selectedTool === 'addImage' || selectedTool === 'addText';
|
||||
|
||||
// Check if we're on annotate tool to highlight the button
|
||||
const isAnnotateActive = selectedTool === 'annotate';
|
||||
|
||||
// Don't show any annotation controls in sign mode
|
||||
if (isSignMode) {
|
||||
return null;
|
||||
@@ -35,13 +41,14 @@ export default function ViewerAnnotationControls({ currentView, disabled = false
|
||||
{/* Annotation Visibility Toggle */}
|
||||
<Tooltip content={t('rightRail.toggleAnnotations', 'Toggle Annotations Visibility')} position={tooltipPosition} offset={tooltipOffset} arrow portalTarget={document.body}>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
variant={isAnnotateActive ? "filled" : "subtle"}
|
||||
color="blue"
|
||||
radius="md"
|
||||
className="right-rail-icon"
|
||||
onClick={() => {
|
||||
viewerContext?.toggleAnnotationsVisibility();
|
||||
}}
|
||||
disabled={disabled || currentView !== 'viewer'}
|
||||
disabled={disabled || currentView !== 'viewer' || isInAnnotationTool}
|
||||
>
|
||||
<LocalIcon
|
||||
icon={viewerContext?.isAnnotationsVisible ? "visibility" : "visibility-off-rounded"}
|
||||
|
||||
@@ -63,7 +63,7 @@ export default function ToastRenderer() {
|
||||
{/* Icon */}
|
||||
<div className="toast-icon">
|
||||
{t.icon ?? (
|
||||
<LocalIcon icon={getDefaultIconName(t)} width={20} height={20} />
|
||||
<LocalIcon icon={`material-symbols:${getDefaultIconName(t)}`} width={20} height={20} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -86,7 +86,7 @@ export default function ToastRenderer() {
|
||||
}}
|
||||
className={`toast-button toast-expand-button ${t.isExpanded ? 'toast-expand-button--expanded' : ''}`}
|
||||
>
|
||||
<LocalIcon icon="expand-more-rounded" />
|
||||
<LocalIcon icon="material-symbols:expand-more-rounded" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
@@ -94,7 +94,7 @@ export default function ToastRenderer() {
|
||||
onClick={() => dismiss(t.id)}
|
||||
className="toast-button"
|
||||
>
|
||||
<LocalIcon icon="close-rounded" width={20} height={20} />
|
||||
<LocalIcon icon="material-symbols:close-rounded" width={20} height={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -42,7 +42,7 @@ const AddAttachmentsSettings = ({ parameters, onParameterChange, disabled = fals
|
||||
component="label"
|
||||
htmlFor="attachments-input"
|
||||
disabled={disabled}
|
||||
leftSection={<LocalIcon icon="add-rounded" width="14" height="14" />}
|
||||
leftSection={<LocalIcon icon="plus" width="14" height="14" />}
|
||||
>
|
||||
{parameters.attachments?.length > 0
|
||||
? t("AddAttachmentsRequest.addMoreFiles", "Add more files...")
|
||||
|
||||
@@ -234,7 +234,7 @@ export const SavedSignaturesSection = ({
|
||||
{groupedSignatures.personal.length > 0 && activePersonalSignature && (
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs">
|
||||
<LocalIcon icon="person-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:person-rounded" width={18} height={18} />
|
||||
<Text fw={600} size="sm">
|
||||
{translate('saved.personalHeading', 'Personal Signatures')}
|
||||
</Text>
|
||||
@@ -257,7 +257,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActivePersonalIndex(prev => Math.max(0, prev - 1))}
|
||||
disabled={disabled || activePersonalIndex === 0}
|
||||
>
|
||||
<LocalIcon icon="chevron-left-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-left-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
@@ -265,7 +265,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActivePersonalIndex(prev => Math.min(groupedSignatures.personal.length - 1, prev + 1))}
|
||||
disabled={disabled || activePersonalIndex >= groupedSignatures.personal.length - 1}
|
||||
>
|
||||
<LocalIcon icon="chevron-right-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-right-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Group>
|
||||
@@ -284,7 +284,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onUseSignature(activePersonalSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="check-circle-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:check-circle-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
<Tooltip label={translate('saved.delete', 'Remove')}>
|
||||
<ActionIcon
|
||||
@@ -294,7 +294,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onDeleteSignature(activePersonalSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="delete-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:delete-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
@@ -317,7 +317,7 @@ export const SavedSignaturesSection = ({
|
||||
{groupedSignatures.shared.length > 0 && activeSharedSignature && (
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs">
|
||||
<LocalIcon icon="groups-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:groups-rounded" width={18} height={18} />
|
||||
<Text fw={600} size="sm">
|
||||
{translate('saved.sharedHeading', 'Shared Signatures')}
|
||||
</Text>
|
||||
@@ -340,7 +340,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActiveSharedIndex(prev => Math.max(0, prev - 1))}
|
||||
disabled={disabled || activeSharedIndex === 0}
|
||||
>
|
||||
<LocalIcon icon="chevron-left-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-left-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
@@ -348,7 +348,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActiveSharedIndex(prev => Math.min(groupedSignatures.shared.length - 1, prev + 1))}
|
||||
disabled={disabled || activeSharedIndex >= groupedSignatures.shared.length - 1}
|
||||
>
|
||||
<LocalIcon icon="chevron-right-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-right-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Group>
|
||||
@@ -367,7 +367,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onUseSignature(activeSharedSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="check-circle-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:check-circle-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
{isAdmin && (
|
||||
<Tooltip label={translate('saved.delete', 'Remove')}>
|
||||
@@ -378,7 +378,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onDeleteSignature(activeSharedSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="delete-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:delete-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
@@ -424,7 +424,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActiveLocalStorageIndex(prev => Math.max(0, prev - 1))}
|
||||
disabled={disabled || activeLocalStorageIndex === 0}
|
||||
>
|
||||
<LocalIcon icon="chevron-left-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-left-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
@@ -432,7 +432,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => setActiveLocalStorageIndex(prev => Math.min(groupedSignatures.localStorage.length - 1, prev + 1))}
|
||||
disabled={disabled || activeLocalStorageIndex >= groupedSignatures.localStorage.length - 1}
|
||||
>
|
||||
<LocalIcon icon="chevron-right-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:chevron-right-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Group>
|
||||
@@ -451,7 +451,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onUseSignature(activeLocalStorageSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="check-circle-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:check-circle-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
<Tooltip label={translate('saved.delete', 'Remove')}>
|
||||
<ActionIcon
|
||||
@@ -461,7 +461,7 @@ export const SavedSignaturesSection = ({
|
||||
onClick={() => onDeleteSignature(activeLocalStorageSignature)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<LocalIcon icon="delete-outline-rounded" width={18} height={18} />
|
||||
<LocalIcon icon="material-symbols:delete-outline-rounded" width={18} height={18} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
|
||||
@@ -370,7 +370,7 @@ const SignSettings = ({
|
||||
isReady,
|
||||
onClick,
|
||||
'personal',
|
||||
'person-rounded',
|
||||
'material-symbols:person-rounded',
|
||||
translate('saved.savePersonal', 'Save Personal')
|
||||
);
|
||||
|
||||
@@ -379,7 +379,7 @@ const SignSettings = ({
|
||||
isReady,
|
||||
onClick,
|
||||
'shared',
|
||||
'groups-rounded',
|
||||
'material-symbols:groups-rounded',
|
||||
translate('saved.saveShared', 'Save Shared')
|
||||
);
|
||||
|
||||
@@ -964,7 +964,7 @@ const SignSettings = ({
|
||||
gap: '0.4rem',
|
||||
}}
|
||||
>
|
||||
<LocalIcon icon="pause-rounded" width={20} height={20} />
|
||||
<LocalIcon icon="material-symbols:pause-rounded" width={20} height={20} />
|
||||
<Text component="span" size="sm" fw={500}>
|
||||
{translate('mode.pause', 'Pause placement')}
|
||||
</Text>
|
||||
@@ -987,7 +987,7 @@ const SignSettings = ({
|
||||
gap: '0.4rem',
|
||||
}}
|
||||
>
|
||||
<LocalIcon icon="play-arrow-rounded" width={20} height={20} />
|
||||
<LocalIcon icon="material-symbols:play-arrow-rounded" width={20} height={20} />
|
||||
<Text component="span" size="sm" fw={500}>
|
||||
{translate('mode.resume', 'Resume placement')}
|
||||
</Text>
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
import { useImperativeHandle, forwardRef, useCallback } from 'react';
|
||||
import { useAnnotationCapability } from '@embedpdf/plugin-annotation/react';
|
||||
import { PdfAnnotationSubtype, PdfAnnotationIcon } from '@embedpdf/models';
|
||||
import type {
|
||||
AnnotationToolId,
|
||||
AnnotationToolOptions,
|
||||
AnnotationAPI,
|
||||
AnnotationEvent,
|
||||
AnnotationPatch,
|
||||
} from '@app/components/viewer/viewerTypes';
|
||||
|
||||
type NoteIcon = NonNullable<AnnotationToolOptions['icon']>;
|
||||
type AnnotationDefaults =
|
||||
| {
|
||||
type:
|
||||
| PdfAnnotationSubtype.HIGHLIGHT
|
||||
| PdfAnnotationSubtype.UNDERLINE
|
||||
| PdfAnnotationSubtype.STRIKEOUT
|
||||
| PdfAnnotationSubtype.SQUIGGLY;
|
||||
color: string;
|
||||
opacity: number;
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: PdfAnnotationSubtype.INK;
|
||||
color: string;
|
||||
opacity?: number;
|
||||
borderWidth?: number;
|
||||
strokeWidth?: number;
|
||||
lineWidth?: number;
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: PdfAnnotationSubtype.FREETEXT;
|
||||
fontColor?: string;
|
||||
fontSize?: number;
|
||||
fontFamily?: string;
|
||||
textAlign?: number;
|
||||
opacity?: number;
|
||||
backgroundColor?: string;
|
||||
borderWidth?: number;
|
||||
contents?: string;
|
||||
icon?: PdfAnnotationIcon;
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: PdfAnnotationSubtype.SQUARE | PdfAnnotationSubtype.CIRCLE | PdfAnnotationSubtype.POLYGON;
|
||||
color: string;
|
||||
strokeColor: string;
|
||||
opacity: number;
|
||||
fillOpacity: number;
|
||||
strokeOpacity: number;
|
||||
borderWidth: number;
|
||||
strokeWidth: number;
|
||||
lineWidth: number;
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: PdfAnnotationSubtype.LINE | PdfAnnotationSubtype.POLYLINE;
|
||||
color: string;
|
||||
strokeColor?: string;
|
||||
opacity: number;
|
||||
borderWidth?: number;
|
||||
strokeWidth?: number;
|
||||
lineWidth?: number;
|
||||
startStyle?: string;
|
||||
endStyle?: string;
|
||||
lineEndingStyles?: { start: string; end: string };
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: PdfAnnotationSubtype.STAMP;
|
||||
imageSrc?: string;
|
||||
imageSize?: { width: number; height: number };
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
| null;
|
||||
|
||||
type AnnotationApiSurface = {
|
||||
setActiveTool: (toolId: AnnotationToolId | null) => void;
|
||||
getActiveTool?: () => { id: AnnotationToolId } | null;
|
||||
setToolDefaults?: (toolId: AnnotationToolId, defaults: AnnotationDefaults) => void;
|
||||
getSelectedAnnotation?: () => unknown | null;
|
||||
deselectAnnotation?: () => void;
|
||||
updateAnnotation?: (pageIndex: number, annotationId: string, patch: AnnotationPatch) => void;
|
||||
onAnnotationEvent?: (listener: (event: AnnotationEvent) => void) => void | (() => void);
|
||||
};
|
||||
|
||||
type ToolDefaultsBuilder = (options?: AnnotationToolOptions) => AnnotationDefaults;
|
||||
|
||||
const NOTE_ICON_MAP: Record<NoteIcon, PdfAnnotationIcon> = {
|
||||
Comment: PdfAnnotationIcon.Comment,
|
||||
Key: PdfAnnotationIcon.Key,
|
||||
Note: PdfAnnotationIcon.Note,
|
||||
Help: PdfAnnotationIcon.Help,
|
||||
NewParagraph: PdfAnnotationIcon.NewParagraph,
|
||||
Paragraph: PdfAnnotationIcon.Paragraph,
|
||||
Insert: PdfAnnotationIcon.Insert,
|
||||
};
|
||||
|
||||
const DEFAULTS = {
|
||||
highlight: '#ffd54f',
|
||||
underline: '#ffb300',
|
||||
strikeout: '#e53935',
|
||||
squiggly: '#00acc1',
|
||||
ink: '#1f2933',
|
||||
inkHighlighter: '#ffd54f',
|
||||
text: '#111111',
|
||||
note: '#ffd54f', // match highlight color
|
||||
shapeFill: '#0000ff',
|
||||
shapeStroke: '#cf5b5b',
|
||||
shapeOpacity: 0.5,
|
||||
};
|
||||
|
||||
const withCustomData = (options?: AnnotationToolOptions) =>
|
||||
options?.customData ? { customData: options.customData } : {};
|
||||
|
||||
const getIconEnum = (icon?: NoteIcon) => NOTE_ICON_MAP[icon ?? 'Comment'] ?? PdfAnnotationIcon.Comment;
|
||||
|
||||
const buildStampDefaults: ToolDefaultsBuilder = (options) => ({
|
||||
type: PdfAnnotationSubtype.STAMP,
|
||||
...(options?.imageSrc ? { imageSrc: options.imageSrc } : {}),
|
||||
...(options?.imageSize ? { imageSize: options.imageSize } : {}),
|
||||
...withCustomData(options),
|
||||
});
|
||||
|
||||
const buildInkDefaults = (options?: AnnotationToolOptions, opacityOverride?: number): AnnotationDefaults => ({
|
||||
type: PdfAnnotationSubtype.INK,
|
||||
color: options?.color ?? (opacityOverride ? DEFAULTS.inkHighlighter : DEFAULTS.ink),
|
||||
opacity: options?.opacity ?? opacityOverride ?? 1,
|
||||
borderWidth: options?.thickness ?? (opacityOverride ? 6 : 2),
|
||||
strokeWidth: options?.thickness ?? (opacityOverride ? 6 : 2),
|
||||
lineWidth: options?.thickness ?? (opacityOverride ? 6 : 2),
|
||||
...withCustomData(options),
|
||||
});
|
||||
|
||||
const TOOL_DEFAULT_BUILDERS: Record<AnnotationToolId, ToolDefaultsBuilder> = {
|
||||
select: () => null,
|
||||
highlight: (options) => ({
|
||||
type: PdfAnnotationSubtype.HIGHLIGHT,
|
||||
color: options?.color ?? DEFAULTS.highlight,
|
||||
opacity: options?.opacity ?? 0.6,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
underline: (options) => ({
|
||||
type: PdfAnnotationSubtype.UNDERLINE,
|
||||
color: options?.color ?? DEFAULTS.underline,
|
||||
opacity: options?.opacity ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
strikeout: (options) => ({
|
||||
type: PdfAnnotationSubtype.STRIKEOUT,
|
||||
color: options?.color ?? DEFAULTS.strikeout,
|
||||
opacity: options?.opacity ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
squiggly: (options) => ({
|
||||
type: PdfAnnotationSubtype.SQUIGGLY,
|
||||
color: options?.color ?? DEFAULTS.squiggly,
|
||||
opacity: options?.opacity ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
ink: (options) => buildInkDefaults(options),
|
||||
inkHighlighter: (options) => buildInkDefaults(options, options?.opacity ?? 0.6),
|
||||
text: (options) => ({
|
||||
type: PdfAnnotationSubtype.FREETEXT,
|
||||
fontColor: options?.color ?? DEFAULTS.text,
|
||||
fontSize: options?.fontSize ?? 14,
|
||||
fontFamily: options?.fontFamily ?? 'Helvetica',
|
||||
textAlign: options?.textAlign ?? 0,
|
||||
opacity: options?.opacity ?? 1,
|
||||
borderWidth: options?.thickness ?? 1,
|
||||
...(options?.fillColor ? { backgroundColor: options.fillColor } : {}),
|
||||
...withCustomData(options),
|
||||
}),
|
||||
note: (options) => {
|
||||
const backgroundColor = options?.fillColor ?? DEFAULTS.note;
|
||||
const fontColor = options?.color ?? DEFAULTS.text;
|
||||
return {
|
||||
type: PdfAnnotationSubtype.FREETEXT,
|
||||
fontColor,
|
||||
color: fontColor,
|
||||
fontFamily: options?.fontFamily ?? 'Helvetica',
|
||||
textAlign: options?.textAlign ?? 0,
|
||||
fontSize: options?.fontSize ?? 12,
|
||||
opacity: options?.opacity ?? 1,
|
||||
backgroundColor,
|
||||
borderWidth: options?.thickness ?? 0,
|
||||
contents: options?.contents ?? 'Note',
|
||||
icon: getIconEnum(options?.icon),
|
||||
...withCustomData(options),
|
||||
};
|
||||
},
|
||||
square: (options) => ({
|
||||
type: PdfAnnotationSubtype.SQUARE,
|
||||
color: options?.color ?? DEFAULTS.shapeFill,
|
||||
strokeColor: options?.strokeColor ?? DEFAULTS.shapeStroke,
|
||||
opacity: options?.opacity ?? DEFAULTS.shapeOpacity,
|
||||
fillOpacity: options?.fillOpacity ?? DEFAULTS.shapeOpacity,
|
||||
strokeOpacity: options?.strokeOpacity ?? DEFAULTS.shapeOpacity,
|
||||
borderWidth: options?.borderWidth ?? 1,
|
||||
strokeWidth: options?.borderWidth ?? 1,
|
||||
lineWidth: options?.borderWidth ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
circle: (options) => ({
|
||||
type: PdfAnnotationSubtype.CIRCLE,
|
||||
color: options?.color ?? DEFAULTS.shapeFill,
|
||||
strokeColor: options?.strokeColor ?? DEFAULTS.shapeStroke,
|
||||
opacity: options?.opacity ?? DEFAULTS.shapeOpacity,
|
||||
fillOpacity: options?.fillOpacity ?? DEFAULTS.shapeOpacity,
|
||||
strokeOpacity: options?.strokeOpacity ?? DEFAULTS.shapeOpacity,
|
||||
borderWidth: options?.borderWidth ?? 1,
|
||||
strokeWidth: options?.borderWidth ?? 1,
|
||||
lineWidth: options?.borderWidth ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
line: (options) => ({
|
||||
type: PdfAnnotationSubtype.LINE,
|
||||
color: options?.color ?? '#1565c0',
|
||||
strokeColor: options?.color ?? '#1565c0',
|
||||
opacity: options?.opacity ?? 1,
|
||||
borderWidth: options?.borderWidth ?? 2,
|
||||
strokeWidth: options?.borderWidth ?? 2,
|
||||
lineWidth: options?.borderWidth ?? 2,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
lineArrow: (options) => ({
|
||||
type: PdfAnnotationSubtype.LINE,
|
||||
color: options?.color ?? '#1565c0',
|
||||
strokeColor: options?.color ?? '#1565c0',
|
||||
opacity: options?.opacity ?? 1,
|
||||
borderWidth: options?.borderWidth ?? 2,
|
||||
strokeWidth: options?.borderWidth ?? 2,
|
||||
lineWidth: options?.borderWidth ?? 2,
|
||||
startStyle: 'None',
|
||||
endStyle: 'ClosedArrow',
|
||||
lineEndingStyles: { start: 'None', end: 'ClosedArrow' },
|
||||
...withCustomData(options),
|
||||
}),
|
||||
polyline: (options) => ({
|
||||
type: PdfAnnotationSubtype.POLYLINE,
|
||||
color: options?.color ?? '#1565c0',
|
||||
opacity: options?.opacity ?? 1,
|
||||
borderWidth: options?.borderWidth ?? 2,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
polygon: (options) => ({
|
||||
type: PdfAnnotationSubtype.POLYGON,
|
||||
color: options?.color ?? DEFAULTS.shapeFill,
|
||||
strokeColor: options?.strokeColor ?? DEFAULTS.shapeStroke,
|
||||
opacity: options?.opacity ?? DEFAULTS.shapeOpacity,
|
||||
fillOpacity: options?.fillOpacity ?? DEFAULTS.shapeOpacity,
|
||||
strokeOpacity: options?.strokeOpacity ?? DEFAULTS.shapeOpacity,
|
||||
borderWidth: options?.borderWidth ?? 1,
|
||||
strokeWidth: options?.borderWidth ?? 1,
|
||||
lineWidth: options?.borderWidth ?? 1,
|
||||
...withCustomData(options),
|
||||
}),
|
||||
stamp: buildStampDefaults,
|
||||
signatureStamp: buildStampDefaults,
|
||||
signatureInk: (options) => buildInkDefaults(options),
|
||||
};
|
||||
|
||||
export const AnnotationAPIBridge = forwardRef<AnnotationAPI>(function AnnotationAPIBridge(_props, ref) {
|
||||
// Use the provided annotation API just like SignatureAPIBridge/HistoryAPIBridge
|
||||
const { provides: annotationApi } = useAnnotationCapability();
|
||||
|
||||
const buildAnnotationDefaults = useCallback(
|
||||
(toolId: AnnotationToolId, options?: AnnotationToolOptions) =>
|
||||
TOOL_DEFAULT_BUILDERS[toolId]?.(options) ?? null,
|
||||
[]
|
||||
);
|
||||
|
||||
const configureAnnotationTool = useCallback(
|
||||
(toolId: AnnotationToolId, options?: AnnotationToolOptions) => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
if (!api?.setActiveTool) return;
|
||||
|
||||
const defaults = buildAnnotationDefaults(toolId, options);
|
||||
|
||||
// Reset tool first, then activate (like SignatureAPIBridge does)
|
||||
api.setActiveTool(null);
|
||||
api.setActiveTool(toolId === 'select' ? null : toolId);
|
||||
|
||||
// Verify tool was activated before setting defaults (like SignatureAPIBridge does)
|
||||
const activeTool = api.getActiveTool?.();
|
||||
if (activeTool && activeTool.id === toolId && defaults) {
|
||||
api.setToolDefaults?.(toolId, defaults);
|
||||
}
|
||||
},
|
||||
[annotationApi, buildAnnotationDefaults]
|
||||
);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
activateAnnotationTool: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => {
|
||||
configureAnnotationTool(toolId, options);
|
||||
},
|
||||
setAnnotationStyle: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => {
|
||||
const defaults = buildAnnotationDefaults(toolId, options);
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
if (defaults && api?.setToolDefaults) {
|
||||
api.setToolDefaults(toolId, defaults);
|
||||
}
|
||||
},
|
||||
getSelectedAnnotation: () => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
if (!api?.getSelectedAnnotation) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return api.getSelectedAnnotation();
|
||||
} catch (error) {
|
||||
// Some EmbedPDF builds expose getSelectedAnnotation with an internal
|
||||
// `this`/state dependency (e.g. reading `selectedUid` from undefined).
|
||||
// If that happens, fail gracefully and treat it as "no selection"
|
||||
// instead of crashing the entire annotations tool.
|
||||
console.error('[AnnotationAPIBridge] getSelectedAnnotation failed:', error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
deselectAnnotation: () => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
api?.deselectAnnotation?.();
|
||||
},
|
||||
updateAnnotation: (pageIndex: number, annotationId: string, patch: AnnotationPatch) => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
api?.updateAnnotation?.(pageIndex, annotationId, patch);
|
||||
},
|
||||
deactivateTools: () => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
api?.setActiveTool?.(null);
|
||||
},
|
||||
onAnnotationEvent: (listener: (event: AnnotationEvent) => void) => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
if (api?.onAnnotationEvent) {
|
||||
return api.onAnnotationEvent(listener);
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
getActiveTool: () => {
|
||||
const api = annotationApi as AnnotationApiSurface | undefined;
|
||||
return api?.getActiveTool?.() ?? null;
|
||||
},
|
||||
}),
|
||||
[annotationApi, configureAnnotationTool, buildAnnotationDefaults]
|
||||
);
|
||||
|
||||
return null;
|
||||
});
|
||||
@@ -17,6 +17,8 @@ import { isStirlingFile } from '@app/types/fileContext';
|
||||
import { useViewerRightRailButtons } from '@app/components/viewer/useViewerRightRailButtons';
|
||||
import { StampPlacementOverlay } from '@app/components/viewer/StampPlacementOverlay';
|
||||
import { useWheelZoom } from '@app/hooks/useWheelZoom';
|
||||
import { ViewerMorphAnchor } from '@app/components/viewer/ViewerMorphAnchor';
|
||||
import { ViewerPageMorphs } from '@app/components/viewer/ViewerPageMorphs';
|
||||
|
||||
export interface EmbedPdfViewerProps {
|
||||
sidebarsVisible: boolean;
|
||||
@@ -56,9 +58,6 @@ const EmbedPdfViewerContent = ({
|
||||
exportActions,
|
||||
} = useViewer();
|
||||
|
||||
// Register viewer right-rail buttons
|
||||
useViewerRightRailButtons();
|
||||
|
||||
const scrollState = getScrollState();
|
||||
const rotationState = getRotationState();
|
||||
|
||||
@@ -70,8 +69,13 @@ const EmbedPdfViewerContent = ({
|
||||
}
|
||||
}, [rotationState.rotation]);
|
||||
|
||||
// Get signature context
|
||||
const { signatureApiRef, historyApiRef, signatureConfig, isPlacementMode } = useSignature();
|
||||
// Get signature and annotation contexts
|
||||
const { signatureApiRef, annotationApiRef, historyApiRef, signatureConfig, isPlacementMode } = useSignature();
|
||||
|
||||
// Track whether there are unsaved annotation changes in this viewer session.
|
||||
// This is our source of truth for navigation guards; it is set when the
|
||||
// annotation history changes, and cleared after we successfully apply changes.
|
||||
const hasAnnotationChangesRef = useRef(false);
|
||||
|
||||
// Get current file from FileContext
|
||||
const { selectors, state } = useFileState();
|
||||
@@ -85,8 +89,8 @@ const EmbedPdfViewerContent = ({
|
||||
|
||||
// Check if we're in an annotation tool
|
||||
const { selectedTool } = useNavigationState();
|
||||
// Tools that require the annotation layer (Sign, Add Text, Add Image)
|
||||
const isInAnnotationTool = selectedTool === 'sign' || selectedTool === 'addText' || selectedTool === 'addImage';
|
||||
// Tools that require the annotation layer (Sign, Add Text, Add Image, Annotate)
|
||||
const isInAnnotationTool = selectedTool === 'sign' || selectedTool === 'addText' || selectedTool === 'addImage' || selectedTool === 'annotate';
|
||||
|
||||
// Sync isAnnotationMode in ViewerContext with current tool
|
||||
useEffect(() => {
|
||||
@@ -132,6 +136,13 @@ const EmbedPdfViewerContent = ({
|
||||
return null;
|
||||
}, [previewFile, activeFiles, activeFileIndex]);
|
||||
|
||||
const currentFileId = React.useMemo(() => {
|
||||
if (currentFile && isStirlingFile(currentFile)) {
|
||||
return currentFile.fileId;
|
||||
}
|
||||
return undefined;
|
||||
}, [currentFile]);
|
||||
|
||||
// Get file with URL for rendering
|
||||
const fileWithUrl = useFileWithUrl(currentFile);
|
||||
|
||||
@@ -148,6 +159,13 @@ const EmbedPdfViewerContent = ({
|
||||
}
|
||||
}, [previewFile, fileWithUrl]);
|
||||
|
||||
const fileForThumbnails = React.useMemo(() => {
|
||||
if (effectiveFile?.file instanceof File) {
|
||||
return effectiveFile.file;
|
||||
}
|
||||
return null;
|
||||
}, [effectiveFile]);
|
||||
|
||||
const bookmarkCacheKey = React.useMemo(() => {
|
||||
if (currentFile && isStirlingFile(currentFile)) {
|
||||
return currentFile.fileId;
|
||||
@@ -225,6 +243,31 @@ const EmbedPdfViewerContent = ({
|
||||
};
|
||||
}, [isViewerHovered, isSearchInterfaceVisible, zoomActions, searchInterfaceActions]);
|
||||
|
||||
// Watch the annotation history API to detect when the document becomes "dirty".
|
||||
// We treat any change that makes the history undoable as unsaved changes until
|
||||
// the user explicitly applies them via applyChanges.
|
||||
useEffect(() => {
|
||||
const historyApi = historyApiRef.current;
|
||||
if (!historyApi || !historyApi.subscribe) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateHasChanges = () => {
|
||||
const canUndo = historyApi.canUndo?.() ?? false;
|
||||
if (!hasAnnotationChangesRef.current && canUndo) {
|
||||
hasAnnotationChangesRef.current = true;
|
||||
setHasUnsavedChanges(true);
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = historyApi.subscribe(updateHasChanges);
|
||||
return () => {
|
||||
if (typeof unsubscribe === 'function') {
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}, [historyApiRef.current, setHasUnsavedChanges]);
|
||||
|
||||
// Register checker for unsaved changes (annotations only for now)
|
||||
useEffect(() => {
|
||||
if (previewFile) {
|
||||
@@ -232,39 +275,28 @@ const EmbedPdfViewerContent = ({
|
||||
}
|
||||
|
||||
const checkForChanges = () => {
|
||||
// Check for annotation changes via history
|
||||
const hasAnnotationChanges = historyApiRef.current?.canUndo() || false;
|
||||
|
||||
console.log('[Viewer] Checking for unsaved changes:', {
|
||||
hasAnnotationChanges
|
||||
});
|
||||
const hasAnnotationChanges = hasAnnotationChangesRef.current;
|
||||
return hasAnnotationChanges;
|
||||
};
|
||||
|
||||
console.log('[Viewer] Registering unsaved changes checker');
|
||||
registerUnsavedChangesChecker(checkForChanges);
|
||||
|
||||
return () => {
|
||||
console.log('[Viewer] Unregistering unsaved changes checker');
|
||||
unregisterUnsavedChangesChecker();
|
||||
};
|
||||
}, [historyApiRef, previewFile, registerUnsavedChangesChecker, unregisterUnsavedChangesChecker]);
|
||||
}, [previewFile, registerUnsavedChangesChecker, unregisterUnsavedChangesChecker]);
|
||||
|
||||
// Apply changes - save annotations to new file version
|
||||
const applyChanges = useCallback(async () => {
|
||||
if (!currentFile || activeFileIds.length === 0) return;
|
||||
|
||||
try {
|
||||
console.log('[Viewer] Applying changes - exporting PDF with annotations');
|
||||
|
||||
// Step 1: Export PDF with annotations using EmbedPDF
|
||||
const arrayBuffer = await exportActions.saveAsCopy();
|
||||
if (!arrayBuffer) {
|
||||
throw new Error('Failed to export PDF');
|
||||
}
|
||||
|
||||
console.log('[Viewer] Exported PDF size:', arrayBuffer.byteLength);
|
||||
|
||||
// Step 2: Convert ArrayBuffer to File
|
||||
const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
|
||||
const filename = currentFile.name || 'document.pdf';
|
||||
@@ -279,12 +311,29 @@ const EmbedPdfViewerContent = ({
|
||||
// Step 4: Consume files (replace in context)
|
||||
await actions.consumeFiles(activeFileIds, stirlingFiles, stubs);
|
||||
|
||||
// Mark annotations as saved so navigation away from the viewer is allowed.
|
||||
hasAnnotationChangesRef.current = false;
|
||||
setHasUnsavedChanges(false);
|
||||
} catch (error) {
|
||||
console.error('Apply changes failed:', error);
|
||||
}
|
||||
}, [currentFile, activeFileIds, exportActions, actions, selectors, setHasUnsavedChanges]);
|
||||
|
||||
// Expose annotation apply via a global event so tools (like Annotate) can
|
||||
// trigger saves from the left sidebar without tight coupling.
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
void applyChanges();
|
||||
};
|
||||
window.addEventListener('stirling-annotations-apply', handler);
|
||||
return () => {
|
||||
window.removeEventListener('stirling-annotations-apply', handler);
|
||||
};
|
||||
}, [applyChanges]);
|
||||
|
||||
// Register viewer right-rail buttons
|
||||
useViewerRightRailButtons();
|
||||
|
||||
const sidebarWidthRem = 15;
|
||||
const totalRightMargin =
|
||||
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0);
|
||||
@@ -302,6 +351,8 @@ const EmbedPdfViewerContent = ({
|
||||
overflow: 'hidden',
|
||||
contain: 'layout style paint'
|
||||
}}>
|
||||
<ViewerMorphAnchor fileId={currentFileId} />
|
||||
<ViewerPageMorphs fileId={currentFileId} file={fileForThumbnails} />
|
||||
{/* Close Button - Only show in preview mode */}
|
||||
{onClose && previewFile && (
|
||||
<ActionIcon
|
||||
@@ -340,6 +391,7 @@ const EmbedPdfViewerContent = ({
|
||||
enableAnnotations={isAnnotationMode}
|
||||
showBakedAnnotations={isAnnotationsVisible}
|
||||
signatureApiRef={signatureApiRef as React.RefObject<any>}
|
||||
annotationApiRef={annotationApiRef as React.RefObject<any>}
|
||||
historyApiRef={historyApiRef as React.RefObject<any>}
|
||||
onSignatureAdded={() => {
|
||||
// Handle signature added - for debugging, enable console logs as needed
|
||||
|
||||
@@ -38,8 +38,9 @@ import { SearchAPIBridge } from '@app/components/viewer/SearchAPIBridge';
|
||||
import { ThumbnailAPIBridge } from '@app/components/viewer/ThumbnailAPIBridge';
|
||||
import { RotateAPIBridge } from '@app/components/viewer/RotateAPIBridge';
|
||||
import { SignatureAPIBridge } from '@app/components/viewer/SignatureAPIBridge';
|
||||
import { AnnotationAPIBridge } from '@app/components/viewer/AnnotationAPIBridge';
|
||||
import { HistoryAPIBridge } from '@app/components/viewer/HistoryAPIBridge';
|
||||
import type { SignatureAPI, HistoryAPI } from '@app/components/viewer/viewerTypes';
|
||||
import type { SignatureAPI, AnnotationAPI, HistoryAPI } from '@app/components/viewer/viewerTypes';
|
||||
import { ExportAPIBridge } from '@app/components/viewer/ExportAPIBridge';
|
||||
import { BookmarkAPIBridge } from '@app/components/viewer/BookmarkAPIBridge';
|
||||
import { PrintAPIBridge } from '@app/components/viewer/PrintAPIBridge';
|
||||
@@ -55,10 +56,11 @@ interface LocalEmbedPDFProps {
|
||||
showBakedAnnotations?: boolean;
|
||||
onSignatureAdded?: (annotation: any) => void;
|
||||
signatureApiRef?: React.RefObject<SignatureAPI>;
|
||||
annotationApiRef?: React.RefObject<AnnotationAPI>;
|
||||
historyApiRef?: React.RefObject<HistoryAPI>;
|
||||
}
|
||||
|
||||
export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedAnnotations = true, onSignatureAdded, signatureApiRef, historyApiRef }: LocalEmbedPDFProps) {
|
||||
export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedAnnotations = true, onSignatureAdded, signatureApiRef, annotationApiRef, historyApiRef }: LocalEmbedPDFProps) {
|
||||
const { t } = useTranslation();
|
||||
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
|
||||
const [, setAnnotations] = useState<Array<{id: string, pageIndex: number, rect: any}>>([]);
|
||||
@@ -123,10 +125,8 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedA
|
||||
selectAfterCreate: true,
|
||||
}),
|
||||
|
||||
// Register pan plugin (depends on Viewport, InteractionManager)
|
||||
createPluginRegistration(PanPluginPackage, {
|
||||
defaultMode: 'mobile', // Try mobile mode which might be more permissive
|
||||
}),
|
||||
// Register pan plugin (depends on Viewport, InteractionManager) - keep disabled to prevent drag panning
|
||||
createPluginRegistration(PanPluginPackage, {}),
|
||||
|
||||
// Register zoom plugin with configuration
|
||||
createPluginRegistration(ZoomPluginPackage, {
|
||||
@@ -252,7 +252,315 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedA
|
||||
if (!annotationApi) return;
|
||||
|
||||
if (enableAnnotations) {
|
||||
annotationApi.addTool({
|
||||
const ensureTool = (tool: any) => {
|
||||
const existing = annotationApi.getTool?.(tool.id);
|
||||
if (!existing) {
|
||||
annotationApi.addTool(tool);
|
||||
}
|
||||
};
|
||||
|
||||
ensureTool({
|
||||
id: 'highlight',
|
||||
name: 'Highlight',
|
||||
interaction: { exclusive: true, cursor: 'text', textSelection: true },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.HIGHLIGHT ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.HIGHLIGHT,
|
||||
color: '#ffd54f',
|
||||
opacity: 0.6,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'underline',
|
||||
name: 'Underline',
|
||||
interaction: { exclusive: true, cursor: 'text', textSelection: true },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.UNDERLINE ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.UNDERLINE,
|
||||
color: '#ffb300',
|
||||
opacity: 1,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'strikeout',
|
||||
name: 'Strikeout',
|
||||
interaction: { exclusive: true, cursor: 'text', textSelection: true },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.STRIKEOUT ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.STRIKEOUT,
|
||||
color: '#e53935',
|
||||
opacity: 1,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'squiggly',
|
||||
name: 'Squiggly',
|
||||
interaction: { exclusive: true, cursor: 'text', textSelection: true },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.SQUIGGLY ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.SQUIGGLY,
|
||||
color: '#00acc1',
|
||||
opacity: 1,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'ink',
|
||||
name: 'Pen',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.INK ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.INK,
|
||||
color: '#1f2933',
|
||||
opacity: 1,
|
||||
borderWidth: 2,
|
||||
lineWidth: 2,
|
||||
strokeWidth: 2,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'inkHighlighter',
|
||||
name: 'Ink Highlighter',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.INK && annotation.color === '#ffd54f' ? 8 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.INK,
|
||||
color: '#ffd54f',
|
||||
opacity: 0.5,
|
||||
borderWidth: 6,
|
||||
lineWidth: 6,
|
||||
strokeWidth: 6,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'square',
|
||||
name: 'Square',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.SQUARE ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.SQUARE,
|
||||
color: '#0000ff', // fill color (blue)
|
||||
strokeColor: '#cf5b5b', // border color (reddish pink)
|
||||
opacity: 0.5,
|
||||
borderWidth: 1,
|
||||
strokeWidth: 1,
|
||||
lineWidth: 1,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
defaultSize: { width: 120, height: 90 },
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'circle',
|
||||
name: 'Circle',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.CIRCLE ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.CIRCLE,
|
||||
color: '#0000ff', // fill color (blue)
|
||||
strokeColor: '#cf5b5b', // border color (reddish pink)
|
||||
opacity: 0.5,
|
||||
borderWidth: 1,
|
||||
strokeWidth: 1,
|
||||
lineWidth: 1,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
defaultSize: { width: 100, height: 100 },
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'line',
|
||||
name: 'Line',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.LINE ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.LINE,
|
||||
color: '#1565c0',
|
||||
opacity: 1,
|
||||
borderWidth: 2,
|
||||
strokeWidth: 2,
|
||||
lineWidth: 2,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
defaultLength: 120,
|
||||
defaultAngle: 0,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'lineArrow',
|
||||
name: 'Arrow',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.LINE && (annotation.endStyle === 'ClosedArrow' || annotation.lineEndingStyles?.end === 'ClosedArrow') ? 9 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.LINE,
|
||||
color: '#1565c0',
|
||||
opacity: 1,
|
||||
borderWidth: 2,
|
||||
startStyle: 'None',
|
||||
endStyle: 'ClosedArrow',
|
||||
lineEndingStyles: { start: 'None', end: 'ClosedArrow' },
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
defaultLength: 120,
|
||||
defaultAngle: 0,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'polyline',
|
||||
name: 'Polyline',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.POLYLINE ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.POLYLINE,
|
||||
color: '#1565c0',
|
||||
opacity: 1,
|
||||
borderWidth: 2,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
finishOnDoubleClick: true,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'polygon',
|
||||
name: 'Polygon',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.POLYGON ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.POLYGON,
|
||||
color: '#0000ff', // fill color (blue)
|
||||
strokeColor: '#cf5b5b', // border color (reddish pink)
|
||||
opacity: 0.5,
|
||||
borderWidth: 1,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
finishOnDoubleClick: true,
|
||||
defaultSize: { width: 140, height: 100 },
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'text',
|
||||
name: 'Text',
|
||||
interaction: { exclusive: true, cursor: 'text' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.FREETEXT ? 10 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.FREETEXT,
|
||||
textColor: '#111111',
|
||||
fontSize: 14,
|
||||
fontFamily: 'Helvetica',
|
||||
opacity: 1,
|
||||
interiorColor: '#fffef7',
|
||||
contents: 'Text',
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'note',
|
||||
name: 'Note',
|
||||
interaction: { exclusive: true, cursor: 'pointer' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.FREETEXT ? 8 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.FREETEXT,
|
||||
textColor: '#1b1b1b',
|
||||
color: '#ffa000',
|
||||
interiorColor: '#fff8e1',
|
||||
opacity: 1,
|
||||
contents: 'Note',
|
||||
fontSize: 12,
|
||||
},
|
||||
clickBehavior: {
|
||||
enabled: true,
|
||||
defaultSize: { width: 160, height: 100 },
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: false,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'stamp',
|
||||
name: 'Image Stamp',
|
||||
interaction: { exclusive: false, cursor: 'copy' },
|
||||
matchScore: (annotation: any) => (annotation.type === PdfAnnotationSubtype.STAMP ? 5 : 0),
|
||||
defaults: {
|
||||
type: PdfAnnotationSubtype.STAMP,
|
||||
},
|
||||
behavior: {
|
||||
deactivateToolAfterCreate: true,
|
||||
selectAfterCreate: true,
|
||||
},
|
||||
});
|
||||
|
||||
ensureTool({
|
||||
id: 'signatureStamp',
|
||||
name: 'Digital Signature',
|
||||
interaction: { exclusive: false, cursor: 'copy' },
|
||||
@@ -262,7 +570,7 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedA
|
||||
},
|
||||
});
|
||||
|
||||
annotationApi.addTool({
|
||||
ensureTool({
|
||||
id: 'signatureInk',
|
||||
name: 'Signature Draw',
|
||||
interaction: { exclusive: true, cursor: 'crosshair' },
|
||||
@@ -310,6 +618,7 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, showBakedA
|
||||
<ThumbnailAPIBridge />
|
||||
<RotateAPIBridge />
|
||||
{enableAnnotations && <SignatureAPIBridge ref={signatureApiRef} />}
|
||||
{enableAnnotations && <AnnotationAPIBridge ref={annotationApiRef} />}
|
||||
{enableAnnotations && <HistoryAPIBridge ref={historyApiRef} />}
|
||||
<ExportAPIBridge />
|
||||
<BookmarkAPIBridge />
|
||||
|
||||
@@ -104,12 +104,20 @@ const createTextStampImage = (
|
||||
|
||||
ctx.fillStyle = textColor;
|
||||
ctx.font = `${fontSize}px ${fontFamily}`;
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textAlign = config.textAlign || 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
const horizontalPadding = paddingX;
|
||||
const verticalCenter = naturalHeight / 2;
|
||||
ctx.fillText(text, horizontalPadding, verticalCenter);
|
||||
|
||||
let xPosition = horizontalPadding;
|
||||
if (config.textAlign === 'center') {
|
||||
xPosition = naturalWidth / 2;
|
||||
} else if (config.textAlign === 'right') {
|
||||
xPosition = naturalWidth - horizontalPadding;
|
||||
}
|
||||
|
||||
ctx.fillText(text, xPosition, verticalCenter);
|
||||
|
||||
return {
|
||||
dataUrl: canvas.toDataURL('image/png'),
|
||||
@@ -199,12 +207,21 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
|
||||
}
|
||||
}, [annotationApi, signatureConfig, placementPreviewSize, applyStampDefaults, cssToPdfSize]);
|
||||
|
||||
|
||||
// Enable keyboard deletion of selected annotations
|
||||
useEffect(() => {
|
||||
// Always enable delete key when we have annotation API and are in sign mode
|
||||
if (!annotationApi || (isPlacementMode === undefined)) return;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
// Skip delete/backspace while a text input/textarea is focused (e.g., editing textbox)
|
||||
const target = event.target as HTMLElement | null;
|
||||
const tag = target?.tagName?.toLowerCase();
|
||||
const editable = target?.getAttribute?.('contenteditable');
|
||||
if (tag === 'input' || tag === 'textarea' || editable === 'true') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'Delete' || event.key === 'Backspace') {
|
||||
const selectedAnnotation = annotationApi.getSelectedAnnotation?.();
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useMorphElement } from '@app/hooks/useMorphElement';
|
||||
|
||||
interface ViewerMorphAnchorProps {
|
||||
fileId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invisible anchor that registers the current viewer file for morph animations.
|
||||
* Gives the transition system a source/target element when coming from the viewer.
|
||||
*/
|
||||
export function ViewerMorphAnchor({ fileId }: ViewerMorphAnchorProps) {
|
||||
const morphId = fileId ? `file-${fileId}` : undefined;
|
||||
|
||||
const metadata = useMemo(() => {
|
||||
if (!fileId) return undefined;
|
||||
return { fileId, type: 'file' };
|
||||
}, [fileId]);
|
||||
|
||||
const ref = useMorphElement<HTMLDivElement>(
|
||||
morphId ?? 'viewer-file-anchor',
|
||||
metadata,
|
||||
{ onlyIn: ['viewer'], disabled: !fileId }
|
||||
);
|
||||
|
||||
if (!fileId) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-morph-id={morphId}
|
||||
data-morph-file-id={fileId}
|
||||
data-morph-type="file"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: '50%',
|
||||
top: '45%',
|
||||
width: '180px',
|
||||
height: '220px',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
pointerEvents: 'none',
|
||||
opacity: 0,
|
||||
borderRadius: '6px',
|
||||
background: 'transparent',
|
||||
zIndex: 5,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useMorphElement } from '@app/hooks/useMorphElement';
|
||||
import { useViewer } from '@app/contexts/ViewerContext';
|
||||
import { useThumbnailGeneration } from '@app/hooks/useThumbnailGeneration';
|
||||
|
||||
interface ViewerPageMorphsProps {
|
||||
fileId?: string;
|
||||
file?: File | null;
|
||||
}
|
||||
|
||||
interface PageMorphProps {
|
||||
fileId: string;
|
||||
pageNumber: number;
|
||||
indexOffset: number;
|
||||
thumbnail?: string;
|
||||
}
|
||||
|
||||
function ViewerPageMorph({ fileId, pageNumber, indexOffset, thumbnail }: PageMorphProps) {
|
||||
const morphId = `page-${fileId}-${pageNumber}`;
|
||||
const ref = useMorphElement<HTMLDivElement>(
|
||||
morphId,
|
||||
{ fileId, type: 'page', pageNumber, thumbnail },
|
||||
{ onlyIn: ['viewer'] }
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={morphId}
|
||||
ref={ref}
|
||||
data-morph-id={morphId}
|
||||
data-morph-file-id={fileId}
|
||||
data-morph-page-number={pageNumber}
|
||||
data-morph-type="page"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: '50%',
|
||||
top: `${40 + indexOffset * 26}%`,
|
||||
width: '140px',
|
||||
height: '180px',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
pointerEvents: 'none',
|
||||
opacity: 0,
|
||||
borderRadius: '4px',
|
||||
background: 'transparent',
|
||||
zIndex: 5,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the currently visible pages in the viewer for morph animations.
|
||||
* Uses limited slots to avoid excessive clones on long documents.
|
||||
*/
|
||||
export function ViewerPageMorphs({ fileId, file }: ViewerPageMorphsProps) {
|
||||
const { getScrollState, getThumbnailAPI } = useViewer();
|
||||
const scrollState = getScrollState();
|
||||
const thumbnailAPI = getThumbnailAPI();
|
||||
const { getThumbnailFromCache, requestThumbnail } = useThumbnailGeneration();
|
||||
const [thumbnailsByPage, setThumbnailsByPage] = useState<Record<number, string>>({});
|
||||
const pendingRequestsRef = useRef(new Map<number, Promise<string | null>>());
|
||||
const objectUrlsRef = useRef(new Map<number, string>());
|
||||
|
||||
// Derive a small window of visible pages around the current page
|
||||
const visiblePages = useMemo(() => {
|
||||
const { currentPage, totalPages } = scrollState;
|
||||
if (!currentPage || totalPages === 0) return [];
|
||||
const pages: number[] = [];
|
||||
for (let i = currentPage - 1; i <= currentPage + 2 && i <= totalPages; i++) {
|
||||
if (i >= 1) pages.push(i);
|
||||
}
|
||||
return pages;
|
||||
}, [scrollState.currentPage, scrollState.totalPages]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
objectUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
objectUrlsRef.current.clear();
|
||||
pendingRequestsRef.current.clear();
|
||||
setThumbnailsByPage({});
|
||||
};
|
||||
}, [fileId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!fileId || visiblePages.length === 0) return;
|
||||
|
||||
visiblePages.forEach((pageNumber) => {
|
||||
if (thumbnailsByPage[pageNumber] || pendingRequestsRef.current.has(pageNumber)) return;
|
||||
|
||||
const cacheKey = `${fileId}-page-${pageNumber}`;
|
||||
const cached = getThumbnailFromCache(cacheKey);
|
||||
if (cached) {
|
||||
setThumbnailsByPage((prev) => ({ ...prev, [pageNumber]: cached }));
|
||||
return;
|
||||
}
|
||||
|
||||
let requestPromise: Promise<string | null> | null = null;
|
||||
|
||||
if (thumbnailAPI?.renderThumb) {
|
||||
requestPromise = thumbnailAPI
|
||||
.renderThumb(pageNumber - 1, 0.18)
|
||||
.toPromise()
|
||||
.then((blob) => {
|
||||
if (!blob) return null;
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrlsRef.current.set(pageNumber, url);
|
||||
return url;
|
||||
})
|
||||
.catch(() => null);
|
||||
}
|
||||
|
||||
if (!requestPromise && file instanceof File) {
|
||||
requestPromise = requestThumbnail(cacheKey, file, pageNumber).catch(() => null);
|
||||
}
|
||||
|
||||
if (!requestPromise) return;
|
||||
|
||||
pendingRequestsRef.current.set(pageNumber, requestPromise);
|
||||
|
||||
requestPromise.then((thumbnail) => {
|
||||
pendingRequestsRef.current.delete(pageNumber);
|
||||
if (!thumbnail) return;
|
||||
setThumbnailsByPage((prev) => ({ ...prev, [pageNumber]: thumbnail }));
|
||||
});
|
||||
});
|
||||
}, [
|
||||
file,
|
||||
fileId,
|
||||
getThumbnailFromCache,
|
||||
requestThumbnail,
|
||||
thumbnailAPI,
|
||||
thumbnailsByPage,
|
||||
visiblePages,
|
||||
]);
|
||||
|
||||
if (!fileId) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{visiblePages.map((pageNumber, idx) => {
|
||||
const thumbSrc = thumbnailsByPage[pageNumber];
|
||||
|
||||
return (
|
||||
<ViewerPageMorph
|
||||
key={`morph-${fileId}-${pageNumber}`}
|
||||
fileId={fileId}
|
||||
pageNumber={pageNumber}
|
||||
indexOffset={idx}
|
||||
thumbnail={thumbSrc}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMemo, useState, useEffect, useCallback } from 'react';
|
||||
import { ActionIcon, Popover } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useViewer } from '@app/contexts/ViewerContext';
|
||||
@@ -9,6 +9,9 @@ import { SearchInterface } from '@app/components/viewer/SearchInterface';
|
||||
import ViewerAnnotationControls from '@app/components/shared/rightRail/ViewerAnnotationControls';
|
||||
import { useSidebarContext } from '@app/contexts/SidebarContext';
|
||||
import { useRightRailTooltipSide } from '@app/hooks/useRightRailTooltipSide';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import { useNavigationState } from '@app/contexts/NavigationContext';
|
||||
import { BASE_PATH, withBasePath } from '@app/constants/app';
|
||||
|
||||
export function useViewerRightRailButtons() {
|
||||
const { t, i18n } = useTranslation();
|
||||
@@ -16,6 +19,32 @@ export function useViewerRightRailButtons() {
|
||||
const [isPanning, setIsPanning] = useState<boolean>(() => viewer.getPanState()?.isPanning ?? false);
|
||||
const { sidebarRefs } = useSidebarContext();
|
||||
const { position: tooltipPosition } = useRightRailTooltipSide(sidebarRefs, 12);
|
||||
const { handleToolSelect } = useToolWorkflow();
|
||||
const { selectedTool } = useNavigationState();
|
||||
|
||||
const stripBasePath = useCallback((path: string) => {
|
||||
if (BASE_PATH && path.startsWith(BASE_PATH)) {
|
||||
return path.slice(BASE_PATH.length) || '/';
|
||||
}
|
||||
return path;
|
||||
}, []);
|
||||
|
||||
const isAnnotationsPath = useCallback(() => {
|
||||
const cleanPath = stripBasePath(window.location.pathname).toLowerCase();
|
||||
return cleanPath === '/annotations' || cleanPath.endsWith('/annotations');
|
||||
}, [stripBasePath]);
|
||||
|
||||
const [isAnnotationsActive, setIsAnnotationsActive] = useState<boolean>(() => isAnnotationsPath());
|
||||
|
||||
useEffect(() => {
|
||||
setIsAnnotationsActive(isAnnotationsPath());
|
||||
}, [selectedTool, isAnnotationsPath]);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePopState = () => setIsAnnotationsActive(isAnnotationsPath());
|
||||
window.addEventListener('popstate', handlePopState);
|
||||
return () => window.removeEventListener('popstate', handlePopState);
|
||||
}, [isAnnotationsPath]);
|
||||
|
||||
// Lift i18n labels out of memo for clarity
|
||||
const searchLabel = t('rightRail.search', 'Search PDF');
|
||||
@@ -25,9 +54,11 @@ export function useViewerRightRailButtons() {
|
||||
const sidebarLabel = t('rightRail.toggleSidebar', 'Toggle Sidebar');
|
||||
const bookmarkLabel = t('rightRail.toggleBookmarks', 'Toggle Bookmarks');
|
||||
const printLabel = t('rightRail.print', 'Print PDF');
|
||||
const annotationsLabel = t('rightRail.annotations', 'Annotations');
|
||||
const saveChangesLabel = t('rightRail.saveChanges', 'Save Changes');
|
||||
|
||||
const viewerButtons = useMemo<RightRailButtonWithAction[]>(() => {
|
||||
return [
|
||||
const buttons: RightRailButtonWithAction[] = [
|
||||
{
|
||||
id: 'viewer-search',
|
||||
tooltip: searchLabel,
|
||||
@@ -147,6 +178,36 @@ export function useViewerRightRailButtons() {
|
||||
viewer.printActions.print();
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'viewer-annotations',
|
||||
tooltip: annotationsLabel,
|
||||
ariaLabel: annotationsLabel,
|
||||
section: 'top' as const,
|
||||
order: 58,
|
||||
render: ({ disabled }) => (
|
||||
<Tooltip content={annotationsLabel} position={tooltipPosition} offset={12} arrow portalTarget={document.body}>
|
||||
<ActionIcon
|
||||
variant={isAnnotationsActive ? 'default' : 'subtle'}
|
||||
radius="md"
|
||||
className="right-rail-icon"
|
||||
onClick={() => {
|
||||
if (disabled || isAnnotationsActive) return;
|
||||
const targetPath = withBasePath('/annotations');
|
||||
if (window.location.pathname !== targetPath) {
|
||||
window.history.pushState(null, '', targetPath);
|
||||
}
|
||||
setIsAnnotationsActive(true);
|
||||
handleToolSelect('annotate');
|
||||
}}
|
||||
disabled={disabled || isAnnotationsActive}
|
||||
aria-pressed={isAnnotationsActive}
|
||||
style={isAnnotationsActive ? { backgroundColor: 'var(--right-rail-pan-active-bg)' } : undefined}
|
||||
>
|
||||
<LocalIcon icon="edit" width="1.5rem" height="1.5rem" />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'viewer-annotation-controls',
|
||||
section: 'top' as const,
|
||||
@@ -154,9 +215,30 @@ export function useViewerRightRailButtons() {
|
||||
render: ({ disabled }) => (
|
||||
<ViewerAnnotationControls currentView="viewer" disabled={disabled} />
|
||||
)
|
||||
}
|
||||
},
|
||||
];
|
||||
}, [t, i18n.language, viewer, isPanning, searchLabel, panLabel, rotateLeftLabel, rotateRightLabel, sidebarLabel, bookmarkLabel, printLabel, tooltipPosition]);
|
||||
|
||||
// Optional: Save button for annotations (always registered when this hook is used
|
||||
// with a save handler; uses a ref to avoid infinite re-registration loops).
|
||||
return buttons;
|
||||
}, [
|
||||
t,
|
||||
i18n.language,
|
||||
viewer,
|
||||
isPanning,
|
||||
searchLabel,
|
||||
panLabel,
|
||||
rotateLeftLabel,
|
||||
rotateRightLabel,
|
||||
sidebarLabel,
|
||||
bookmarkLabel,
|
||||
printLabel,
|
||||
tooltipPosition,
|
||||
annotationsLabel,
|
||||
saveChangesLabel,
|
||||
isAnnotationsActive,
|
||||
handleToolSelect,
|
||||
]);
|
||||
|
||||
useRightRailButtons(viewerButtons);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,17 @@ export interface SignatureAPI {
|
||||
getPageAnnotations: (pageIndex: number) => Promise<any[]>;
|
||||
}
|
||||
|
||||
export interface AnnotationAPI {
|
||||
activateAnnotationTool: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => void;
|
||||
setAnnotationStyle: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => void;
|
||||
getSelectedAnnotation: () => AnnotationSelection | null;
|
||||
deselectAnnotation: () => void;
|
||||
updateAnnotation: (pageIndex: number, annotationId: string, patch: AnnotationPatch) => void;
|
||||
deactivateTools: () => void;
|
||||
onAnnotationEvent?: (listener: (event: AnnotationEvent) => void) => void | (() => void);
|
||||
getActiveTool?: () => { id: AnnotationToolId } | null;
|
||||
}
|
||||
|
||||
export interface HistoryAPI {
|
||||
undo: () => void;
|
||||
redo: () => void;
|
||||
@@ -23,3 +34,50 @@ export interface HistoryAPI {
|
||||
canRedo: () => boolean;
|
||||
subscribe?: (listener: () => void) => () => void;
|
||||
}
|
||||
|
||||
export type AnnotationToolId =
|
||||
| 'select'
|
||||
| 'highlight'
|
||||
| 'underline'
|
||||
| 'strikeout'
|
||||
| 'squiggly'
|
||||
| 'ink'
|
||||
| 'inkHighlighter'
|
||||
| 'text'
|
||||
| 'note'
|
||||
| 'square'
|
||||
| 'circle'
|
||||
| 'line'
|
||||
| 'lineArrow'
|
||||
| 'polyline'
|
||||
| 'polygon'
|
||||
| 'stamp'
|
||||
| 'signatureStamp'
|
||||
| 'signatureInk';
|
||||
|
||||
export interface AnnotationEvent {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type AnnotationPatch = Record<string, unknown>;
|
||||
export type AnnotationSelection = unknown;
|
||||
|
||||
export interface AnnotationToolOptions {
|
||||
color?: string;
|
||||
fillColor?: string;
|
||||
strokeColor?: string;
|
||||
opacity?: number;
|
||||
strokeOpacity?: number;
|
||||
fillOpacity?: number;
|
||||
thickness?: number;
|
||||
borderWidth?: number;
|
||||
fontSize?: number;
|
||||
fontFamily?: string;
|
||||
textAlign?: number; // 0 = Left, 1 = Center, 2 = Right
|
||||
imageSrc?: string;
|
||||
imageSize?: { width: number; height: number };
|
||||
icon?: 'Comment' | 'Key' | 'Note' | 'Help' | 'NewParagraph' | 'Paragraph' | 'Insert';
|
||||
contents?: string;
|
||||
customData?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import React, { createContext, useContext, ReactNode, useRef } from 'react';
|
||||
import type { AnnotationAPI } from '@app/components/viewer/viewerTypes';
|
||||
|
||||
interface AnnotationContextValue {
|
||||
annotationApiRef: React.RefObject<AnnotationAPI | null>;
|
||||
}
|
||||
|
||||
const AnnotationContext = createContext<AnnotationContextValue | undefined>(undefined);
|
||||
|
||||
export const AnnotationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const annotationApiRef = useRef<AnnotationAPI>(null);
|
||||
|
||||
const value: AnnotationContextValue = {
|
||||
annotationApiRef,
|
||||
};
|
||||
|
||||
return <AnnotationContext.Provider value={value}>{children}</AnnotationContext.Provider>;
|
||||
};
|
||||
|
||||
export const useAnnotation = (): AnnotationContextValue => {
|
||||
const context = useContext(AnnotationContext);
|
||||
if (!context) {
|
||||
throw new Error('useAnnotation must be used within an AnnotationProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { createContext, useContext, useState, ReactNode, useCallback, useRef } from 'react';
|
||||
import { SignParameters } from '@app/hooks/tools/sign/useSignParameters';
|
||||
import type { SignatureAPI, HistoryAPI } from '@app/components/viewer/viewerTypes';
|
||||
import type { SignatureAPI, HistoryAPI, AnnotationAPI } from '@app/components/viewer/viewerTypes';
|
||||
|
||||
// Signature state interface
|
||||
interface SignatureState {
|
||||
@@ -34,6 +34,7 @@ interface SignatureActions {
|
||||
// Combined context interface
|
||||
interface SignatureContextValue extends SignatureState, SignatureActions {
|
||||
signatureApiRef: React.RefObject<SignatureAPI | null>;
|
||||
annotationApiRef: React.RefObject<AnnotationAPI | null>;
|
||||
historyApiRef: React.RefObject<HistoryAPI | null>;
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ const initialState: SignatureState = {
|
||||
export const SignatureProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const [state, setState] = useState<SignatureState>(initialState);
|
||||
const signatureApiRef = useRef<SignatureAPI>(null);
|
||||
const annotationApiRef = useRef<AnnotationAPI>(null);
|
||||
const historyApiRef = useRef<HistoryAPI>(null);
|
||||
const imageDataStore = useRef<Map<string, string>>(new Map());
|
||||
|
||||
@@ -157,6 +159,7 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({ children
|
||||
const contextValue: SignatureContextValue = {
|
||||
...state,
|
||||
signatureApiRef,
|
||||
annotationApiRef,
|
||||
historyApiRef,
|
||||
setSignatureConfig,
|
||||
setPlacementMode,
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useRef } from 'react';
|
||||
import type { BaseWorkbenchType } from '../types/workbench';
|
||||
|
||||
/**
|
||||
* Element snapshot for morphing animations
|
||||
*/
|
||||
export interface ElementSnapshot {
|
||||
id: string;
|
||||
rect: DOMRect;
|
||||
element: HTMLElement;
|
||||
thumbnail?: string;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition state tracking
|
||||
*/
|
||||
interface TransitionState {
|
||||
isTransitioning: boolean;
|
||||
fromWorkbench: BaseWorkbenchType | null;
|
||||
toWorkbench: BaseWorkbenchType | null;
|
||||
sourceSnapshots: ElementSnapshot[];
|
||||
targetSnapshots: ElementSnapshot[];
|
||||
}
|
||||
|
||||
interface WorkbenchTransitionContextValue {
|
||||
// Transition state
|
||||
transitionState: TransitionState;
|
||||
|
||||
// Register elements for morphing
|
||||
registerSourceElement: (id: string, element: HTMLElement, metadata?: Record<string, any>) => void;
|
||||
registerTargetElement: (id: string, element: HTMLElement, metadata?: Record<string, any>) => void;
|
||||
|
||||
// Initiate transition
|
||||
startTransition: (from: BaseWorkbenchType, to: BaseWorkbenchType, onViewChange?: () => void) => Promise<void>;
|
||||
completeTransition: () => void;
|
||||
|
||||
// Get morph pairs
|
||||
getMorphPairs: () => Array<{ source: ElementSnapshot; target: ElementSnapshot }>;
|
||||
}
|
||||
|
||||
const WorkbenchTransitionContext = createContext<WorkbenchTransitionContextValue | null>(null);
|
||||
|
||||
export function useWorkbenchTransition() {
|
||||
const context = useContext(WorkbenchTransitionContext);
|
||||
if (!context) {
|
||||
throw new Error('useWorkbenchTransition must be used within WorkbenchTransitionProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface WorkbenchTransitionProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const MAX_MORPH_ELEMENTS = 40; // cap clones to what can reasonably be on screen
|
||||
|
||||
export function WorkbenchTransitionProvider({ children }: WorkbenchTransitionProviderProps) {
|
||||
const [transitionState, setTransitionState] = useState<TransitionState>({
|
||||
isTransitioning: false,
|
||||
fromWorkbench: null,
|
||||
toWorkbench: null,
|
||||
sourceSnapshots: [],
|
||||
targetSnapshots: [],
|
||||
});
|
||||
|
||||
// Use refs to store element registrations
|
||||
const sourceElementsRef = useRef<Map<string, { element: HTMLElement; metadata?: Record<string, any> }>>(new Map());
|
||||
const targetElementsRef = useRef<Map<string, { element: HTMLElement; metadata?: Record<string, any> }>>(new Map());
|
||||
|
||||
const registerSourceElement = useCallback((id: string, element: HTMLElement, metadata?: Record<string, any>) => {
|
||||
sourceElementsRef.current.set(id, { element, metadata });
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[WorkbenchTransition] Source registered', { id, fileId: metadata?.fileId, type: metadata?.type });
|
||||
}
|
||||
}, []);
|
||||
|
||||
const registerTargetElement = useCallback((id: string, element: HTMLElement, metadata?: Record<string, any>) => {
|
||||
targetElementsRef.current.set(id, { element, metadata });
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[WorkbenchTransition] Target registered', { id, fileId: metadata?.fileId, type: metadata?.type, page: metadata?.pageNumber });
|
||||
}
|
||||
}, []);
|
||||
|
||||
const captureSnapshot = useCallback((id: string, element: HTMLElement, metadata?: Record<string, any>): ElementSnapshot => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
|
||||
// Try to capture thumbnail if it's an image or provided metadata
|
||||
let thumbnail: string | undefined;
|
||||
const img = element.querySelector('img');
|
||||
if (img && img.src) {
|
||||
thumbnail = img.src;
|
||||
} else if (metadata?.thumbnail) {
|
||||
thumbnail = metadata.thumbnail;
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
rect,
|
||||
element,
|
||||
thumbnail,
|
||||
metadata,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startTransition = useCallback(async (from: BaseWorkbenchType, to: BaseWorkbenchType, onViewChange?: () => void) => {
|
||||
const waitForNextPaint = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const hasTargetsOfType = (type: string) => {
|
||||
for (const [, data] of targetElementsRef.current) {
|
||||
if (data.metadata?.type === type) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Capture source snapshots
|
||||
const sourceSnapshots: ElementSnapshot[] = [];
|
||||
sourceElementsRef.current.forEach((data, id) => {
|
||||
if (sourceSnapshots.length >= MAX_MORPH_ELEMENTS) return;
|
||||
if (data.element.offsetParent !== null) { // Only capture visible elements
|
||||
sourceSnapshots.push(captureSnapshot(id, data.element, data.metadata));
|
||||
}
|
||||
});
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[WorkbenchTransition] Captured sources', sourceSnapshots.length);
|
||||
}
|
||||
|
||||
setTransitionState({
|
||||
isTransitioning: true,
|
||||
fromWorkbench: from,
|
||||
toWorkbench: to,
|
||||
sourceSnapshots,
|
||||
targetSnapshots: [],
|
||||
});
|
||||
|
||||
// Call the view change callback to mount the new view
|
||||
onViewChange?.();
|
||||
|
||||
// Give the new view a tick to mount before we look for targets
|
||||
await waitForNextPaint();
|
||||
|
||||
// Helper to scan DOM as a fallback in case targets haven't registered yet
|
||||
const scanForTargets = () => {
|
||||
let added = 0;
|
||||
const elements = document.querySelectorAll('[data-morph-id]');
|
||||
elements.forEach((el) => {
|
||||
const htmlEl = el as HTMLElement;
|
||||
const morphId = htmlEl.dataset.morphId;
|
||||
const fileId = htmlEl.dataset.morphFileId;
|
||||
const pageNumber = htmlEl.dataset.morphPageNumber;
|
||||
const type = htmlEl.dataset.morphType;
|
||||
|
||||
if (morphId && fileId) {
|
||||
const metadata: Record<string, any> = { fileId, type };
|
||||
if (pageNumber) {
|
||||
metadata.pageNumber = parseInt(pageNumber);
|
||||
}
|
||||
|
||||
// Preserve any explicit registration, otherwise add from scan
|
||||
if (!targetElementsRef.current.has(morphId)) {
|
||||
targetElementsRef.current.set(morphId, { element: htmlEl, metadata });
|
||||
added++;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[WorkbenchTransition] DOM scan found', elements.length, 'morphables; added', added);
|
||||
}
|
||||
};
|
||||
|
||||
// Wait for target registrations coming from useMorphElement (and fall back to DOM scan)
|
||||
const startTime = performance.now();
|
||||
const maxWaitMs = 1200; // shorter wait so animation can start quicker
|
||||
while (performance.now() - startTime < maxWaitMs) {
|
||||
if (targetElementsRef.current.size > 0) break;
|
||||
scanForTargets();
|
||||
await waitForNextPaint();
|
||||
}
|
||||
|
||||
// If we are transitioning to pageEditor, prefer to wait for page targets
|
||||
if (to === 'pageEditor') {
|
||||
const typeWaitStart = performance.now();
|
||||
const typeWaitMs = 400; // brief grace period to pick up page targets
|
||||
while (!hasTargetsOfType('page') && performance.now() - typeWaitStart < typeWaitMs) {
|
||||
scanForTargets();
|
||||
await waitForNextPaint();
|
||||
}
|
||||
}
|
||||
|
||||
// If we are transitioning to fileEditor, prefer to wait for file targets
|
||||
if (to === 'fileEditor') {
|
||||
const typeWaitStart = performance.now();
|
||||
const typeWaitMs = 400; // brief grace period to pick up file targets
|
||||
while (!hasTargetsOfType('file') && performance.now() - typeWaitStart < typeWaitMs) {
|
||||
scanForTargets();
|
||||
await waitForNextPaint();
|
||||
}
|
||||
}
|
||||
|
||||
// If we are transitioning to viewer, also wait briefly for file targets (viewer anchor)
|
||||
if (to === 'viewer') {
|
||||
const typeWaitStart = performance.now();
|
||||
const typeWaitMs = 400;
|
||||
while (!hasTargetsOfType('file') && performance.now() - typeWaitStart < typeWaitMs) {
|
||||
scanForTargets();
|
||||
await waitForNextPaint();
|
||||
}
|
||||
}
|
||||
|
||||
// One final scan after wait to pick up any late mounts
|
||||
scanForTargets();
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[WorkbenchTransition] Targets registered after wait:', targetElementsRef.current.size);
|
||||
}
|
||||
|
||||
// Give targets one more paint so layout stabilizes before measuring
|
||||
await waitForNextPaint();
|
||||
|
||||
// Allow layout to settle so we capture accurate positions
|
||||
await waitForNextPaint();
|
||||
|
||||
// Capture target snapshots
|
||||
console.log('[WorkbenchTransition] Capturing targets. Found:', targetElementsRef.current.size);
|
||||
const targetSnapshots: ElementSnapshot[] = [];
|
||||
targetElementsRef.current.forEach((data, id) => {
|
||||
if (targetSnapshots.length >= MAX_MORPH_ELEMENTS) return;
|
||||
if (data.element.offsetParent !== null) {
|
||||
targetSnapshots.push(captureSnapshot(id, data.element, data.metadata));
|
||||
}
|
||||
});
|
||||
|
||||
// If nothing was visible, fall back to first few elements regardless of viewport
|
||||
if (targetSnapshots.length === 0 && targetElementsRef.current.size > 0) {
|
||||
let count = 0;
|
||||
targetElementsRef.current.forEach((data, id) => {
|
||||
if (count >= Math.min(MAX_MORPH_ELEMENTS, 12)) return;
|
||||
const snap = captureSnapshot(id, data.element, data.metadata);
|
||||
targetSnapshots.push(snap);
|
||||
count++;
|
||||
});
|
||||
}
|
||||
console.log('[WorkbenchTransition] Captured', targetSnapshots.length, 'visible targets');
|
||||
|
||||
setTransitionState(prev => ({
|
||||
...prev,
|
||||
targetSnapshots,
|
||||
}));
|
||||
}, [captureSnapshot]);
|
||||
|
||||
const completeTransition = useCallback(() => {
|
||||
setTransitionState({
|
||||
isTransitioning: false,
|
||||
fromWorkbench: null,
|
||||
toWorkbench: null,
|
||||
sourceSnapshots: [],
|
||||
targetSnapshots: [],
|
||||
});
|
||||
|
||||
// Clear registrations
|
||||
sourceElementsRef.current.clear();
|
||||
targetElementsRef.current.clear();
|
||||
}, []);
|
||||
|
||||
const getMorphPairs = useCallback(() => {
|
||||
const pairs: Array<{ source: ElementSnapshot; target: ElementSnapshot }> = [];
|
||||
|
||||
// Group snapshots by fileId for split/merge animations
|
||||
const sourcesByFile = new Map<string, ElementSnapshot[]>();
|
||||
const targetsByFile = new Map<string, ElementSnapshot[]>();
|
||||
|
||||
// Group sources by fileId
|
||||
transitionState.sourceSnapshots.forEach(source => {
|
||||
const fileId = source.metadata?.fileId;
|
||||
if (fileId) {
|
||||
if (!sourcesByFile.has(fileId)) {
|
||||
sourcesByFile.set(fileId, []);
|
||||
}
|
||||
sourcesByFile.get(fileId)!.push(source);
|
||||
}
|
||||
});
|
||||
|
||||
// Group targets by fileId
|
||||
transitionState.targetSnapshots.forEach(target => {
|
||||
const fileId = target.metadata?.fileId;
|
||||
if (fileId) {
|
||||
if (!targetsByFile.has(fileId)) {
|
||||
targetsByFile.set(fileId, []);
|
||||
}
|
||||
targetsByFile.get(fileId)!.push(target);
|
||||
}
|
||||
});
|
||||
|
||||
// Create morph pairs for each file group
|
||||
const allFileIds = new Set([...sourcesByFile.keys(), ...targetsByFile.keys()]);
|
||||
|
||||
allFileIds.forEach(fileId => {
|
||||
const sources = sourcesByFile.get(fileId) || [];
|
||||
const targets = targetsByFile.get(fileId) || [];
|
||||
|
||||
if (sources.length === 0 || targets.length === 0) return;
|
||||
|
||||
// Sort targets by page number for consistent animation
|
||||
targets.sort((a, b) => (a.metadata?.pageNumber || 0) - (b.metadata?.pageNumber || 0));
|
||||
|
||||
if (sources.length === 1 && targets.length > 1) {
|
||||
// SPLIT: 1 file card → N page thumbnails
|
||||
// All targets morph from the same source (file card)
|
||||
const source = sources[0];
|
||||
targets.forEach(target => {
|
||||
pairs.push({ source, target });
|
||||
});
|
||||
} else if (sources.length > 1 && targets.length === 1) {
|
||||
// MERGE: N page thumbnails → 1 file card
|
||||
// All sources morph to the same target (file card)
|
||||
const target = targets[0];
|
||||
sources.forEach(source => {
|
||||
pairs.push({ source, target });
|
||||
});
|
||||
} else if (sources.length === targets.length) {
|
||||
// 1:1 mapping (e.g., page editor to page editor, or same view)
|
||||
sources.sort((a, b) => (a.metadata?.pageNumber || 0) - (b.metadata?.pageNumber || 0));
|
||||
sources.forEach((source, i) => {
|
||||
pairs.push({ source, target: targets[i] });
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return pairs;
|
||||
}, [transitionState.sourceSnapshots, transitionState.targetSnapshots]);
|
||||
|
||||
const value: WorkbenchTransitionContextValue = {
|
||||
transitionState,
|
||||
registerSourceElement,
|
||||
registerTargetElement,
|
||||
startTransition,
|
||||
completeTransition,
|
||||
getMorphPairs,
|
||||
};
|
||||
|
||||
return (
|
||||
<WorkbenchTransitionContext.Provider value={value}>
|
||||
{children}
|
||||
</WorkbenchTransitionContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
ProcessedFileMetadata,
|
||||
} from '@app/types/fileContext';
|
||||
import { FileId, ToolOperation } from '@app/types/file';
|
||||
import { generateThumbnailWithMetadata, generateThumbnailForFile } from '@app/utils/thumbnailUtils';
|
||||
import { generateThumbnailWithMetadata } from '@app/utils/thumbnailUtils';
|
||||
import { FileLifecycleManager } from '@app/contexts/file/lifecycle';
|
||||
import { buildQuickKeySet } from '@app/contexts/file/fileSelectors';
|
||||
import { StirlingFile } from '@app/types/fileContext';
|
||||
@@ -296,6 +296,7 @@ export async function addFiles(
|
||||
// Non-PDF files: simple thumbnail generation, no processedFile metadata
|
||||
try {
|
||||
if (DEBUG) console.log(`📄 Generating simple thumbnail for non-PDF file ${file.name}`);
|
||||
const { generateThumbnailForFile } = await import('@app/utils/thumbnailUtils');
|
||||
thumbnail = await generateThumbnailForFile(file);
|
||||
if (DEBUG) console.log(`📄 Generated simple thumbnail for ${file.name}: no page count, thumbnail: SUCCESS`);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import { useMemo, lazy } from "react";
|
||||
import { useMemo } from "react";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { devApiLink } from "@app/constants/links";
|
||||
import SplitPdfPanel from "@app/tools/Split";
|
||||
import CompressPdfPanel from "@app/tools/Compress";
|
||||
import OCRPanel from "@app/tools/OCR";
|
||||
import ConvertPanel from "@app/tools/Convert";
|
||||
import Sanitize from "@app/tools/Sanitize";
|
||||
import AddPassword from "@app/tools/AddPassword";
|
||||
import ChangePermissions from "@app/tools/ChangePermissions";
|
||||
import RemoveBlanks from "@app/tools/RemoveBlanks";
|
||||
import RemovePages from "@app/tools/RemovePages";
|
||||
import ReorganizePages from "@app/tools/ReorganizePages";
|
||||
import { reorganizePagesOperationConfig } from "@app/hooks/tools/reorganizePages/useReorganizePagesOperation";
|
||||
import RemovePassword from "@app/tools/RemovePassword";
|
||||
import {
|
||||
SubcategoryId,
|
||||
ToolCategoryId,
|
||||
@@ -12,9 +23,35 @@ import {
|
||||
LinkToolRegistry,
|
||||
} from "@app/data/toolsTaxonomy";
|
||||
import { isSuperToolId, isLinkToolId } from '@app/types/toolId';
|
||||
import AdjustContrast from "@app/tools/AdjustContrast";
|
||||
import AdjustContrastSingleStepSettings from "@app/components/tools/adjustContrast/AdjustContrastSingleStepSettings";
|
||||
import { adjustContrastOperationConfig } from "@app/hooks/tools/adjustContrast/useAdjustContrastOperation";
|
||||
import { getSynonyms } from "@app/utils/toolSynonyms";
|
||||
import { useProprietaryToolRegistry } from "@app/data/useProprietaryToolRegistry";
|
||||
import GetPdfInfo from "@app/tools/GetPdfInfo";
|
||||
import AddWatermark from "@app/tools/AddWatermark";
|
||||
import AddStamp from "@app/tools/AddStamp";
|
||||
import AddAttachments from "@app/tools/AddAttachments";
|
||||
import Merge from '@app/tools/Merge';
|
||||
import EditTableOfContents from '@app/tools/EditTableOfContents';
|
||||
import Repair from "@app/tools/Repair";
|
||||
import AutoRename from "@app/tools/AutoRename";
|
||||
import SingleLargePage from "@app/tools/SingleLargePage";
|
||||
import PageLayout from "@app/tools/PageLayout";
|
||||
import UnlockPdfForms from "@app/tools/UnlockPdfForms";
|
||||
import RemoveCertificateSign from "@app/tools/RemoveCertificateSign";
|
||||
import RemoveImage from "@app/tools/RemoveImage";
|
||||
import CertSign from "@app/tools/CertSign";
|
||||
import BookletImposition from "@app/tools/BookletImposition";
|
||||
import Flatten from "@app/tools/Flatten";
|
||||
import Rotate from "@app/tools/Rotate";
|
||||
import PdfTextEditor from "@app/tools/pdfTextEditor/PdfTextEditor";
|
||||
import ChangeMetadata from "@app/tools/ChangeMetadata";
|
||||
import Crop from "@app/tools/Crop";
|
||||
import Sign from "@app/tools/Sign";
|
||||
import AddText from "@app/tools/AddText";
|
||||
import AddImage from "@app/tools/AddImage";
|
||||
import Annotate from "@app/tools/Annotate";
|
||||
import { compressOperationConfig } from "@app/hooks/tools/compress/useCompressOperation";
|
||||
import { splitOperationConfig } from "@app/hooks/tools/split/useSplitOperation";
|
||||
import { addPasswordOperationConfig } from "@app/hooks/tools/addPassword/useAddPasswordOperation";
|
||||
@@ -52,7 +89,50 @@ import { scannerImageSplitOperationConfig } from "@app/hooks/tools/scannerImageS
|
||||
import { addPageNumbersOperationConfig } from "@app/components/tools/addPageNumbers/useAddPageNumbersOperation";
|
||||
import { extractPagesOperationConfig } from "@app/hooks/tools/extractPages/useExtractPagesOperation";
|
||||
import { ENDPOINTS as SPLIT_ENDPOINT_NAMES } from '@app/constants/splitConstants';
|
||||
import CompressSettings from "@app/components/tools/compress/CompressSettings";
|
||||
import AddPasswordSettings from "@app/components/tools/addPassword/AddPasswordSettings";
|
||||
import RemovePasswordSettings from "@app/components/tools/removePassword/RemovePasswordSettings";
|
||||
import SanitizeSettings from "@app/components/tools/sanitize/SanitizeSettings";
|
||||
import AddWatermarkSingleStepSettings from "@app/components/tools/addWatermark/AddWatermarkSingleStepSettings";
|
||||
import OCRSettings from "@app/components/tools/ocr/OCRSettings";
|
||||
import ConvertSettings from "@app/components/tools/convert/ConvertSettings";
|
||||
import ChangePermissionsSettings from "@app/components/tools/changePermissions/ChangePermissionsSettings";
|
||||
import BookletImpositionSettings from "@app/components/tools/bookletImposition/BookletImpositionSettings";
|
||||
import FlattenSettings from "@app/components/tools/flatten/FlattenSettings";
|
||||
import RedactSingleStepSettings from "@app/components/tools/redact/RedactSingleStepSettings";
|
||||
import Redact from "@app/tools/Redact";
|
||||
import AdjustPageScale from "@app/tools/AdjustPageScale";
|
||||
import ReplaceColor from "@app/tools/ReplaceColor";
|
||||
import ScannerImageSplit from "@app/tools/ScannerImageSplit";
|
||||
import OverlayPdfs from "@app/tools/OverlayPdfs";
|
||||
import { ToolId } from "@app/types/toolId";
|
||||
import MergeSettings from '@app/components/tools/merge/MergeSettings';
|
||||
import AdjustPageScaleSettings from "@app/components/tools/adjustPageScale/AdjustPageScaleSettings";
|
||||
import ScannerImageSplitSettings from "@app/components/tools/scannerImageSplit/ScannerImageSplitSettings";
|
||||
import ChangeMetadataSingleStep from "@app/components/tools/changeMetadata/ChangeMetadataSingleStep";
|
||||
import SignSettings from "@app/components/tools/sign/SignSettings";
|
||||
import AddPageNumbers from "@app/tools/AddPageNumbers";
|
||||
import RemoveAnnotations from "@app/tools/RemoveAnnotations";
|
||||
import PageLayoutSettings from "@app/components/tools/pageLayout/PageLayoutSettings";
|
||||
import ExtractImages from "@app/tools/ExtractImages";
|
||||
import ExtractPages from "@app/tools/ExtractPages";
|
||||
import ExtractImagesSettings from "@app/components/tools/extractImages/ExtractImagesSettings";
|
||||
import ExtractPagesSettings from "@app/components/tools/extractPages/ExtractPagesSettings";
|
||||
import ReplaceColorSettings from "@app/components/tools/replaceColor/ReplaceColorSettings";
|
||||
import AddStampAutomationSettings from "@app/components/tools/addStamp/AddStampAutomationSettings";
|
||||
import CertSignAutomationSettings from "@app/components/tools/certSign/CertSignAutomationSettings";
|
||||
import CropAutomationSettings from "@app/components/tools/crop/CropAutomationSettings";
|
||||
import RotateAutomationSettings from "@app/components/tools/rotate/RotateAutomationSettings";
|
||||
import SplitAutomationSettings from "@app/components/tools/split/SplitAutomationSettings";
|
||||
import AddAttachmentsSettings from "@app/components/tools/addAttachments/AddAttachmentsSettings";
|
||||
import RemovePagesSettings from "@app/components/tools/removePages/RemovePagesSettings";
|
||||
import RemoveBlanksSettings from "@app/components/tools/removeBlanks/RemoveBlanksSettings";
|
||||
import AddPageNumbersAutomationSettings from "@app/components/tools/addPageNumbers/AddPageNumbersAutomationSettings";
|
||||
import OverlayPdfsSettings from "@app/components/tools/overlayPdfs/OverlayPdfsSettings";
|
||||
import ValidateSignature from "@app/tools/ValidateSignature";
|
||||
import ShowJS from "@app/tools/ShowJS";
|
||||
import Automate from "@app/tools/Automate";
|
||||
import Compare from "@app/tools/Compare";
|
||||
import { CONVERT_SUPPORTED_FORMATS } from "@app/constants/convertSupportedFornats";
|
||||
|
||||
|
||||
@@ -77,7 +157,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
pdfTextEditor: {
|
||||
icon: <LocalIcon icon="edit-square-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.pdfTextEditor.title", "PDF Text Editor"),
|
||||
component: lazy(() => import("@app/tools/pdfTextEditor/PdfTextEditor")),
|
||||
component: PdfTextEditor,
|
||||
description: t(
|
||||
"home.pdfTextEditor.desc",
|
||||
"Review and edit text and images in PDFs with grouped text editing and PDF regeneration"
|
||||
@@ -107,21 +187,21 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
merge: {
|
||||
icon: <LocalIcon icon="library-add-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.merge.title", "Merge"),
|
||||
component: lazy(() => import("@app/tools/Merge")),
|
||||
component: Merge,
|
||||
description: t("home.merge.desc", "Merge multiple PDFs into a single document"),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
maxFiles: -1,
|
||||
endpoints: ["merge-pdfs"],
|
||||
operationConfig: mergeOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/merge/MergeSettings")),
|
||||
automationSettings: MergeSettings,
|
||||
synonyms: getSynonyms(t, "merge")
|
||||
},
|
||||
// Signing
|
||||
certSign: {
|
||||
icon: <LocalIcon icon="workspace-premium-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.certSign.title", "Certificate Sign"),
|
||||
component: lazy(() => import("@app/tools/CertSign")),
|
||||
component: CertSign,
|
||||
description: t("home.certSign.desc", "Sign PDF documents using digital certificates"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.SIGNING,
|
||||
@@ -129,24 +209,24 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
maxFiles: -1,
|
||||
endpoints: ["cert-sign"],
|
||||
operationConfig: certSignOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/certSign/CertSignAutomationSettings")),
|
||||
automationSettings: CertSignAutomationSettings,
|
||||
},
|
||||
sign: {
|
||||
icon: <LocalIcon icon="signature-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.sign.title", "Sign"),
|
||||
component: lazy(() => import("@app/tools/Sign")),
|
||||
component: Sign,
|
||||
description: t("home.sign.desc", "Adds signature to PDF by drawing, text or image"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.SIGNING,
|
||||
operationConfig: signOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/sign/SignSettings")), // TODO:: not all settings shown, suggested next tools shown
|
||||
automationSettings: SignSettings, // TODO:: not all settings shown, suggested next tools shown
|
||||
synonyms: getSynonyms(t, "sign"),
|
||||
supportsAutomate: false, //TODO make support Sign
|
||||
},
|
||||
addText: {
|
||||
icon: <LocalIcon icon="text-fields-rounded" width="1.5rem" height="1.5rem" />,
|
||||
icon: <LocalIcon icon="material-symbols:text-fields-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t('home.addText.title', 'Add Text'),
|
||||
component: lazy(() => import("@app/tools/AddText")),
|
||||
component: AddText,
|
||||
description: t('home.addText.desc', 'Add custom text anywhere in your PDF'),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
@@ -158,7 +238,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
addImage: {
|
||||
icon: <LocalIcon icon="image-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t('home.addImage.title', 'Add Image'),
|
||||
component: lazy(() => import("@app/tools/AddImage")),
|
||||
component: AddImage,
|
||||
description: t('home.addImage.desc', 'Add images anywhere in your PDF'),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
@@ -167,39 +247,52 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
synonyms: getSynonyms(t, 'addImage'),
|
||||
supportsAutomate: false,
|
||||
},
|
||||
annotate: {
|
||||
icon: <LocalIcon icon="edit" width="1.5rem" height="1.5rem" />,
|
||||
name: t('home.annotate.title', 'Annotate'),
|
||||
component: Annotate,
|
||||
description: t('home.annotate.desc', 'Highlight, draw, add notes, and shapes directly in the viewer'),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
workbench: 'viewer',
|
||||
operationConfig: signOperationConfig,
|
||||
automationSettings: null,
|
||||
synonyms: getSynonyms(t, 'annotate'),
|
||||
supportsAutomate: false,
|
||||
},
|
||||
|
||||
// Document Security
|
||||
|
||||
addPassword: {
|
||||
icon: <LocalIcon icon="password-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.addPassword.title", "Add Password"),
|
||||
component: lazy(() => import("@app/tools/AddPassword")),
|
||||
component: AddPassword,
|
||||
description: t("home.addPassword.desc", "Add password protection and restrictions to PDF files"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
maxFiles: -1,
|
||||
endpoints: ["add-password"],
|
||||
operationConfig: addPasswordOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/addPassword/AddPasswordSettings")),
|
||||
automationSettings: AddPasswordSettings,
|
||||
synonyms: getSynonyms(t, "addPassword")
|
||||
},
|
||||
watermark: {
|
||||
icon: <LocalIcon icon="branding-watermark-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.watermark.title", "Add Watermark"),
|
||||
component: lazy(() => import("@app/tools/AddWatermark")),
|
||||
component: AddWatermark,
|
||||
maxFiles: -1,
|
||||
description: t("home.watermark.desc", "Add a custom watermark to your PDF document."),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
endpoints: ["add-watermark"],
|
||||
operationConfig: addWatermarkOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/addWatermark/AddWatermarkSingleStepSettings")),
|
||||
automationSettings: AddWatermarkSingleStepSettings,
|
||||
synonyms: getSynonyms(t, "watermark")
|
||||
},
|
||||
addStamp: {
|
||||
icon: <LocalIcon icon="approval-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.addStamp.title", "Add Stamp to PDF"),
|
||||
component: lazy(() => import("@app/tools/AddStamp")),
|
||||
component: AddStamp,
|
||||
description: t("home.addStamp.desc", "Add text or add image stamps at set locations"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
@@ -207,38 +300,38 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
maxFiles: -1,
|
||||
endpoints: ["add-stamp"],
|
||||
operationConfig: addStampOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/addStamp/AddStampAutomationSettings")),
|
||||
automationSettings: AddStampAutomationSettings,
|
||||
},
|
||||
sanitize: {
|
||||
icon: <LocalIcon icon="cleaning-services-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.sanitize.title", "Sanitize"),
|
||||
component: lazy(() => import("@app/tools/Sanitize")),
|
||||
component: Sanitize,
|
||||
maxFiles: -1,
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
description: t("home.sanitize.desc", "Remove potentially harmful elements from PDF files"),
|
||||
endpoints: ["sanitize-pdf"],
|
||||
operationConfig: sanitizeOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/sanitize/SanitizeSettings")),
|
||||
automationSettings: SanitizeSettings,
|
||||
synonyms: getSynonyms(t, "sanitize")
|
||||
},
|
||||
flatten: {
|
||||
icon: <LocalIcon icon="layers-clear-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.flatten.title", "Flatten"),
|
||||
component: lazy(() => import("@app/tools/Flatten")),
|
||||
component: Flatten,
|
||||
description: t("home.flatten.desc", "Remove all interactive elements and forms from a PDF"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
maxFiles: -1,
|
||||
endpoints: ["flatten"],
|
||||
operationConfig: flattenOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/flatten/FlattenSettings")),
|
||||
automationSettings: FlattenSettings,
|
||||
synonyms: getSynonyms(t, "flatten")
|
||||
},
|
||||
unlockPDFForms: {
|
||||
icon: <LocalIcon icon="preview-off-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.unlockPDFForms.title", "Unlock PDF Forms"),
|
||||
component: lazy(() => import("@app/tools/UnlockPdfForms")),
|
||||
component: UnlockPdfForms,
|
||||
description: t("home.unlockPDFForms.desc", "Remove read-only property of form fields in a PDF document."),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
@@ -251,20 +344,20 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
changePermissions: {
|
||||
icon: <LocalIcon icon="lock-outline" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.changePermissions.title", "Change Permissions"),
|
||||
component: lazy(() => import("@app/tools/ChangePermissions")),
|
||||
component: ChangePermissions,
|
||||
description: t("home.changePermissions.desc", "Change document restrictions and permissions"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
maxFiles: -1,
|
||||
endpoints: ["add-password"],
|
||||
operationConfig: changePermissionsOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/changePermissions/ChangePermissionsSettings")),
|
||||
automationSettings: ChangePermissionsSettings,
|
||||
synonyms: getSynonyms(t, "changePermissions"),
|
||||
},
|
||||
getPdfInfo: {
|
||||
icon: <LocalIcon icon="fact-check-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.getPdfInfo.title", "Get ALL Info on PDF"),
|
||||
component: lazy(() => import("@app/tools/GetPdfInfo")),
|
||||
component: GetPdfInfo,
|
||||
description: t("home.getPdfInfo.desc", "Grabs any and all information possible on PDFs"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.VERIFICATION,
|
||||
@@ -277,7 +370,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
validateSignature: {
|
||||
icon: <LocalIcon icon="verified-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.validateSignature.title", "Validate PDF Signature"),
|
||||
component: lazy(() => import("@app/tools/ValidateSignature")),
|
||||
component: ValidateSignature,
|
||||
description: t("home.validateSignature.desc", "Verify digital signatures and certificates in PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.VERIFICATION,
|
||||
@@ -307,20 +400,20 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
changeMetadata: {
|
||||
icon: <LocalIcon icon="assignment-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.changeMetadata.title", "Change Metadata"),
|
||||
component: lazy(() => import("@app/tools/ChangeMetadata")),
|
||||
component: ChangeMetadata,
|
||||
description: t("home.changeMetadata.desc", "Change/Remove/Add metadata from a PDF document"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_REVIEW,
|
||||
maxFiles: -1,
|
||||
endpoints: ["update-metadata"],
|
||||
operationConfig: changeMetadataOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/changeMetadata/ChangeMetadataSingleStep")),
|
||||
automationSettings: ChangeMetadataSingleStep,
|
||||
synonyms: getSynonyms(t, "changeMetadata")
|
||||
},
|
||||
editTableOfContents: {
|
||||
icon: <LocalIcon icon="toc-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.editTableOfContents.title", "Edit Table of Contents"),
|
||||
component: lazy(() => import("@app/tools/EditTableOfContents")),
|
||||
component: EditTableOfContents,
|
||||
description: t(
|
||||
"home.editTableOfContents.desc",
|
||||
"Add or edit bookmarks and table of contents in PDF documents"
|
||||
@@ -339,44 +432,44 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
crop: {
|
||||
icon: <LocalIcon icon="crop-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.crop.title", "Crop PDF"),
|
||||
component: lazy(() => import("@app/tools/Crop")),
|
||||
component: Crop,
|
||||
description: t("home.crop.desc", "Crop a PDF to reduce its size (maintains text!)"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["crop"],
|
||||
operationConfig: cropOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/crop/CropAutomationSettings")),
|
||||
automationSettings: CropAutomationSettings,
|
||||
},
|
||||
rotate: {
|
||||
icon: <LocalIcon icon="rotate-right-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.rotate.title", "Rotate"),
|
||||
component: lazy(() => import("@app/tools/Rotate")),
|
||||
component: Rotate,
|
||||
description: t("home.rotate.desc", "Easily rotate your PDFs."),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["rotate-pdf"],
|
||||
operationConfig: rotateOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/rotate/RotateAutomationSettings")),
|
||||
automationSettings: RotateAutomationSettings,
|
||||
synonyms: getSynonyms(t, "rotate")
|
||||
},
|
||||
split: {
|
||||
icon: <LocalIcon icon="content-cut-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.split.title", "Split"),
|
||||
component: lazy(() => import("@app/tools/Split")),
|
||||
component: SplitPdfPanel,
|
||||
description: t("home.split.desc", "Split PDFs into multiple documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
endpoints: Array.from(new Set(Object.values(SPLIT_ENDPOINT_NAMES))),
|
||||
operationConfig: splitOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/split/SplitAutomationSettings")),
|
||||
automationSettings: SplitAutomationSettings,
|
||||
synonyms: getSynonyms(t, "split")
|
||||
},
|
||||
reorganizePages: {
|
||||
icon: <LocalIcon icon="move-down-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.reorganizePages.title", "Reorganize Pages"),
|
||||
component: lazy(() => import("@app/tools/ReorganizePages")),
|
||||
component: ReorganizePages,
|
||||
description: t(
|
||||
"home.reorganizePages.desc",
|
||||
"Rearrange, duplicate, or delete PDF pages with visual drag-and-drop control."
|
||||
@@ -392,24 +485,24 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
scalePages: {
|
||||
icon: <LocalIcon icon="crop-free-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.scalePages.title", "Adjust page size/scale"),
|
||||
component: lazy(() => import("@app/tools/AdjustPageScale")),
|
||||
component: AdjustPageScale,
|
||||
description: t("home.scalePages.desc", "Change the size/scale of a page and/or its contents."),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["scale-pages"],
|
||||
operationConfig: adjustPageScaleOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/adjustPageScale/AdjustPageScaleSettings")),
|
||||
automationSettings: AdjustPageScaleSettings,
|
||||
synonyms: getSynonyms(t, "scalePages")
|
||||
},
|
||||
addPageNumbers: {
|
||||
icon: <LocalIcon icon="123-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.addPageNumbers.title", "Add Page Numbers"),
|
||||
component: lazy(() => import("@app/tools/AddPageNumbers")),
|
||||
component: AddPageNumbers,
|
||||
description: t("home.addPageNumbers.desc", "Add Page numbers throughout a document in a set location"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
automationSettings: lazy(() => import("@app/components/tools/addPageNumbers/AddPageNumbersAutomationSettings")),
|
||||
automationSettings: AddPageNumbersAutomationSettings,
|
||||
maxFiles: -1,
|
||||
endpoints: ["add-page-numbers"],
|
||||
operationConfig: addPageNumbersOperationConfig,
|
||||
@@ -418,21 +511,21 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
pageLayout: {
|
||||
icon: <LocalIcon icon="dashboard-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.pageLayout.title", "Multi-Page Layout"),
|
||||
component: lazy(() => import("@app/tools/PageLayout")),
|
||||
component: PageLayout,
|
||||
description: t("home.pageLayout.desc", "Merge multiple pages of a PDF document into a single page"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["multi-page-layout"],
|
||||
automationSettings: lazy(() => import("@app/components/tools/pageLayout/PageLayoutSettings")),
|
||||
automationSettings: PageLayoutSettings,
|
||||
synonyms: getSynonyms(t, "pageLayout")
|
||||
},
|
||||
bookletImposition: {
|
||||
icon: <LocalIcon icon="menu-book-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.bookletImposition.title", "Booklet Imposition"),
|
||||
component: lazy(() => import("@app/tools/BookletImposition")),
|
||||
component: BookletImposition,
|
||||
operationConfig: bookletImpositionOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/bookletImposition/BookletImpositionSettings")),
|
||||
automationSettings: BookletImpositionSettings,
|
||||
description: t("home.bookletImposition.desc", "Create booklets with proper page ordering and multi-page layout for printing and binding"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
@@ -442,7 +535,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
|
||||
icon: <LocalIcon icon="looks-one-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.pdfToSinglePage.title", "PDF to Single Large Page"),
|
||||
component: lazy(() => import("@app/tools/SingleLargePage")),
|
||||
component: SingleLargePage,
|
||||
|
||||
description: t("home.pdfToSinglePage.desc", "Merges all PDF pages into one large single page"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
@@ -456,7 +549,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
addAttachments: {
|
||||
icon: <LocalIcon icon="attachment-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.addAttachments.title", "Add Attachments"),
|
||||
component: lazy(() => import("@app/tools/AddAttachments")),
|
||||
component: AddAttachments,
|
||||
description: t("home.addAttachments.desc", "Add or remove embedded files (attachments) to/from a PDF"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.PAGE_FORMATTING,
|
||||
@@ -464,7 +557,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
maxFiles: 1,
|
||||
endpoints: ["add-attachments"],
|
||||
operationConfig: addAttachmentsOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/addAttachments/AddAttachmentsSettings")),
|
||||
automationSettings: AddAttachmentsSettings,
|
||||
},
|
||||
|
||||
// Extraction
|
||||
@@ -472,26 +565,26 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
extractPages: {
|
||||
icon: <LocalIcon icon="upload-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.extractPages.title", "Extract Pages"),
|
||||
component: lazy(() => import("@app/tools/ExtractPages")),
|
||||
component: ExtractPages,
|
||||
description: t("home.extractPages.desc", "Extract specific pages from a PDF document"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.EXTRACTION,
|
||||
synonyms: getSynonyms(t, "extractPages"),
|
||||
automationSettings: lazy(() => import("@app/components/tools/extractPages/ExtractPagesSettings")),
|
||||
automationSettings: ExtractPagesSettings,
|
||||
operationConfig: extractPagesOperationConfig,
|
||||
endpoints: ["rearrange-pages"],
|
||||
},
|
||||
extractImages: {
|
||||
icon: <LocalIcon icon="photo-library-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.extractImages.title", "Extract Images"),
|
||||
component: lazy(() => import("@app/tools/ExtractImages")),
|
||||
component: ExtractImages,
|
||||
description: t("home.extractImages.desc", "Extract images from PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.EXTRACTION,
|
||||
maxFiles: -1,
|
||||
endpoints: ["extract-images"],
|
||||
operationConfig: extractImagesOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/extractImages/ExtractImagesSettings")),
|
||||
automationSettings: ExtractImagesSettings,
|
||||
synonyms: getSynonyms(t, "extractImages")
|
||||
},
|
||||
|
||||
@@ -500,7 +593,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
removePages: {
|
||||
icon: <LocalIcon icon="delete-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removePages.title", "Remove Pages"),
|
||||
component: lazy(() => import("@app/tools/RemovePages")),
|
||||
component: RemovePages,
|
||||
description: t("home.removePages.desc", "Remove specific pages from a PDF document"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
@@ -508,12 +601,12 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
endpoints: ["remove-pages"],
|
||||
synonyms: getSynonyms(t, "removePages"),
|
||||
operationConfig: removePagesOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/removePages/RemovePagesSettings")),
|
||||
automationSettings: RemovePagesSettings,
|
||||
},
|
||||
removeBlanks: {
|
||||
icon: <LocalIcon icon="scan-delete-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removeBlanks.title", "Remove Blank Pages"),
|
||||
component: lazy(() => import("@app/tools/RemoveBlanks")),
|
||||
component: RemoveBlanks,
|
||||
description: t("home.removeBlanks.desc", "Remove blank pages from PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
@@ -521,12 +614,12 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
endpoints: ["remove-blanks"],
|
||||
synonyms: getSynonyms(t, "removeBlanks"),
|
||||
operationConfig: removeBlanksOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/removeBlanks/RemoveBlanksSettings")),
|
||||
automationSettings: RemoveBlanksSettings,
|
||||
},
|
||||
removeAnnotations: {
|
||||
icon: <LocalIcon icon="thread-unread-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removeAnnotations.title", "Remove Annotations"),
|
||||
component: lazy(() => import("@app/tools/RemoveAnnotations")),
|
||||
component: RemoveAnnotations,
|
||||
description: t("home.removeAnnotations.desc", "Remove annotations and comments from PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
@@ -539,7 +632,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
removeImage: {
|
||||
icon: <LocalIcon icon="remove-selection-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removeImage.title", "Remove Images"),
|
||||
component: lazy(() => import("@app/tools/RemoveImage")),
|
||||
component: RemoveImage,
|
||||
description: t("home.removeImage.desc", "Remove all images from a PDF document"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
@@ -552,20 +645,20 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
removePassword: {
|
||||
icon: <LocalIcon icon="lock-open-right-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removePassword.title", "Remove Password"),
|
||||
component: lazy(() => import("@app/tools/RemovePassword")),
|
||||
component: RemovePassword,
|
||||
description: t("home.removePassword.desc", "Remove password protection from PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
endpoints: ["remove-password"],
|
||||
maxFiles: -1,
|
||||
operationConfig: removePasswordOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/removePassword/RemovePasswordSettings")),
|
||||
automationSettings: RemovePasswordSettings,
|
||||
synonyms: getSynonyms(t, "removePassword")
|
||||
},
|
||||
removeCertSign: {
|
||||
icon: <LocalIcon icon="remove-moderator-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.removeCertSign.title", "Remove Certificate Sign"),
|
||||
component: lazy(() => import("@app/tools/RemoveCertificateSign")),
|
||||
component: RemoveCertificateSign,
|
||||
description: t("home.removeCertSign.desc", "Remove digital signature from PDF documents"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.REMOVAL,
|
||||
@@ -581,7 +674,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
automate: {
|
||||
icon: <LocalIcon icon="automation-outline" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.automate.title", "Automate"),
|
||||
component: lazy(() => import("@app/tools/Automate")),
|
||||
component: Automate,
|
||||
description: t(
|
||||
"home.automate.desc",
|
||||
"Build multi-step workflows by chaining together PDF actions. Ideal for recurring tasks."
|
||||
@@ -597,7 +690,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
autoRename: {
|
||||
icon: <LocalIcon icon="match-word-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.autoRename.title", "Auto Rename PDF File"),
|
||||
component: lazy(() => import("@app/tools/AutoRename")),
|
||||
component: AutoRename,
|
||||
maxFiles: -1,
|
||||
endpoints: ["auto-rename"],
|
||||
operationConfig: autoRenameOperationConfig,
|
||||
@@ -613,18 +706,18 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
adjustContrast: {
|
||||
icon: <LocalIcon icon="palette" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.adjustContrast.title", "Adjust Colors/Contrast"),
|
||||
component: lazy(() => import("@app/tools/AdjustContrast")),
|
||||
component: AdjustContrast,
|
||||
description: t("home.adjustContrast.desc", "Adjust colors and contrast of PDF documents"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
|
||||
operationConfig: adjustContrastOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/adjustContrast/AdjustContrastSingleStepSettings")),
|
||||
automationSettings: AdjustContrastSingleStepSettings,
|
||||
synonyms: getSynonyms(t, "adjustContrast"),
|
||||
},
|
||||
repair: {
|
||||
icon: <LocalIcon icon="build-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.repair.title", "Repair"),
|
||||
component: lazy(() => import("@app/tools/Repair")),
|
||||
component: Repair,
|
||||
description: t("home.repair.desc", "Repair corrupted or damaged PDF files"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
|
||||
@@ -637,39 +730,39 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
scannerImageSplit: {
|
||||
icon: <LocalIcon icon="scanner-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.scannerImageSplit.title", "Detect & Split Scanned Photos"),
|
||||
component: lazy(() => import("@app/tools/ScannerImageSplit")),
|
||||
component: ScannerImageSplit,
|
||||
description: t("home.scannerImageSplit.desc", "Detect and split scanned photos into separate pages"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["extract-image-scans"],
|
||||
operationConfig: scannerImageSplitOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/scannerImageSplit/ScannerImageSplitSettings")),
|
||||
automationSettings: ScannerImageSplitSettings,
|
||||
synonyms: getSynonyms(t, "ScannerImageSplit"),
|
||||
},
|
||||
overlayPdfs: {
|
||||
icon: <LocalIcon icon="layers-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.overlay-pdfs.title", "Overlay PDFs"),
|
||||
component: lazy(() => import("@app/tools/OverlayPdfs")),
|
||||
component: OverlayPdfs,
|
||||
description: t("home.overlay-pdfs.desc", "Overlay one PDF on top of another"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
|
||||
endpoints: ["overlay-pdf"],
|
||||
operationConfig: overlayPdfsOperationConfig,
|
||||
synonyms: getSynonyms(t, "overlay-pdfs"),
|
||||
automationSettings: lazy(() => import("@app/components/tools/overlayPdfs/OverlayPdfsSettings"))
|
||||
automationSettings: OverlayPdfsSettings
|
||||
},
|
||||
replaceColor: {
|
||||
icon: <LocalIcon icon="format-color-fill-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.replaceColor.title", "Replace & Invert Color"),
|
||||
component: lazy(() => import("@app/tools/ReplaceColor")),
|
||||
component: ReplaceColor,
|
||||
description: t("home.replaceColor.desc", "Replace or invert colors in PDF documents"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
|
||||
maxFiles: -1,
|
||||
endpoints: ["replace-invert-pdf"],
|
||||
operationConfig: replaceColorOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/replaceColor/ReplaceColorSettings")),
|
||||
automationSettings: ReplaceColorSettings,
|
||||
synonyms: getSynonyms(t, "replaceColor"),
|
||||
},
|
||||
scannerEffect: {
|
||||
@@ -689,7 +782,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
showJS: {
|
||||
icon: <LocalIcon icon="javascript-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.showJS.title", "Show JavaScript"),
|
||||
component: lazy(() => import("@app/tools/ShowJS")),
|
||||
component: ShowJS,
|
||||
description: t("home.showJS.desc", "Extract and display JavaScript code from PDF documents"),
|
||||
categoryId: ToolCategoryId.ADVANCED_TOOLS,
|
||||
subcategoryId: SubcategoryId.DEVELOPER_TOOLS,
|
||||
@@ -752,7 +845,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
compare: {
|
||||
icon: <LocalIcon icon="compare-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.compare.title", "Compare"),
|
||||
component: lazy(() => import("@app/tools/Compare")),
|
||||
component: Compare,
|
||||
description: t("home.compare.desc", "Compare two PDF documents and highlight differences"),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
@@ -765,20 +858,20 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
compress: {
|
||||
icon: <LocalIcon icon="zoom-in-map-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.compress.title", "Compress"),
|
||||
component: lazy(() => import("@app/tools/Compress")),
|
||||
component: CompressPdfPanel,
|
||||
description: t("home.compress.desc", "Compress PDFs to reduce their file size."),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
maxFiles: -1,
|
||||
endpoints: ["compress-pdf"],
|
||||
operationConfig: compressOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/compress/CompressSettings")),
|
||||
automationSettings: CompressSettings,
|
||||
synonyms: getSynonyms(t, "compress")
|
||||
},
|
||||
convert: {
|
||||
icon: <LocalIcon icon="sync-alt-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.convert.title", "Convert"),
|
||||
component: lazy(() => import("@app/tools/Convert")),
|
||||
component: ConvertPanel,
|
||||
description: t("home.convert.desc", "Convert files to and from PDF format"),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
@@ -802,34 +895,34 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
],
|
||||
|
||||
operationConfig: convertOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/convert/ConvertSettings")),
|
||||
automationSettings: ConvertSettings,
|
||||
synonyms: getSynonyms(t, "convert")
|
||||
},
|
||||
|
||||
ocr: {
|
||||
icon: <LocalIcon icon="quick-reference-all-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.ocr.title", "OCR"),
|
||||
component: lazy(() => import("@app/tools/OCR")),
|
||||
component: OCRPanel,
|
||||
description: t("home.ocr.desc", "Extract text from scanned PDFs using Optical Character Recognition"),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
maxFiles: -1,
|
||||
endpoints: ["ocr-pdf"],
|
||||
operationConfig: ocrOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/ocr/OCRSettings")),
|
||||
automationSettings: OCRSettings,
|
||||
synonyms: getSynonyms(t, "ocr")
|
||||
},
|
||||
redact: {
|
||||
icon: <LocalIcon icon="visibility-off-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.redact.title", "Redact"),
|
||||
component: lazy(() => import("@app/tools/Redact")),
|
||||
component: Redact,
|
||||
description: t("home.redact.desc", "Permanently remove sensitive information from PDF documents"),
|
||||
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
maxFiles: -1,
|
||||
endpoints: ["auto-redact"],
|
||||
operationConfig: redactOperationConfig,
|
||||
automationSettings: lazy(() => import("@app/components/tools/redact/RedactSingleStepSettings")),
|
||||
automationSettings: RedactSingleStepSettings,
|
||||
synonyms: getSynonyms(t, "redact")
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import JSZip from 'jszip';
|
||||
import { OCRParameters, defaultParameters } from '@app/hooks/tools/ocr/useOCRParameters';
|
||||
import { useToolOperation, ToolOperationConfig, ToolType } from '@app/hooks/tools/shared/useToolOperation';
|
||||
import { createStandardErrorHandler } from '@app/utils/toolErrorHandler';
|
||||
@@ -19,7 +18,8 @@ function getMimeType(filename: string): string {
|
||||
|
||||
// Lightweight ZIP extractor (keep or replace with a shared util if you have one)
|
||||
async function extractZipFile(zipBlob: Blob): Promise<File[]> {
|
||||
const zip = new JSZip();
|
||||
const JSZip = await import('jszip');
|
||||
const zip = new JSZip.default();
|
||||
const zipContent = await zip.loadAsync(await zipBlob.arrayBuffer());
|
||||
const out: File[] = [];
|
||||
for (const [filename, file] of Object.entries(zipContent.files)) {
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface SignParameters {
|
||||
fontFamily?: string;
|
||||
fontSize?: number;
|
||||
textColor?: string;
|
||||
textAlign?: 'left' | 'center' | 'right';
|
||||
}
|
||||
|
||||
export const DEFAULT_PARAMETERS: SignParameters = {
|
||||
@@ -28,6 +29,7 @@ export const DEFAULT_PARAMETERS: SignParameters = {
|
||||
fontFamily: 'Helvetica',
|
||||
fontSize: 16,
|
||||
textColor: '#000000',
|
||||
textAlign: 'left',
|
||||
};
|
||||
|
||||
const validateSignParameters = (parameters: SignParameters): boolean => {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useRef, useMemo } from 'react';
|
||||
import { useWorkbenchTransition } from '@app/contexts/WorkbenchTransitionContext';
|
||||
import { useNavigationState } from '@app/contexts/NavigationContext';
|
||||
import { isBaseWorkbench } from '@app/types/workbench';
|
||||
|
||||
/**
|
||||
* Hook to register an element for morphing animations during workbench transitions
|
||||
*
|
||||
* @param morphId - Unique identifier for this element (should be consistent across views)
|
||||
* @param metadata - Optional metadata (file ID, page number, etc.)
|
||||
* @param options - Configuration options
|
||||
* @returns Ref to attach to the element that should morph
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // In FileEditor
|
||||
* const ref = useMorphElement(`file-${fileId}`, { fileId, type: 'file' });
|
||||
* return <div ref={ref}>File Card</div>;
|
||||
*
|
||||
* // In PageEditor (same fileId)
|
||||
* const ref = useMorphElement(`file-${fileId}`, { fileId, type: 'page' });
|
||||
* return <div ref={ref}>Page Thumbnail</div>;
|
||||
* ```
|
||||
*/
|
||||
export function useMorphElement<T extends HTMLElement = HTMLDivElement>(
|
||||
morphId: string,
|
||||
metadata?: Record<string, any>,
|
||||
options?: {
|
||||
/**
|
||||
* Only register in specific workbench types
|
||||
*/
|
||||
onlyIn?: ('viewer' | 'pageEditor' | 'fileEditor')[];
|
||||
|
||||
/**
|
||||
* Disable morphing for this element
|
||||
*/
|
||||
disabled?: boolean;
|
||||
}
|
||||
) {
|
||||
const elementRef = useRef<T>(null);
|
||||
const { registerSourceElement, registerTargetElement, transitionState } = useWorkbenchTransition();
|
||||
const { workbench } = useNavigationState();
|
||||
|
||||
const currentWorkbench = isBaseWorkbench(workbench) ? workbench : null;
|
||||
|
||||
// Stabilize metadata object to prevent unnecessary re-registrations
|
||||
const stableMetadata = useMemo(() => metadata, [JSON.stringify(metadata)]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!elementRef.current || !currentWorkbench || options?.disabled) return;
|
||||
|
||||
// Check if we should register in this workbench
|
||||
if (options?.onlyIn && !options.onlyIn.includes(currentWorkbench)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const element = elementRef.current;
|
||||
|
||||
// ALWAYS register as source when mounted in current workbench
|
||||
// This ensures elements are available as sources before transition starts
|
||||
registerSourceElement(morphId, element, stableMetadata);
|
||||
|
||||
// Cleanup is handled by the context when transition completes
|
||||
}, [
|
||||
morphId,
|
||||
currentWorkbench,
|
||||
registerSourceElement,
|
||||
stableMetadata,
|
||||
options?.disabled,
|
||||
options?.onlyIn,
|
||||
]);
|
||||
|
||||
// Separate effect for target registration during transitions
|
||||
useEffect(() => {
|
||||
if (!elementRef.current || !currentWorkbench || options?.disabled) return;
|
||||
|
||||
// Check if we should register in this workbench
|
||||
if (options?.onlyIn && !options.onlyIn.includes(currentWorkbench)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only register as target if we're transitioning TO this workbench
|
||||
if (transitionState.isTransitioning && transitionState.toWorkbench === currentWorkbench) {
|
||||
const element = elementRef.current;
|
||||
registerTargetElement(morphId, element, stableMetadata);
|
||||
}
|
||||
}, [
|
||||
morphId,
|
||||
currentWorkbench,
|
||||
transitionState.isTransitioning,
|
||||
transitionState.toWorkbench,
|
||||
registerTargetElement,
|
||||
stableMetadata,
|
||||
options?.disabled,
|
||||
options?.onlyIn,
|
||||
]);
|
||||
|
||||
return elementRef;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useWorkbenchTransition as useMorphContext } from '@app/contexts/WorkbenchTransitionContext';
|
||||
import type { BaseWorkbenchType } from '../types/workbench';
|
||||
|
||||
/**
|
||||
* Hook for initiating morphing transitions between workbenches
|
||||
*
|
||||
* Coordinates the animation sequence:
|
||||
* 1. Register source elements (current view)
|
||||
* 2. Start transition (capture snapshots)
|
||||
* 3. Swap view content
|
||||
* 4. Register target elements (new view)
|
||||
* 5. Morph animation plays
|
||||
* 6. Complete transition
|
||||
*/
|
||||
export function useWorkbenchMorphTransition() {
|
||||
const { startTransition } = useMorphContext();
|
||||
|
||||
const transition = useCallback(
|
||||
async (from: BaseWorkbenchType, to: BaseWorkbenchType, onViewChange?: () => void) => {
|
||||
// Start transition and pass view change callback
|
||||
// The callback will be called after source snapshots are captured
|
||||
// and before target snapshots are captured
|
||||
await startTransition(from, to, onViewChange);
|
||||
},
|
||||
[startTransition]
|
||||
);
|
||||
|
||||
return { transition };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState, lazy, Suspense } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
|
||||
import { Group, useMantineColorScheme } from "@mantine/core";
|
||||
@@ -15,16 +15,15 @@ import { useViewer } from "@app/contexts/ViewerContext";
|
||||
import AppsIcon from '@mui/icons-material/AppsRounded';
|
||||
|
||||
import ToolPanel from "@app/components/tools/ToolPanel";
|
||||
import Workbench from "@app/components/layout/Workbench";
|
||||
import QuickAccessBar from "@app/components/shared/QuickAccessBar";
|
||||
import RightRail from "@app/components/shared/RightRail";
|
||||
import FileManager from "@app/components/FileManager";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
|
||||
// Lazy-load heavy components that aren't needed on initial render
|
||||
const Workbench = lazy(() => import("@app/components/layout/Workbench"));
|
||||
const FileManager = lazy(() => import("@app/components/FileManager"));
|
||||
const AppConfigModal = lazy(() => import("@app/components/shared/AppConfigModal"));
|
||||
|
||||
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
|
||||
import AppConfigModal from "@app/components/shared/AppConfigModal";
|
||||
import { WorkbenchTransitionProvider } from "@app/contexts/WorkbenchTransitionContext";
|
||||
import { MorphOverlay } from "@app/components/shared/MorphOverlay";
|
||||
|
||||
import "@app/pages/HomePage.css";
|
||||
|
||||
@@ -178,7 +177,9 @@ export default function HomePage() {
|
||||
// Note: File selection limits are now handled directly by individual tools
|
||||
|
||||
return (
|
||||
<div className="h-screen overflow-hidden">
|
||||
<WorkbenchTransitionProvider>
|
||||
<MorphOverlay />
|
||||
<div className="h-screen overflow-hidden">
|
||||
{isMobile ? (
|
||||
<div className="mobile-layout">
|
||||
<div className="mobile-toggle">
|
||||
@@ -221,9 +222,7 @@ export default function HomePage() {
|
||||
<div className="mobile-slide" aria-label={t('home.mobile.workbenchSlide', 'Workspace panel')}>
|
||||
<div className="mobile-slide-content">
|
||||
<div className="flex-1 min-h-0 flex">
|
||||
<Suspense fallback={<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading...</div>}>
|
||||
<Workbench />
|
||||
</Suspense>
|
||||
<Workbench />
|
||||
<RightRail />
|
||||
</div>
|
||||
</div>
|
||||
@@ -273,15 +272,11 @@ export default function HomePage() {
|
||||
<span className="mobile-bottom-button-label">{t('quickAccess.config', 'Config')}</span>
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={null}>
|
||||
<FileManager selectedTool={selectedTool as any /* FIX ME */} />
|
||||
</Suspense>
|
||||
<Suspense fallback={null}>
|
||||
<AppConfigModal
|
||||
opened={configModalOpen}
|
||||
onClose={() => setConfigModalOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
<FileManager selectedTool={selectedTool as any /* FIX ME */} />
|
||||
<AppConfigModal
|
||||
opened={configModalOpen}
|
||||
onClose={() => setConfigModalOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Group
|
||||
@@ -292,15 +287,12 @@ export default function HomePage() {
|
||||
>
|
||||
<QuickAccessBar ref={quickAccessRef} />
|
||||
<ToolPanel />
|
||||
<Suspense fallback={<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading...</div>}>
|
||||
<Workbench />
|
||||
</Suspense>
|
||||
<Workbench />
|
||||
<RightRail />
|
||||
<Suspense fallback={null}>
|
||||
<FileManager selectedTool={selectedTool as any /* FIX ME */} />
|
||||
</Suspense>
|
||||
<FileManager selectedTool={selectedTool as any /* FIX ME */} />
|
||||
</Group>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</WorkbenchTransitionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,14 +3,9 @@
|
||||
*
|
||||
* Prevents infinite worker creation by managing PDF.js workers globally
|
||||
* and ensuring proper cleanup when operations complete.
|
||||
*
|
||||
* Uses dynamic imports to avoid bundling PDF.js in main bundle.
|
||||
*/
|
||||
|
||||
// Dynamic import types for TypeScript
|
||||
type PDFDocumentProxy = import('pdfjs-dist').PDFDocumentProxy;
|
||||
type GlobalWorkerOptions = typeof import('pdfjs-dist').GlobalWorkerOptions;
|
||||
type GetDocumentFn = typeof import('pdfjs-dist').getDocument;
|
||||
import { GlobalWorkerOptions, getDocument, PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';
|
||||
|
||||
class PDFWorkerManager {
|
||||
private static instance: PDFWorkerManager;
|
||||
@@ -18,10 +13,9 @@ class PDFWorkerManager {
|
||||
private workerCount = 0;
|
||||
private maxWorkers = 10; // Limit concurrent workers
|
||||
private isInitialized = false;
|
||||
private pdfjsLib: { GlobalWorkerOptions: GlobalWorkerOptions; getDocument: GetDocumentFn } | null = null;
|
||||
|
||||
private constructor() {
|
||||
// Don't initialize worker in constructor - defer until first use
|
||||
this.initializeWorker();
|
||||
}
|
||||
|
||||
static getInstance(): PDFWorkerManager {
|
||||
@@ -32,14 +26,11 @@ class PDFWorkerManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy-load PDF.js library and initialize worker once globally
|
||||
* Initialize PDF.js worker once globally
|
||||
*/
|
||||
private async initializeWorker(): Promise<void> {
|
||||
private initializeWorker(): void {
|
||||
if (!this.isInitialized) {
|
||||
// Dynamic import - only loads when first PDF operation is needed
|
||||
this.pdfjsLib = await import('pdfjs-dist/legacy/build/pdf.mjs');
|
||||
|
||||
this.pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
|
||||
GlobalWorkerOptions.workerSrc = new URL(
|
||||
'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
|
||||
import.meta.url
|
||||
).toString();
|
||||
@@ -60,13 +51,6 @@ class PDFWorkerManager {
|
||||
verbosity?: number;
|
||||
} = {}
|
||||
): Promise<PDFDocumentProxy> {
|
||||
// Lazy-load PDF.js on first use
|
||||
await this.initializeWorker();
|
||||
|
||||
if (!this.pdfjsLib) {
|
||||
throw new Error('Failed to load PDF.js library');
|
||||
}
|
||||
|
||||
// Wait if we've hit the worker limit
|
||||
if (this.activeDocuments.size >= this.maxWorkers) {
|
||||
await this.waitForAvailableWorker();
|
||||
@@ -84,7 +68,7 @@ class PDFWorkerManager {
|
||||
pdfData = data; // Pass through as-is
|
||||
}
|
||||
|
||||
const loadingTask = this.pdfjsLib.getDocument(
|
||||
const loadingTask = getDocument(
|
||||
typeof pdfData === 'string' ? {
|
||||
url: pdfData,
|
||||
disableAutoFetch: options.disableAutoFetch ?? true,
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
import { useEffect, useState, useContext, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { createToolFlow } from '@app/components/tools/shared/createToolFlow';
|
||||
import { useNavigation } from '@app/contexts/NavigationContext';
|
||||
import { useFileSelection } from '@app/contexts/FileContext';
|
||||
import { BaseToolProps } from '@app/types/tool';
|
||||
import { useSignature } from '@app/contexts/SignatureContext';
|
||||
import { ViewerContext, useViewer } from '@app/contexts/ViewerContext';
|
||||
import type { AnnotationToolId } from '@app/components/viewer/viewerTypes';
|
||||
import { useAnnotationStyleState } from '@app/tools/annotate/useAnnotationStyleState';
|
||||
import { useAnnotationSelection } from '@app/tools/annotate/useAnnotationSelection';
|
||||
import { AnnotationPanel } from '@app/tools/annotate/AnnotationPanel';
|
||||
|
||||
const KNOWN_ANNOTATION_TOOLS: AnnotationToolId[] = [
|
||||
'select',
|
||||
'highlight',
|
||||
'underline',
|
||||
'strikeout',
|
||||
'squiggly',
|
||||
'ink',
|
||||
'inkHighlighter',
|
||||
'text',
|
||||
'note',
|
||||
'square',
|
||||
'circle',
|
||||
'line',
|
||||
'lineArrow',
|
||||
'polyline',
|
||||
'polygon',
|
||||
'stamp',
|
||||
'signatureStamp',
|
||||
'signatureInk',
|
||||
];
|
||||
|
||||
const isKnownAnnotationTool = (toolId: string | undefined | null): toolId is AnnotationToolId =>
|
||||
!!toolId && (KNOWN_ANNOTATION_TOOLS as string[]).includes(toolId);
|
||||
|
||||
const Annotate = (_props: BaseToolProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { selectedTool, workbench, hasUnsavedChanges } = useNavigation();
|
||||
const { selectedFiles } = useFileSelection();
|
||||
const {
|
||||
signatureApiRef,
|
||||
annotationApiRef,
|
||||
historyApiRef,
|
||||
undo,
|
||||
redo,
|
||||
setSignatureConfig,
|
||||
setPlacementMode,
|
||||
placementPreviewSize,
|
||||
setPlacementPreviewSize,
|
||||
} = useSignature();
|
||||
const viewerContext = useContext(ViewerContext);
|
||||
const { getZoomState, registerImmediateZoomUpdate } = useViewer();
|
||||
|
||||
const [activeTool, setActiveTool] = useState<AnnotationToolId>('select');
|
||||
const activeToolRef = useRef<AnnotationToolId>('select');
|
||||
const wasAnnotateActiveRef = useRef<boolean>(false);
|
||||
const [selectedTextDraft, setSelectedTextDraft] = useState<string>('');
|
||||
const [selectedFontSize, setSelectedFontSize] = useState<number>(14);
|
||||
const [stampImageData, setStampImageData] = useState<string | undefined>();
|
||||
const [stampImageSize, setStampImageSize] = useState<{ width: number; height: number } | null>(null);
|
||||
const [historyAvailability, setHistoryAvailability] = useState({ canUndo: false, canRedo: false });
|
||||
const manualToolSwitch = useRef<boolean>(false);
|
||||
|
||||
// Zoom tracking for stamp size conversion
|
||||
const [currentZoom, setCurrentZoom] = useState(() => {
|
||||
const zoomState = getZoomState();
|
||||
if (!zoomState) return 1;
|
||||
if (typeof zoomState.zoomPercent === 'number') {
|
||||
return Math.max(zoomState.zoomPercent / 100, 0.01);
|
||||
}
|
||||
return Math.max(zoomState.currentZoom ?? 1, 0.01);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
return registerImmediateZoomUpdate((newZoomPercent) => {
|
||||
setCurrentZoom(Math.max(newZoomPercent / 100, 0.01));
|
||||
});
|
||||
}, [registerImmediateZoomUpdate]);
|
||||
|
||||
useEffect(() => {
|
||||
activeToolRef.current = activeTool;
|
||||
}, [activeTool]);
|
||||
|
||||
// CSS to PDF size conversion accounting for zoom
|
||||
const cssToPdfSize = useCallback(
|
||||
(size: { width: number; height: number }) => {
|
||||
const zoom = currentZoom || 1;
|
||||
const factor = 1 / zoom;
|
||||
return {
|
||||
width: size.width * factor,
|
||||
height: size.height * factor,
|
||||
};
|
||||
},
|
||||
[currentZoom]
|
||||
);
|
||||
|
||||
const computeStampDisplaySize = useCallback((natural: { width: number; height: number } | null) => {
|
||||
if (!natural) {
|
||||
return { width: 180, height: 120 };
|
||||
}
|
||||
const maxSide = 260;
|
||||
const minSide = 24;
|
||||
const { width, height } = natural;
|
||||
const largest = Math.max(width || maxSide, height || maxSide, 1);
|
||||
const scale = Math.min(1, maxSide / largest);
|
||||
return {
|
||||
width: Math.max(minSide, Math.round(width * scale)),
|
||||
height: Math.max(minSide, Math.round(height * scale)),
|
||||
};
|
||||
}, []);
|
||||
|
||||
const {
|
||||
styleState,
|
||||
styleActions,
|
||||
buildToolOptions,
|
||||
getActiveColor,
|
||||
} = useAnnotationStyleState(cssToPdfSize);
|
||||
|
||||
const {
|
||||
setInkWidth,
|
||||
setShapeThickness,
|
||||
setTextColor,
|
||||
setTextBackgroundColor,
|
||||
setNoteBackgroundColor,
|
||||
setInkColor,
|
||||
setHighlightColor,
|
||||
setHighlightOpacity,
|
||||
setFreehandHighlighterWidth,
|
||||
setUnderlineColor,
|
||||
setUnderlineOpacity,
|
||||
setStrikeoutColor,
|
||||
setStrikeoutOpacity,
|
||||
setSquigglyColor,
|
||||
setSquigglyOpacity,
|
||||
setShapeStrokeColor,
|
||||
setShapeFillColor,
|
||||
setShapeOpacity,
|
||||
setShapeStrokeOpacity,
|
||||
setShapeFillOpacity,
|
||||
setTextAlignment,
|
||||
} = styleActions;
|
||||
|
||||
const handleApplyChanges = useCallback(() => {
|
||||
window.dispatchEvent(new CustomEvent('stirling-annotations-apply'));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const isAnnotateActive = workbench === 'viewer' && selectedTool === 'annotate';
|
||||
if (wasAnnotateActiveRef.current && !isAnnotateActive) {
|
||||
annotationApiRef?.current?.deactivateTools?.();
|
||||
signatureApiRef?.current?.deactivateTools?.();
|
||||
setPlacementMode(false);
|
||||
} else if (!wasAnnotateActiveRef.current && isAnnotateActive) {
|
||||
// When entering annotate mode, activate the select tool by default
|
||||
const toolOptions = buildToolOptions('select');
|
||||
annotationApiRef?.current?.activateAnnotationTool?.('select', toolOptions);
|
||||
}
|
||||
wasAnnotateActiveRef.current = isAnnotateActive;
|
||||
}, [workbench, selectedTool, annotationApiRef, signatureApiRef, setPlacementMode, buildToolOptions]);
|
||||
|
||||
// Monitor history state for undo/redo availability
|
||||
useEffect(() => {
|
||||
const historyApi = historyApiRef?.current;
|
||||
if (!historyApi) return;
|
||||
|
||||
const updateAvailability = () =>
|
||||
setHistoryAvailability({
|
||||
canUndo: historyApi.canUndo?.() ?? false,
|
||||
canRedo: historyApi.canRedo?.() ?? false,
|
||||
});
|
||||
|
||||
updateAvailability();
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | undefined;
|
||||
if (!historyApi.subscribe) {
|
||||
// Fallback polling in case the history API doesn't support subscriptions
|
||||
interval = setInterval(updateAvailability, 350);
|
||||
} else {
|
||||
const unsubscribe = historyApi.subscribe(updateAvailability);
|
||||
return () => {
|
||||
if (typeof unsubscribe === 'function') {
|
||||
unsubscribe();
|
||||
}
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
}, [historyApiRef?.current]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewerContext) return;
|
||||
if (viewerContext.isAnnotationMode) return;
|
||||
|
||||
viewerContext.setAnnotationMode(true);
|
||||
const toolOptions =
|
||||
activeTool === 'stamp'
|
||||
? buildToolOptions('stamp', { stampImageData, stampImageSize })
|
||||
: buildToolOptions(activeTool);
|
||||
annotationApiRef?.current?.activateAnnotationTool?.(activeTool, toolOptions);
|
||||
}, [viewerContext?.isAnnotationMode, signatureApiRef, activeTool, buildToolOptions, stampImageData, stampImageSize]);
|
||||
|
||||
const activateAnnotationTool = (toolId: AnnotationToolId) => {
|
||||
// If leaving stamp tool, clean up placement mode
|
||||
if (activeTool === 'stamp' && toolId !== 'stamp') {
|
||||
setPlacementMode(false);
|
||||
setSignatureConfig(null);
|
||||
}
|
||||
|
||||
viewerContext?.setAnnotationMode(true);
|
||||
|
||||
// Mark as manual tool switch to prevent auto-switch back
|
||||
manualToolSwitch.current = true;
|
||||
|
||||
// Deselect annotation in the viewer first
|
||||
annotationApiRef?.current?.deselectAnnotation?.();
|
||||
|
||||
// Clear selection state to show default controls
|
||||
setSelectedAnn(null);
|
||||
setSelectedAnnId(null);
|
||||
|
||||
// Change the tool
|
||||
setActiveTool(toolId);
|
||||
const options =
|
||||
toolId === 'stamp'
|
||||
? buildToolOptions('stamp', { stampImageData, stampImageSize })
|
||||
: buildToolOptions(toolId);
|
||||
|
||||
// For stamp, apply the image if we have one
|
||||
annotationApiRef?.current?.setAnnotationStyle?.(toolId, options);
|
||||
annotationApiRef?.current?.activateAnnotationTool?.(toolId === 'stamp' ? 'stamp' : toolId, options);
|
||||
|
||||
// Reset flag after a short delay
|
||||
setTimeout(() => {
|
||||
manualToolSwitch.current = false;
|
||||
}, 300);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// push style updates to EmbedPDF when sliders/colors change
|
||||
if (activeTool === 'stamp') {
|
||||
const options = buildToolOptions('stamp', { stampImageData, stampImageSize });
|
||||
annotationApiRef?.current?.setAnnotationStyle?.('stamp', options);
|
||||
} else {
|
||||
annotationApiRef?.current?.setAnnotationStyle?.(activeTool, buildToolOptions(activeTool));
|
||||
}
|
||||
}, [activeTool, buildToolOptions, signatureApiRef, stampImageData, stampImageSize]);
|
||||
|
||||
// Sync preview size from overlay to annotation engine
|
||||
useEffect(() => {
|
||||
// When preview size changes, update stamp annotation sizing
|
||||
// The SignatureAPIBridge will use placementPreviewSize from SignatureContext
|
||||
// and apply the converted size to the stamp tool automatically
|
||||
if (activeTool === 'stamp' && stampImageData) {
|
||||
const size = placementPreviewSize ?? stampImageSize;
|
||||
const stampOptions = buildToolOptions('stamp', { stampImageData, stampImageSize: size ?? null });
|
||||
annotationApiRef?.current?.setAnnotationStyle?.('stamp', stampOptions);
|
||||
}
|
||||
}, [placementPreviewSize, activeTool, stampImageData, signatureApiRef, stampImageSize, cssToPdfSize, buildToolOptions]);
|
||||
|
||||
// Allow exiting multi-point tools with Escape (e.g., polyline)
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (['polyline', 'polygon'].includes(activeTool)) {
|
||||
annotationApiRef?.current?.setAnnotationStyle?.(activeTool, buildToolOptions(activeTool));
|
||||
annotationApiRef?.current?.activateAnnotationTool?.(null as any);
|
||||
setTimeout(() => {
|
||||
annotationApiRef?.current?.activateAnnotationTool?.(activeTool, buildToolOptions(activeTool));
|
||||
}, 50);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [activeTool, buildToolOptions, signatureApiRef]);
|
||||
|
||||
const deriveToolFromAnnotation = useCallback((annotation: any): AnnotationToolId | undefined => {
|
||||
if (!annotation) return undefined;
|
||||
const customToolId = annotation.customData?.toolId || annotation.customData?.annotationToolId;
|
||||
if (isKnownAnnotationTool(customToolId)) {
|
||||
return customToolId;
|
||||
}
|
||||
|
||||
const type = annotation.type ?? annotation.object?.type;
|
||||
switch (type) {
|
||||
case 3: return 'text'; // FREETEXT
|
||||
case 4: return 'line'; // LINE
|
||||
case 5: return 'square'; // SQUARE
|
||||
case 6: return 'circle'; // CIRCLE
|
||||
case 7: return 'polygon'; // POLYGON
|
||||
case 8: return 'polyline'; // POLYLINE
|
||||
case 9: return 'highlight'; // HIGHLIGHT
|
||||
case 10: return 'underline'; // UNDERLINE
|
||||
case 11: return 'squiggly'; // SQUIGGLY
|
||||
case 12: return 'strikeout'; // STRIKEOUT
|
||||
case 13: return 'stamp'; // STAMP
|
||||
case 15: return 'ink'; // INK
|
||||
default: return undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const {
|
||||
selectedAnn,
|
||||
setSelectedAnn,
|
||||
setSelectedAnnId,
|
||||
} = useAnnotationSelection({
|
||||
annotationApiRef,
|
||||
deriveToolFromAnnotation,
|
||||
activeToolRef,
|
||||
manualToolSwitch,
|
||||
setActiveTool,
|
||||
setSelectedTextDraft,
|
||||
setSelectedFontSize,
|
||||
setInkWidth,
|
||||
setShapeThickness,
|
||||
setTextColor,
|
||||
setTextBackgroundColor,
|
||||
setNoteBackgroundColor,
|
||||
setInkColor,
|
||||
setHighlightColor,
|
||||
setHighlightOpacity,
|
||||
setFreehandHighlighterWidth,
|
||||
setUnderlineColor,
|
||||
setUnderlineOpacity,
|
||||
setStrikeoutColor,
|
||||
setStrikeoutOpacity,
|
||||
setSquigglyColor,
|
||||
setSquigglyOpacity,
|
||||
setShapeStrokeColor,
|
||||
setShapeFillColor,
|
||||
setShapeOpacity,
|
||||
setShapeStrokeOpacity,
|
||||
setShapeFillOpacity,
|
||||
setTextAlignment,
|
||||
});
|
||||
|
||||
const steps =
|
||||
selectedFiles.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
title: t('annotation.title', 'Annotate'),
|
||||
isCollapsed: false,
|
||||
onCollapsedClick: undefined,
|
||||
content: (
|
||||
<AnnotationPanel
|
||||
activeTool={activeTool}
|
||||
activateAnnotationTool={activateAnnotationTool}
|
||||
styleState={styleState}
|
||||
styleActions={styleActions}
|
||||
getActiveColor={getActiveColor}
|
||||
buildToolOptions={buildToolOptions}
|
||||
deriveToolFromAnnotation={deriveToolFromAnnotation}
|
||||
selectedAnn={selectedAnn}
|
||||
selectedTextDraft={selectedTextDraft}
|
||||
setSelectedTextDraft={setSelectedTextDraft}
|
||||
selectedFontSize={selectedFontSize}
|
||||
setSelectedFontSize={setSelectedFontSize}
|
||||
annotationApiRef={annotationApiRef}
|
||||
signatureApiRef={signatureApiRef}
|
||||
viewerContext={viewerContext}
|
||||
setPlacementMode={setPlacementMode}
|
||||
setSignatureConfig={setSignatureConfig}
|
||||
computeStampDisplaySize={computeStampDisplaySize}
|
||||
stampImageData={stampImageData}
|
||||
setStampImageData={setStampImageData}
|
||||
stampImageSize={stampImageSize}
|
||||
setStampImageSize={setStampImageSize}
|
||||
setPlacementPreviewSize={setPlacementPreviewSize}
|
||||
undo={undo}
|
||||
redo={redo}
|
||||
historyAvailability={historyAvailability}
|
||||
onApplyChanges={handleApplyChanges}
|
||||
applyDisabled={!hasUnsavedChanges}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
return createToolFlow({
|
||||
files: {
|
||||
selectedFiles,
|
||||
isCollapsed: false,
|
||||
},
|
||||
steps,
|
||||
review: {
|
||||
isVisible: false,
|
||||
operation: {
|
||||
files: [],
|
||||
thumbnails: [],
|
||||
isGeneratingThumbnails: false,
|
||||
downloadUrl: null,
|
||||
downloadFilename: '',
|
||||
isLoading: false,
|
||||
status: '',
|
||||
errorMessage: null,
|
||||
progress: null,
|
||||
executeOperation: async () => {},
|
||||
resetResults: () => {},
|
||||
clearError: () => {},
|
||||
cancelOperation: () => {},
|
||||
undoOperation: async () => {},
|
||||
},
|
||||
title: '',
|
||||
onFileClick: () => {},
|
||||
onUndo: () => {},
|
||||
},
|
||||
forceStepNumbers: true,
|
||||
});
|
||||
};
|
||||
|
||||
export default Annotate;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,383 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AnnotationAPI, AnnotationToolId } from '@app/components/viewer/viewerTypes';
|
||||
|
||||
interface UseAnnotationSelectionParams {
|
||||
annotationApiRef: React.RefObject<AnnotationAPI | null>;
|
||||
deriveToolFromAnnotation: (annotation: any) => AnnotationToolId | undefined;
|
||||
activeToolRef: React.MutableRefObject<AnnotationToolId>;
|
||||
manualToolSwitch: React.MutableRefObject<boolean>;
|
||||
setActiveTool: (toolId: AnnotationToolId) => void;
|
||||
setSelectedTextDraft: (text: string) => void;
|
||||
setSelectedFontSize: (size: number) => void;
|
||||
setInkWidth: (value: number) => void;
|
||||
setFreehandHighlighterWidth?: (value: number) => void;
|
||||
setShapeThickness: (value: number) => void;
|
||||
setTextColor: (value: string) => void;
|
||||
setTextBackgroundColor: (value: string) => void;
|
||||
setNoteBackgroundColor: (value: string) => void;
|
||||
setInkColor: (value: string) => void;
|
||||
setHighlightColor: (value: string) => void;
|
||||
setHighlightOpacity: (value: number) => void;
|
||||
setUnderlineColor: (value: string) => void;
|
||||
setUnderlineOpacity: (value: number) => void;
|
||||
setStrikeoutColor: (value: string) => void;
|
||||
setStrikeoutOpacity: (value: number) => void;
|
||||
setSquigglyColor: (value: string) => void;
|
||||
setSquigglyOpacity: (value: number) => void;
|
||||
setShapeStrokeColor: (value: string) => void;
|
||||
setShapeFillColor: (value: string) => void;
|
||||
setShapeOpacity: (value: number) => void;
|
||||
setShapeStrokeOpacity: (value: number) => void;
|
||||
setShapeFillOpacity: (value: number) => void;
|
||||
setTextAlignment: (value: 'left' | 'center' | 'right') => void;
|
||||
}
|
||||
|
||||
const MARKUP_TOOL_IDS = ['highlight', 'underline', 'strikeout', 'squiggly'] as const;
|
||||
const DRAWING_TOOL_IDS = ['ink', 'inkHighlighter'] as const;
|
||||
|
||||
const isTextMarkupAnnotation = (annotation: any): boolean => {
|
||||
const toolId =
|
||||
annotation?.customData?.annotationToolId ||
|
||||
annotation?.customData?.toolId ||
|
||||
annotation?.object?.customData?.annotationToolId ||
|
||||
annotation?.object?.customData?.toolId;
|
||||
if (toolId && MARKUP_TOOL_IDS.includes(toolId)) return true;
|
||||
|
||||
const type = annotation?.type ?? annotation?.object?.type;
|
||||
if (typeof type === 'number' && [9, 10, 11, 12].includes(type)) return true;
|
||||
|
||||
const subtype = annotation?.subtype ?? annotation?.object?.subtype;
|
||||
if (typeof subtype === 'string') {
|
||||
const lower = subtype.toLowerCase();
|
||||
if (MARKUP_TOOL_IDS.some((t) => lower.includes(t))) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const shouldStayOnPlacementTool = (annotation: any, derivedTool?: string | null | undefined): boolean => {
|
||||
const toolId =
|
||||
derivedTool ||
|
||||
annotation?.customData?.annotationToolId ||
|
||||
annotation?.customData?.toolId ||
|
||||
annotation?.object?.customData?.annotationToolId ||
|
||||
annotation?.object?.customData?.toolId;
|
||||
|
||||
if (toolId && (MARKUP_TOOL_IDS.includes(toolId as any) || DRAWING_TOOL_IDS.includes(toolId as any))) {
|
||||
return true;
|
||||
}
|
||||
const type = annotation?.type ?? annotation?.object?.type;
|
||||
if (typeof type === 'number' && type === 15) return true; // ink family
|
||||
if (isTextMarkupAnnotation(annotation)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
export function useAnnotationSelection({
|
||||
annotationApiRef,
|
||||
deriveToolFromAnnotation,
|
||||
activeToolRef,
|
||||
manualToolSwitch,
|
||||
setActiveTool,
|
||||
setSelectedTextDraft,
|
||||
setSelectedFontSize,
|
||||
setInkWidth,
|
||||
setShapeThickness,
|
||||
setTextColor,
|
||||
setTextBackgroundColor,
|
||||
setNoteBackgroundColor,
|
||||
setInkColor,
|
||||
setHighlightColor,
|
||||
setHighlightOpacity,
|
||||
setUnderlineColor,
|
||||
setUnderlineOpacity,
|
||||
setStrikeoutColor,
|
||||
setStrikeoutOpacity,
|
||||
setSquigglyColor,
|
||||
setSquigglyOpacity,
|
||||
setShapeStrokeColor,
|
||||
setShapeFillColor,
|
||||
setShapeOpacity,
|
||||
setShapeStrokeOpacity,
|
||||
setShapeFillOpacity,
|
||||
setTextAlignment,
|
||||
setFreehandHighlighterWidth,
|
||||
}: UseAnnotationSelectionParams) {
|
||||
const [selectedAnn, setSelectedAnn] = useState<any | null>(null);
|
||||
const [selectedAnnId, setSelectedAnnId] = useState<string | null>(null);
|
||||
const selectedAnnIdRef = useRef<string | null>(null);
|
||||
|
||||
const applySelectionFromAnnotation = useCallback(
|
||||
(ann: any | null) => {
|
||||
const annObject = ann?.object ?? ann ?? null;
|
||||
const annId = annObject?.id ?? null;
|
||||
const type = annObject?.type;
|
||||
const derivedTool = annObject ? deriveToolFromAnnotation(annObject) : undefined;
|
||||
selectedAnnIdRef.current = annId;
|
||||
setSelectedAnnId(annId);
|
||||
// Normalize selected annotation to always expose .object for edit panels
|
||||
const normalizedSelection = ann?.object ? ann : annObject ? { object: annObject } : null;
|
||||
setSelectedAnn(normalizedSelection);
|
||||
|
||||
if (annObject?.contents !== undefined) {
|
||||
setSelectedTextDraft(annObject.contents ?? '');
|
||||
}
|
||||
if (annObject?.fontSize !== undefined) {
|
||||
setSelectedFontSize(annObject.fontSize ?? 14);
|
||||
}
|
||||
if (annObject?.textAlign !== undefined) {
|
||||
const align = annObject.textAlign;
|
||||
if (typeof align === 'string') {
|
||||
const normalized = align === 'center' ? 'center' : align === 'right' ? 'right' : 'left';
|
||||
setTextAlignment(normalized);
|
||||
} else if (typeof align === 'number') {
|
||||
const normalized = align === 1 ? 'center' : align === 2 ? 'right' : 'left';
|
||||
setTextAlignment(normalized);
|
||||
}
|
||||
}
|
||||
if (type === 3) {
|
||||
const background =
|
||||
(annObject?.backgroundColor as string | undefined) ||
|
||||
(annObject?.fillColor as string | undefined) ||
|
||||
undefined;
|
||||
const textColor = (annObject?.textColor as string | undefined) || (annObject?.color as string | undefined);
|
||||
if (textColor) {
|
||||
setTextColor(textColor);
|
||||
}
|
||||
if (derivedTool === 'note') {
|
||||
setNoteBackgroundColor(background || '');
|
||||
} else {
|
||||
setTextBackgroundColor(background || '');
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 15) {
|
||||
const width =
|
||||
annObject?.strokeWidth ?? annObject?.borderWidth ?? annObject?.lineWidth ?? annObject?.thickness;
|
||||
if (derivedTool === 'inkHighlighter') {
|
||||
if (annObject?.color) setHighlightColor(annObject.color);
|
||||
if (annObject?.opacity !== undefined) {
|
||||
setHighlightOpacity(Math.round((annObject.opacity ?? 1) * 100));
|
||||
}
|
||||
if (width !== undefined && setFreehandHighlighterWidth) {
|
||||
setFreehandHighlighterWidth(width);
|
||||
}
|
||||
} else {
|
||||
if (width !== undefined) setInkWidth(width ?? 2);
|
||||
if (annObject?.color) {
|
||||
setInkColor(annObject.color);
|
||||
}
|
||||
}
|
||||
} else if (type >= 4 && type <= 8) {
|
||||
const width = annObject?.strokeWidth ?? annObject?.borderWidth ?? annObject?.lineWidth;
|
||||
if (width !== undefined) {
|
||||
setShapeThickness(width ?? 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 9) {
|
||||
if (annObject?.color) setHighlightColor(annObject.color);
|
||||
if (annObject?.opacity !== undefined) setHighlightOpacity(Math.round((annObject.opacity ?? 1) * 100));
|
||||
} else if (type === 10) {
|
||||
if (annObject?.color) setUnderlineColor(annObject.color);
|
||||
if (annObject?.opacity !== undefined) setUnderlineOpacity(Math.round((annObject.opacity ?? 1) * 100));
|
||||
} else if (type === 12) {
|
||||
if (annObject?.color) setStrikeoutColor(annObject.color);
|
||||
if (annObject?.opacity !== undefined) setStrikeoutOpacity(Math.round((annObject.opacity ?? 1) * 100));
|
||||
} else if (type === 11) {
|
||||
if (annObject?.color) setSquigglyColor(annObject.color);
|
||||
if (annObject?.opacity !== undefined) setSquigglyOpacity(Math.round((annObject.opacity ?? 1) * 100));
|
||||
}
|
||||
|
||||
if ([4, 5, 6, 7, 8].includes(type)) {
|
||||
const stroke = (annObject?.strokeColor as string | undefined) ?? (annObject?.color as string | undefined);
|
||||
if (stroke) setShapeStrokeColor(stroke);
|
||||
if ([5, 6, 7].includes(type)) {
|
||||
const fill = (annObject?.color as string | undefined) ?? (annObject?.fillColor as string | undefined);
|
||||
if (fill) setShapeFillColor(fill);
|
||||
}
|
||||
const opacity =
|
||||
annObject?.opacity !== undefined ? Math.round((annObject.opacity ?? 1) * 100) : undefined;
|
||||
const strokeOpacityValue =
|
||||
annObject?.strokeOpacity !== undefined
|
||||
? Math.round((annObject.strokeOpacity ?? 1) * 100)
|
||||
: undefined;
|
||||
const fillOpacityValue =
|
||||
annObject?.fillOpacity !== undefined ? Math.round((annObject.fillOpacity ?? 1) * 100) : undefined;
|
||||
if (opacity !== undefined) {
|
||||
setShapeOpacity(opacity);
|
||||
setShapeStrokeOpacity(strokeOpacityValue ?? opacity);
|
||||
setShapeFillOpacity(fillOpacityValue ?? opacity);
|
||||
} else {
|
||||
if (strokeOpacityValue !== undefined) setShapeStrokeOpacity(strokeOpacityValue);
|
||||
if (fillOpacityValue !== undefined) setShapeFillOpacity(fillOpacityValue);
|
||||
}
|
||||
}
|
||||
|
||||
const matchingTool = derivedTool;
|
||||
const stayOnPlacement = shouldStayOnPlacementTool(annObject, matchingTool);
|
||||
if (matchingTool && activeToolRef.current !== 'select' && !stayOnPlacement) {
|
||||
activeToolRef.current = 'select';
|
||||
setActiveTool('select');
|
||||
// Immediately enable select tool to avoid re-entering placement after creation.
|
||||
annotationApiRef.current?.activateAnnotationTool?.('select');
|
||||
} else if (activeToolRef.current === 'select') {
|
||||
// Keep the viewer in Select mode so clicking existing annotations does not re-enable placement.
|
||||
annotationApiRef.current?.activateAnnotationTool?.('select');
|
||||
}
|
||||
},
|
||||
[
|
||||
activeToolRef,
|
||||
deriveToolFromAnnotation,
|
||||
manualToolSwitch,
|
||||
setActiveTool,
|
||||
setInkWidth,
|
||||
setNoteBackgroundColor,
|
||||
setSelectedFontSize,
|
||||
setSelectedTextDraft,
|
||||
setShapeThickness,
|
||||
setTextBackgroundColor,
|
||||
setTextColor,
|
||||
setInkColor,
|
||||
setHighlightColor,
|
||||
setHighlightOpacity,
|
||||
setUnderlineColor,
|
||||
setUnderlineOpacity,
|
||||
setStrikeoutColor,
|
||||
setStrikeoutOpacity,
|
||||
setSquigglyColor,
|
||||
setSquigglyOpacity,
|
||||
setShapeStrokeColor,
|
||||
setShapeFillColor,
|
||||
setShapeOpacity,
|
||||
setShapeStrokeOpacity,
|
||||
setShapeFillOpacity,
|
||||
setTextAlignment,
|
||||
setFreehandHighlighterWidth,
|
||||
shouldStayOnPlacementTool,
|
||||
]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const api = annotationApiRef.current as any;
|
||||
if (!api) return;
|
||||
|
||||
const checkSelection = () => {
|
||||
let ann: any = null;
|
||||
if (typeof api.getSelectedAnnotation === 'function') {
|
||||
try {
|
||||
ann = api.getSelectedAnnotation();
|
||||
} catch (error) {
|
||||
// Some builds of the annotation plugin can throw when reading
|
||||
// internal selection state (e.g., accessing `selectedUid` on
|
||||
// an undefined object). Treat this as "no current selection"
|
||||
// instead of crashing the annotations tool.
|
||||
console.error('[useAnnotationSelection] getSelectedAnnotation failed:', error);
|
||||
ann = null;
|
||||
}
|
||||
}
|
||||
const currentId = ann?.object?.id ?? ann?.id ?? null;
|
||||
if (currentId !== selectedAnnIdRef.current) {
|
||||
applySelectionFromAnnotation(ann ?? null);
|
||||
}
|
||||
};
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
if (typeof api.onAnnotationEvent === 'function') {
|
||||
const handler = (event: any) => {
|
||||
const ann = event?.annotation ?? event?.selectedAnnotation ?? null;
|
||||
const eventType = event?.type;
|
||||
switch (eventType) {
|
||||
case 'create':
|
||||
case 'add':
|
||||
case 'added':
|
||||
case 'created':
|
||||
case 'annotationCreated':
|
||||
case 'annotationAdded':
|
||||
case 'complete': {
|
||||
const eventAnn = ann ?? api.getSelectedAnnotation?.();
|
||||
applySelectionFromAnnotation(eventAnn);
|
||||
const currentTool = activeToolRef.current;
|
||||
const tool =
|
||||
deriveToolFromAnnotation((eventAnn as any)?.object ?? eventAnn ?? api.getSelectedAnnotation?.()) ||
|
||||
currentTool;
|
||||
const stayOnPlacement =
|
||||
shouldStayOnPlacementTool(eventAnn, tool) ||
|
||||
(tool ? DRAWING_TOOL_IDS.includes(tool as any) : false);
|
||||
if (activeToolRef.current !== 'select' && !stayOnPlacement) {
|
||||
activeToolRef.current = 'select';
|
||||
setActiveTool('select');
|
||||
annotationApiRef.current?.activateAnnotationTool?.('select');
|
||||
}
|
||||
// Re-read selection after the viewer updates to ensure we have the full annotation object for the edit panel.
|
||||
setTimeout(() => {
|
||||
const selected = api.getSelectedAnnotation?.();
|
||||
applySelectionFromAnnotation(selected ?? eventAnn ?? null);
|
||||
const derivedAfter =
|
||||
deriveToolFromAnnotation((selected as any)?.object ?? selected ?? eventAnn ?? null) || activeToolRef.current;
|
||||
const stayOnPlacementAfter =
|
||||
shouldStayOnPlacementTool(selected ?? eventAnn ?? null, derivedAfter) ||
|
||||
(derivedAfter ? DRAWING_TOOL_IDS.includes(derivedAfter as any) : false);
|
||||
if (activeToolRef.current !== 'select' && !stayOnPlacementAfter) {
|
||||
activeToolRef.current = 'select';
|
||||
setActiveTool('select');
|
||||
annotationApiRef.current?.activateAnnotationTool?.('select');
|
||||
}
|
||||
}, 50);
|
||||
break;
|
||||
}
|
||||
case 'select':
|
||||
case 'selected':
|
||||
case 'annotationSelected':
|
||||
case 'annotationClicked':
|
||||
case 'annotationTapped':
|
||||
applySelectionFromAnnotation(ann ?? api.getSelectedAnnotation?.());
|
||||
break;
|
||||
case 'deselect':
|
||||
case 'clearSelection':
|
||||
applySelectionFromAnnotation(null);
|
||||
break;
|
||||
case 'delete':
|
||||
case 'remove':
|
||||
if (ann?.id && ann.id === selectedAnnIdRef.current) {
|
||||
applySelectionFromAnnotation(null);
|
||||
}
|
||||
break;
|
||||
case 'update':
|
||||
case 'change':
|
||||
if (selectedAnnIdRef.current) {
|
||||
const current = api.getSelectedAnnotation?.();
|
||||
if (current) {
|
||||
applySelectionFromAnnotation(current);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = api.onAnnotationEvent(handler);
|
||||
interval = setInterval(checkSelection, 450);
|
||||
return () => {
|
||||
if (typeof unsubscribe === 'function') {
|
||||
unsubscribe();
|
||||
}
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
}
|
||||
|
||||
interval = setInterval(checkSelection, 350);
|
||||
return () => {
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
}, [annotationApiRef, applySelectionFromAnnotation]);
|
||||
|
||||
return {
|
||||
selectedAnn,
|
||||
selectedAnnId,
|
||||
selectedAnnIdRef,
|
||||
setSelectedAnn,
|
||||
setSelectedAnnId,
|
||||
applySelectionFromAnnotation,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import type { AnnotationToolId } from '@app/components/viewer/viewerTypes';
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
export type BuildToolOptionsExtras = {
|
||||
includeMetadata?: boolean;
|
||||
stampImageData?: string;
|
||||
stampImageSize?: Size | null;
|
||||
};
|
||||
|
||||
interface StyleState {
|
||||
inkColor: string;
|
||||
inkWidth: number;
|
||||
highlightColor: string;
|
||||
highlightOpacity: number;
|
||||
freehandHighlighterWidth: number;
|
||||
underlineColor: string;
|
||||
underlineOpacity: number;
|
||||
strikeoutColor: string;
|
||||
strikeoutOpacity: number;
|
||||
squigglyColor: string;
|
||||
squigglyOpacity: number;
|
||||
textColor: string;
|
||||
textSize: number;
|
||||
textAlignment: 'left' | 'center' | 'right';
|
||||
textBackgroundColor: string;
|
||||
noteBackgroundColor: string;
|
||||
shapeStrokeColor: string;
|
||||
shapeFillColor: string;
|
||||
shapeOpacity: number;
|
||||
shapeStrokeOpacity: number;
|
||||
shapeFillOpacity: number;
|
||||
shapeThickness: number;
|
||||
}
|
||||
|
||||
interface StyleActions {
|
||||
setInkColor: (value: string) => void;
|
||||
setInkWidth: (value: number) => void;
|
||||
setHighlightColor: (value: string) => void;
|
||||
setHighlightOpacity: (value: number) => void;
|
||||
setFreehandHighlighterWidth: (value: number) => void;
|
||||
setUnderlineColor: (value: string) => void;
|
||||
setUnderlineOpacity: (value: number) => void;
|
||||
setStrikeoutColor: (value: string) => void;
|
||||
setStrikeoutOpacity: (value: number) => void;
|
||||
setSquigglyColor: (value: string) => void;
|
||||
setSquigglyOpacity: (value: number) => void;
|
||||
setTextColor: (value: string) => void;
|
||||
setTextSize: (value: number) => void;
|
||||
setTextAlignment: (value: 'left' | 'center' | 'right') => void;
|
||||
setTextBackgroundColor: (value: string) => void;
|
||||
setNoteBackgroundColor: (value: string) => void;
|
||||
setShapeStrokeColor: (value: string) => void;
|
||||
setShapeFillColor: (value: string) => void;
|
||||
setShapeOpacity: (value: number) => void;
|
||||
setShapeStrokeOpacity: (value: number) => void;
|
||||
setShapeFillOpacity: (value: number) => void;
|
||||
setShapeThickness: (value: number) => void;
|
||||
}
|
||||
|
||||
export type BuildToolOptionsFn = (
|
||||
toolId: AnnotationToolId,
|
||||
extras?: BuildToolOptionsExtras
|
||||
) => Record<string, unknown>;
|
||||
|
||||
export interface AnnotationStyleStateReturn {
|
||||
styleState: StyleState;
|
||||
styleActions: StyleActions;
|
||||
buildToolOptions: BuildToolOptionsFn;
|
||||
getActiveColor: (target: string | null) => string;
|
||||
}
|
||||
|
||||
export const useAnnotationStyleState = (
|
||||
cssToPdfSize?: (size: Size) => Size
|
||||
): AnnotationStyleStateReturn => {
|
||||
const [inkColor, setInkColor] = useState('#1f2933');
|
||||
const [inkWidth, setInkWidth] = useState(2);
|
||||
const [highlightColor, setHighlightColor] = useState('#ffd54f');
|
||||
const [highlightOpacity, setHighlightOpacity] = useState(60);
|
||||
const [freehandHighlighterWidth, setFreehandHighlighterWidth] = useState(6);
|
||||
const [underlineColor, setUnderlineColor] = useState('#ffb300');
|
||||
const [underlineOpacity, setUnderlineOpacity] = useState(100);
|
||||
const [strikeoutColor, setStrikeoutColor] = useState('#e53935');
|
||||
const [strikeoutOpacity, setStrikeoutOpacity] = useState(100);
|
||||
const [squigglyColor, setSquigglyColor] = useState('#00acc1');
|
||||
const [squigglyOpacity, setSquigglyOpacity] = useState(100);
|
||||
const [textColor, setTextColor] = useState('#111111');
|
||||
const [textSize, setTextSize] = useState(14);
|
||||
const [textAlignment, setTextAlignment] = useState<'left' | 'center' | 'right'>('left');
|
||||
const [textBackgroundColor, setTextBackgroundColor] = useState<string>('');
|
||||
const [noteBackgroundColor, setNoteBackgroundColor] = useState('#ffd54f');
|
||||
const [shapeStrokeColor, setShapeStrokeColor] = useState('#cf5b5b');
|
||||
const [shapeFillColor, setShapeFillColor] = useState('#0000ff');
|
||||
const [shapeOpacity, setShapeOpacity] = useState(50);
|
||||
const [shapeStrokeOpacity, setShapeStrokeOpacity] = useState(50);
|
||||
const [shapeFillOpacity, setShapeFillOpacity] = useState(50);
|
||||
const [shapeThickness, setShapeThickness] = useState(2);
|
||||
|
||||
const buildToolOptions = useCallback<BuildToolOptionsFn>(
|
||||
(toolId, extras) => {
|
||||
const includeMetadata = extras?.includeMetadata ?? true;
|
||||
const metadata = includeMetadata
|
||||
? {
|
||||
customData: {
|
||||
toolId,
|
||||
annotationToolId: toolId,
|
||||
source: 'annotate',
|
||||
author: 'User',
|
||||
createdAt: new Date().toISOString(),
|
||||
modifiedAt: new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
: {};
|
||||
|
||||
switch (toolId) {
|
||||
case 'ink':
|
||||
return { color: inkColor, thickness: inkWidth, ...metadata };
|
||||
case 'inkHighlighter':
|
||||
return {
|
||||
color: highlightColor,
|
||||
opacity: highlightOpacity / 100,
|
||||
thickness: freehandHighlighterWidth,
|
||||
...metadata,
|
||||
};
|
||||
case 'highlight':
|
||||
return { color: highlightColor, opacity: highlightOpacity / 100, ...metadata };
|
||||
case 'underline':
|
||||
return { color: underlineColor, opacity: underlineOpacity / 100, ...metadata };
|
||||
case 'strikeout':
|
||||
return { color: strikeoutColor, opacity: strikeoutOpacity / 100, ...metadata };
|
||||
case 'squiggly':
|
||||
return { color: squigglyColor, opacity: squigglyOpacity / 100, ...metadata };
|
||||
case 'text': {
|
||||
const textAlignNumber = textAlignment === 'left' ? 0 : textAlignment === 'center' ? 1 : 2;
|
||||
return {
|
||||
color: textColor,
|
||||
textColor: textColor,
|
||||
fontSize: textSize,
|
||||
textAlign: textAlignNumber,
|
||||
...(textBackgroundColor ? { fillColor: textBackgroundColor } : {}),
|
||||
...metadata,
|
||||
};
|
||||
}
|
||||
case 'note': {
|
||||
const noteFillColor = noteBackgroundColor || 'transparent';
|
||||
return {
|
||||
color: textColor,
|
||||
fillColor: noteFillColor,
|
||||
opacity: 1,
|
||||
...metadata,
|
||||
};
|
||||
}
|
||||
case 'square':
|
||||
case 'circle':
|
||||
case 'polygon':
|
||||
return {
|
||||
color: shapeFillColor,
|
||||
strokeColor: shapeStrokeColor,
|
||||
opacity: shapeOpacity / 100,
|
||||
strokeOpacity: shapeStrokeOpacity / 100,
|
||||
fillOpacity: shapeFillOpacity / 100,
|
||||
borderWidth: shapeThickness,
|
||||
...metadata,
|
||||
};
|
||||
case 'line':
|
||||
case 'polyline':
|
||||
case 'lineArrow':
|
||||
return {
|
||||
color: shapeStrokeColor,
|
||||
strokeColor: shapeStrokeColor,
|
||||
opacity: shapeStrokeOpacity / 100,
|
||||
borderWidth: shapeThickness,
|
||||
...metadata,
|
||||
};
|
||||
case 'stamp': {
|
||||
const pdfSize =
|
||||
extras?.stampImageSize && cssToPdfSize ? cssToPdfSize(extras.stampImageSize) : undefined;
|
||||
return {
|
||||
imageSrc: extras?.stampImageData,
|
||||
...(pdfSize ? { imageSize: pdfSize } : {}),
|
||||
...metadata,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return { ...metadata };
|
||||
}
|
||||
},
|
||||
[
|
||||
cssToPdfSize,
|
||||
freehandHighlighterWidth,
|
||||
highlightColor,
|
||||
highlightOpacity,
|
||||
inkColor,
|
||||
inkWidth,
|
||||
noteBackgroundColor,
|
||||
shapeFillColor,
|
||||
shapeFillOpacity,
|
||||
shapeOpacity,
|
||||
shapeStrokeColor,
|
||||
shapeStrokeOpacity,
|
||||
shapeThickness,
|
||||
squigglyColor,
|
||||
squigglyOpacity,
|
||||
strikeoutColor,
|
||||
strikeoutOpacity,
|
||||
textAlignment,
|
||||
textBackgroundColor,
|
||||
textColor,
|
||||
textSize,
|
||||
underlineColor,
|
||||
underlineOpacity,
|
||||
]
|
||||
);
|
||||
|
||||
const getActiveColor = useCallback(
|
||||
(target: string | null) => {
|
||||
if (target === 'ink') return inkColor;
|
||||
if (target === 'highlight' || target === 'inkHighlighter') return highlightColor;
|
||||
if (target === 'underline') return underlineColor;
|
||||
if (target === 'strikeout') return strikeoutColor;
|
||||
if (target === 'squiggly') return squigglyColor;
|
||||
if (target === 'shapeStroke') return shapeStrokeColor;
|
||||
if (target === 'shapeFill') return shapeFillColor;
|
||||
if (target === 'textBackground') return textBackgroundColor || '#ffffff';
|
||||
if (target === 'noteBackground') return noteBackgroundColor || '#ffffff';
|
||||
return textColor;
|
||||
},
|
||||
[
|
||||
highlightColor,
|
||||
inkColor,
|
||||
noteBackgroundColor,
|
||||
shapeFillColor,
|
||||
shapeStrokeColor,
|
||||
squigglyColor,
|
||||
strikeoutColor,
|
||||
textBackgroundColor,
|
||||
textColor,
|
||||
underlineColor,
|
||||
]
|
||||
);
|
||||
|
||||
const styleState: StyleState = useMemo(
|
||||
() => ({
|
||||
inkColor,
|
||||
inkWidth,
|
||||
highlightColor,
|
||||
highlightOpacity,
|
||||
freehandHighlighterWidth,
|
||||
underlineColor,
|
||||
underlineOpacity,
|
||||
strikeoutColor,
|
||||
strikeoutOpacity,
|
||||
squigglyColor,
|
||||
squigglyOpacity,
|
||||
textColor,
|
||||
textSize,
|
||||
textAlignment,
|
||||
textBackgroundColor,
|
||||
noteBackgroundColor,
|
||||
shapeStrokeColor,
|
||||
shapeFillColor,
|
||||
shapeOpacity,
|
||||
shapeStrokeOpacity,
|
||||
shapeFillOpacity,
|
||||
shapeThickness,
|
||||
}),
|
||||
[
|
||||
freehandHighlighterWidth,
|
||||
highlightColor,
|
||||
highlightOpacity,
|
||||
inkColor,
|
||||
inkWidth,
|
||||
noteBackgroundColor,
|
||||
shapeFillColor,
|
||||
shapeFillOpacity,
|
||||
shapeOpacity,
|
||||
shapeStrokeColor,
|
||||
shapeStrokeOpacity,
|
||||
shapeThickness,
|
||||
squigglyColor,
|
||||
squigglyOpacity,
|
||||
strikeoutColor,
|
||||
strikeoutOpacity,
|
||||
textAlignment,
|
||||
textBackgroundColor,
|
||||
textColor,
|
||||
textSize,
|
||||
underlineColor,
|
||||
underlineOpacity,
|
||||
]
|
||||
);
|
||||
|
||||
const styleActions: StyleActions = {
|
||||
setInkColor,
|
||||
setInkWidth,
|
||||
setHighlightColor,
|
||||
setHighlightOpacity,
|
||||
setFreehandHighlighterWidth,
|
||||
setUnderlineColor,
|
||||
setUnderlineOpacity,
|
||||
setStrikeoutColor,
|
||||
setStrikeoutOpacity,
|
||||
setSquigglyColor,
|
||||
setSquigglyOpacity,
|
||||
setTextColor,
|
||||
setTextSize,
|
||||
setTextAlignment,
|
||||
setTextBackgroundColor,
|
||||
setNoteBackgroundColor,
|
||||
setShapeStrokeColor,
|
||||
setShapeFillColor,
|
||||
setShapeOpacity,
|
||||
setShapeStrokeOpacity,
|
||||
setShapeFillOpacity,
|
||||
setShapeThickness,
|
||||
};
|
||||
|
||||
return {
|
||||
styleState,
|
||||
styleActions,
|
||||
buildToolOptions,
|
||||
getActiveColor,
|
||||
};
|
||||
};
|
||||
@@ -25,6 +25,7 @@ export const CORE_REGULAR_TOOL_IDS = [
|
||||
'ocr',
|
||||
'addImage',
|
||||
'rotate',
|
||||
'annotate',
|
||||
'scannerImageSplit',
|
||||
'editTableOfContents',
|
||||
'scannerEffect',
|
||||
|
||||
@@ -70,6 +70,8 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {
|
||||
'/scanner-image-split': 'scannerImageSplit',
|
||||
|
||||
// Annotation and content removal
|
||||
'/annotations': 'annotate',
|
||||
'/annotate': 'annotate',
|
||||
'/remove-annotations': 'removeAnnotations',
|
||||
'/remove-image': 'removeImage',
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export interface FileOpenService {
|
||||
getOpenedFiles(): Promise<string[]>;
|
||||
@@ -61,6 +60,8 @@ class TauriFileOpenService implements FileOpenService {
|
||||
|
||||
// Only import if in Tauri environment
|
||||
if (isTauri()) {
|
||||
const { listen } = await import('@tauri-apps/api/event');
|
||||
|
||||
// Check again after async import
|
||||
if (isCleanedUp) {
|
||||
return;
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { Suspense, lazy } from "react";
|
||||
import { Suspense } from "react";
|
||||
import { Routes, Route } from "react-router-dom";
|
||||
import { AppProviders } from "@app/components/AppProviders";
|
||||
import { AppLayout } from "@app/components/AppLayout";
|
||||
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
|
||||
|
||||
// Lazy-load auth routes - only loaded when user navigates to them
|
||||
const Landing = lazy(() => import("@app/routes/Landing"));
|
||||
const Login = lazy(() => import("@app/routes/Login"));
|
||||
const Signup = lazy(() => import("@app/routes/Signup"));
|
||||
const AuthCallback = lazy(() => import("@app/routes/AuthCallback"));
|
||||
const InviteAccept = lazy(() => import("@app/routes/InviteAccept"));
|
||||
|
||||
// Lazy-load Onboarding - only shown once for first-time users
|
||||
const Onboarding = lazy(() => import("@app/components/onboarding/Onboarding"));
|
||||
import Landing from "@app/routes/Landing";
|
||||
import Login from "@app/routes/Login";
|
||||
import Signup from "@app/routes/Signup";
|
||||
import AuthCallback from "@app/routes/AuthCallback";
|
||||
import InviteAccept from "@app/routes/InviteAccept";
|
||||
import Onboarding from "@app/components/onboarding/Onboarding";
|
||||
|
||||
// Import global styles
|
||||
import "@app/styles/tailwind.css";
|
||||
@@ -38,9 +34,7 @@ export default function App() {
|
||||
{/* Main app routes - Landing handles auth logic */}
|
||||
<Route path="/*" element={<Landing />} />
|
||||
</Routes>
|
||||
<Suspense fallback={null}>
|
||||
<Onboarding />
|
||||
</Suspense>
|
||||
<Onboarding />
|
||||
</AppLayout>
|
||||
</AppProviders>
|
||||
</Suspense>
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
import React, { lazy } from 'react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useConfigNavSections as useCoreConfigNavSections, createConfigNavSections as createCoreConfigNavSections, ConfigNavSection } from '@core/components/shared/config/configNavSections';
|
||||
|
||||
// Lazy load all config sections
|
||||
const PeopleSection = lazy(() => import('@app/components/shared/config/configSections/PeopleSection'));
|
||||
const TeamsSection = lazy(() => import('@app/components/shared/config/configSections/TeamsSection'));
|
||||
const AdminGeneralSection = lazy(() => import('@app/components/shared/config/configSections/AdminGeneralSection'));
|
||||
const AdminSecuritySection = lazy(() => import('@app/components/shared/config/configSections/AdminSecuritySection'));
|
||||
const AdminConnectionsSection = lazy(() => import('@app/components/shared/config/configSections/AdminConnectionsSection'));
|
||||
const AdminPrivacySection = lazy(() => import('@app/components/shared/config/configSections/AdminPrivacySection'));
|
||||
const AdminDatabaseSection = lazy(() => import('@app/components/shared/config/configSections/AdminDatabaseSection'));
|
||||
const AdminAdvancedSection = lazy(() => import('@app/components/shared/config/configSections/AdminAdvancedSection'));
|
||||
const AdminLegalSection = lazy(() => import('@app/components/shared/config/configSections/AdminLegalSection'));
|
||||
const AdminPlanSection = lazy(() => import('@app/components/shared/config/configSections/AdminPlanSection'));
|
||||
const AdminFeaturesSection = lazy(() => import('@app/components/shared/config/configSections/AdminFeaturesSection'));
|
||||
const AdminEndpointsSection = lazy(() => import('@app/components/shared/config/configSections/AdminEndpointsSection'));
|
||||
const AdminAuditSection = lazy(() => import('@app/components/shared/config/configSections/AdminAuditSection'));
|
||||
const AdminUsageSection = lazy(() => import('@app/components/shared/config/configSections/AdminUsageSection'));
|
||||
const ApiKeys = lazy(() => import('@app/components/shared/config/configSections/ApiKeys'));
|
||||
const AccountSection = lazy(() => import('@app/components/shared/config/configSections/AccountSection'));
|
||||
const GeneralSection = lazy(() => import('@app/components/shared/config/configSections/GeneralSection'));
|
||||
import PeopleSection from '@app/components/shared/config/configSections/PeopleSection';
|
||||
import TeamsSection from '@app/components/shared/config/configSections/TeamsSection';
|
||||
import AdminGeneralSection from '@app/components/shared/config/configSections/AdminGeneralSection';
|
||||
import AdminSecuritySection from '@app/components/shared/config/configSections/AdminSecuritySection';
|
||||
import AdminConnectionsSection from '@app/components/shared/config/configSections/AdminConnectionsSection';
|
||||
import AdminPrivacySection from '@app/components/shared/config/configSections/AdminPrivacySection';
|
||||
import AdminDatabaseSection from '@app/components/shared/config/configSections/AdminDatabaseSection';
|
||||
import AdminAdvancedSection from '@app/components/shared/config/configSections/AdminAdvancedSection';
|
||||
import AdminLegalSection from '@app/components/shared/config/configSections/AdminLegalSection';
|
||||
import AdminPlanSection from '@app/components/shared/config/configSections/AdminPlanSection';
|
||||
import AdminFeaturesSection from '@app/components/shared/config/configSections/AdminFeaturesSection';
|
||||
import AdminEndpointsSection from '@app/components/shared/config/configSections/AdminEndpointsSection';
|
||||
import AdminAuditSection from '@app/components/shared/config/configSections/AdminAuditSection';
|
||||
import AdminUsageSection from '@app/components/shared/config/configSections/AdminUsageSection';
|
||||
import ApiKeys from '@app/components/shared/config/configSections/ApiKeys';
|
||||
import AccountSection from '@app/components/shared/config/configSections/AccountSection';
|
||||
import GeneralSection from '@app/components/shared/config/configSections/GeneralSection';
|
||||
|
||||
/**
|
||||
* Hook version of proprietary config nav sections with proper i18n support
|
||||
|
||||
+1
-45
@@ -2,29 +2,6 @@ import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react-swc';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
import { viteStaticCopy } from 'vite-plugin-static-copy';
|
||||
import { visualizer } from "rollup-plugin-visualizer";
|
||||
import type { OutputBundle } from "rollup";
|
||||
|
||||
const maxChunkSize = 500;
|
||||
|
||||
function failOnLargeChunks(limitKb: number) {
|
||||
return {
|
||||
name: "fail-on-large-chunks",
|
||||
generateBundle(_: unknown, bundle: OutputBundle) {
|
||||
for (const [fileName, chunk] of Object.entries(bundle)) {
|
||||
if (chunk.type === "chunk") {
|
||||
const sizeKb = Buffer.byteLength(chunk.code) / 1024;
|
||||
|
||||
if (sizeKb > limitKb) {
|
||||
throw new Error(
|
||||
`❌ Chunk "${fileName}" is ${sizeKb.toFixed(1)} KB (limit: ${limitKb} KB)`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
// When DISABLE_ADDITIONAL_FEATURES is false (or unset), enable proprietary features
|
||||
@@ -40,10 +17,6 @@ export default defineConfig(({ mode }) => {
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
visualizer({
|
||||
open: true,
|
||||
filename: "stats.html"
|
||||
}),
|
||||
react(),
|
||||
tsconfigPaths({
|
||||
projects: [tsconfigProject],
|
||||
@@ -56,25 +29,8 @@ export default defineConfig(({ mode }) => {
|
||||
dest: 'pdfium'
|
||||
}
|
||||
]
|
||||
}),
|
||||
failOnLargeChunks(maxChunkSize),
|
||||
})
|
||||
],
|
||||
build: {
|
||||
chunkSizeWarningLimit: maxChunkSize,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
// Manual chunks for better code splitting
|
||||
manualChunks: {
|
||||
// Large UI libraries
|
||||
'vendor-ui': ['@mantine/core', '@mantine/hooks', '@mantine/dates', '@mantine/dropzone'],
|
||||
// React and related
|
||||
'vendor-react': ['react', 'react-dom', 'react-router-dom'],
|
||||
// Other large dependencies
|
||||
'vendor-utils': ['jszip'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
// make sure this port matches the devUrl port in tauri.conf.json file
|
||||
|
||||
Reference in New Issue
Block a user