Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

UI redesign staging (#6149)

EthanHealy01c731d5fd5d69
diff --git a/AGENTS.md b/AGENTS.md
index a90ceecb5a..fa0340c276 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -183,26 +183,26 @@ Use this pattern for desktop-specific or proprietary-specific features WITHOUT r
**Example - Desktop-specific footer:**
```typescript
-// core/components/rightRail/RightRailFooterExtensions.tsx (stub)
-interface RightRailFooterExtensionsProps {
+// core/components/workbenchBar/WorkbenchBarFooterExtensions.tsx (stub)
+interface WorkbenchBarFooterExtensionsProps {
className?: string;
}
-export function RightRailFooterExtensions(_props: RightRailFooterExtensionsProps) {
+export function WorkbenchBarFooterExtensions(_props: WorkbenchBarFooterExtensionsProps) {
return null; // Stub - does nothing in web builds
}
```
```tsx
-// desktop/components/rightRail/RightRailFooterExtensions.tsx (real implementation)
+// desktop/components/workbenchBar/WorkbenchBarFooterExtensions.tsx (real implementation)
import { Box } from '@mantine/core';
import { BackendHealthIndicator } from '@app/components/BackendHealthIndicator';
-interface RightRailFooterExtensionsProps {
+interface WorkbenchBarFooterExtensionsProps {
className?: string;
}
-export function RightRailFooterExtensions({ className }: RightRailFooterExtensionsProps) {
+export function WorkbenchBarFooterExtensions({ className }: WorkbenchBarFooterExtensionsProps) {
return (
<Box className={className}>
<BackendHealthIndicator />
@@ -212,15 +212,15 @@ export function RightRailFooterExtensions({ className }: RightRailFooterExtensio
```
```tsx
-// core/components/shared/RightRail.tsx (usage - works in ALL builds)
-import { RightRailFooterExtensions } from '@app/components/rightRail/RightRailFooterExtensions';
+// core/components/shared/WorkbenchBar.tsx (usage - works in ALL builds)
+import { WorkbenchBarFooterExtensions } from '@app/components/workbenchBar/WorkbenchBarFooterExtensions';
-export function RightRail() {
+export function WorkbenchBar() {
return (
<div>
{/* In web builds: renders nothing (stub returns null) */}
{/* In desktop builds: renders BackendHealthIndicator */}
- <RightRailFooterExtensions className="right-rail-footer" />
+ <WorkbenchBarFooterExtensions className="workbench-bar-footer" />
</div>
);
}
diff --git a/frontend/.prettierignore b/frontend/.prettierignore
index 3ad5fb2f0b..f4812a8f1f 100644
--- a/frontend/.prettierignore
+++ b/frontend/.prettierignore
@@ -2,6 +2,8 @@ dist/
# Tauri/Cargo build output (binary assets named *.js etc. confuse Prettier)
src-tauri/target/
node_modules/
+src-tauri/target/
+src-tauri/gen/
public/vendor/
public/pdfjs*/
public/js/thirdParty/
diff --git a/frontend/public/locales/en-GB/translation.toml b/frontend/public/locales/en-GB/translation.toml
index 9dc9a8915a..5ae0cfc435 100644
--- a/frontend/public/locales/en-GB/translation.toml
+++ b/frontend/public/locales/en-GB/translation.toml
@@ -52,8 +52,8 @@ exportAndContinue = "Export & Continue"
false = "False"
fileNotSavedToDisk = "Not saved to disk"
fileSavedToDisk = "File saved to disk"
-fileSelected = "Selected: {{filename}}"
-filesSelected = "{{count}} files selected"
+fileSelected = "{{filename}}"
+filesSelected = "{{count}} files"
font = "Font"
fontSizeTooltip = "Size of the page number text in points. Larger numbers create bigger text."
fontTypeTooltip = "Font family for the page numbers. Choose based on your document style."
@@ -82,7 +82,7 @@ multiPdfPrompt = "Select PDFs (2+)"
never = "Never"
no = "No"
noFavourites = "No favourites added"
-noFileSelected = "No file selected. Please upload one."
+noFileSelected = "No file loaded. Please upload one."
noFilesToUndo = "Cannot undo: no files were processed in the last operation"
noOperationToUndo = "No operation to undo"
notAuthenticatedMessage = "User not authenticated."
@@ -1460,14 +1460,14 @@ inactive = "Inactive"
[adminOnboarding]
adminTools = "Finally, we have advanced administration tools like <strong>Auditing</strong> to track system activity and <strong>Usage Analytics</strong> to monitor how your users interact with the platform."
-configButton = "Click the <strong>Config</strong> button to access all system settings and administrative controls."
+configButton = "Open <strong>Settings</strong> to access all system configuration and administrative controls."
connectionsSection = "The <strong>Connections</strong> section supports various login methods including custom SSO and SAML providers like Google and GitHub, plus email integrations for notifications and communications."
databaseSection = "For advanced production environments, we have settings to allow <strong>external database hookups</strong> so you can integrate with your existing infrastructure."
settingsOverview = "This is the <strong>Settings Panel</strong>. Admin settings are organised by category for easy navigation."
systemCustomization = "We have extensive ways to customise the UI: <strong>System Settings</strong> let you change the app name and languages, <strong>Features</strong> allows server certificate management, and <strong>Endpoints</strong> lets you enable or disable specific tools for your users."
teamsAndUsers = "Manage <strong>Teams</strong> and individual users here. You can invite new users via email, shareable links, or create custom accounts for them yourself."
welcome = "Welcome to the <strong>Admin Tour</strong>! Let's explore the powerful enterprise features and settings available to system administrators."
-wrapUp = "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. Access this tour anytime from the <strong>Help</strong> menu."
+wrapUp = "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. You can replay it anytime — just open <strong>Settings</strong> and find it here in the <strong>Tours</strong> section under Help."
[adminUserSettings]
actions = "Actions"
@@ -2728,6 +2728,7 @@ used = "used"
[compare]
addFilesHint = "Add PDFs in the Files step to enable selection."
clearSelected = "Clear selected"
+clearSlot = "Remove file"
cta = "Compare"
header = "Compare PDFs"
loading = "Comparing..."
@@ -2753,7 +2754,7 @@ label = "Original document"
placeholder = "Select the original PDF"
[compare.clear]
-confirm = "Clear and return"
+confirm = "Clear Selected"
confirmBody = "This will close the current comparison and take you back to Active Files."
confirmTitle = "Clear selected PDFs?"
@@ -2779,6 +2780,7 @@ title = "These PDFs look highly different"
[compare.edited]
label = "Edited PDF"
+selectBaseFirst = "Select original PDF first"
placeholder = "Select the edited PDF"
[compare.error]
@@ -2860,6 +2862,7 @@ pageLabel = "Page"
[compare.swap]
confirm = "Swap and Re-run"
+label = "Swap"
confirmBody = "This will rerun the tool. Are you sure you want to swap the order of Original and Edited?"
confirmTitle = "Re-run comparison?"
@@ -3109,7 +3112,7 @@ maintainAspectRatio = "Maintain Aspect Ratio"
markdown = "Markdown"
maxAttachmentSize = "Maximum attachment size (MB)"
multiple = "Multiple"
-noFileSelected = "No file selected. Use the file panel to add files."
+noFileSelected = "No file loaded. Use the file panel to add files."
odpExt = "OpenDocument Presentation (.odp)"
odtExt = "OpenDocument Text (.odt)"
officeDocs = "Office Documents (Word, Excel, PowerPoint)"
@@ -3130,9 +3133,9 @@ pdfxDigitalSignatureWarning = "The PDF contains a digital signature. This will b
pptExt = "PowerPoint (.pptx)"
results = "Results"
rtfExt = "Rich Text Format (.rtf)"
-selectedFiles = "Selected files"
-selectFilesPlaceholder = "Select files in the main view to get started"
-selectSourceFormatFirst = "Select a source format first"
+selectedFiles = "Active files"
+selectFilesPlaceholder = "Add files to the workbench to get started"
+selectSourceFormatFirst = "Choose a source format first"
settings = "Settings"
single = "Single"
sourceFormatPlaceholder = "Source format"
@@ -3287,7 +3290,7 @@ forRegularWork = "For regular PDF work:"
[crop]
autoCrop = "Auto-crop whitespace"
header = "Crop PDF"
-noFileSelected = "Select a PDF file to begin cropping"
+noFileSelected = "Add a PDF file to begin cropping"
reset = "Reset to full PDF"
submit = "Apply Crop"
title = "Crop"
@@ -3492,6 +3495,8 @@ unlockAll = "Use for all ({{count}})"
unlockAllPartialFail = "Wrong password for: {{names}}"
unlockAllSuccess = "Unlocked {{count}} file(s)."
unlockPrompt = "Unlock PDF to continue"
+viewerLocked = "This PDF is password-protected"
+viewerUnlock = "Unlock"
[encryptedPdfUnlock.password]
label = "PDF password"
@@ -3599,25 +3604,29 @@ or = "or"
[fileEditor]
addFiles = "Add Files"
+pageCount = "{{count}} pages"
+pageCount_one = "{{count}} page"
+pageCount_other = "{{count}} pages"
[fileManager]
active = "Active"
addToUpload = "Add to Upload"
changesNotUploaded = "Changes not uploaded"
clearAll = "Clear All"
-clearSelection = "Clear Selection"
+clearSelection = "Clear"
clickToUpload = "Click to upload files"
+closeAllFiles = "Close all files"
closeFile = "Close File"
cloudFile = "Cloud file"
copyCreated = "Copy saved to this device."
copyFailed = "Could not create a copy."
delete = "Delete"
deleteAll = "Delete All"
-deleteSelected = "Delete Selected"
-deselectAll = "Deselect All"
+deleteSelected = "Delete Files"
+deselectAll = "Uncheck All"
details = "File Details"
download = "Download"
-downloadSelected = "Download Selected"
+downloadSelected = "Download Files"
dragDrop = "Drag & Drop files here"
dropFilesHere = "Drop files here"
failedToLoad = "Failed to load file to active set."
@@ -3626,7 +3635,7 @@ fileFormat = "Format"
fileHistory = "File History"
fileName = "Name"
fileSize = "Size"
-filesSelected = "files selected"
+filesSelected = "files"
filesStored = "files stored"
fileVersion = "Version"
filterAll = "All"
@@ -3652,7 +3661,7 @@ mobileUpload = "Mobile Upload"
mobileUploadNotAvailable = "Mobile upload not enabled"
myFiles = "My Files"
noFiles = "No files available"
-noFileSelected = "No files selected"
+noFileSelected = "No files chosen"
noFilesFound = "No files found matching your search"
noRecentFiles = "No recent files found"
openFile = "Open File"
@@ -3675,18 +3684,19 @@ removeSharedPrompt = "This file is shared with you. You can remove it from this
removeSharedServerOnlyBlockedPrompt = "This file is shared with you and stored only on the server."
removeSharedServerOnlyPrompt = "This file is shared with you and stored only on the server. Remove it from your list?"
restore = "Restore"
-saveSelected = "Save Selected"
+saveSelected = "Save Files"
searchFiles = "Search files..."
-selectAll = "Select All"
-selectedCount = "{{count}} selected"
-selectedFiles = "Selected Files"
+selectAll = "Check All"
+selectedCount = "{{count}} checked"
+selectedFiles = "Files Added"
share = "Share"
+shared = "Shared"
sharedByYou = "Shared by you"
sharedEditNoticeBody = "You do not have edit rights to the server version of this file. Any edits you make will be saved as a local copy."
sharedEditNoticeConfirm = "Got it"
sharedEditNoticeTitle = "Read-only server copy"
sharedWithYou = "Shared with you"
-shareSelected = "Share Selected"
+shareSelected = "Share Files"
sharing = "Sharing"
showAll = "Show All"
showHistory = "Show History"
@@ -3703,24 +3713,59 @@ supportMessage = "Powered by browser database storage for unlimited capacity"
synced = "Synced"
title = "Upload PDF Files"
toolChain = "Tools Applied"
-totalSelected = "Total Selected"
+totalSelected = "Total Files"
unsupported = "Unsupported"
unzip = "Unzip"
updateOnServer = "Update on Server"
uploadError = "Failed to upload some files."
-uploadSelected = "Upload Selected"
+uploadSelected = "Upload Files"
uploadToServer = "Upload to Server"
[files]
addFiles = "Add files"
created = "Created"
-selectFromWorkbench = "Select files from the workbench or "
-selectMultipleFromWorkbench = "Select at least {{count}} files from the workbench or "
+selectFromWorkbench = "Add files to the workbench or "
+selectMultipleFromWorkbench = "Add at least {{count}} files to the workbench or "
size = "File Size"
title = "Files"
upload = "Upload"
uploadFiles = "Upload Files"
+[fileSelectorPicker]
+empty = "No files available"
+placeholder = "Select file"
+search = "Filter files…"
+tabListLabel = "Saved files, workbench, upload"
+upload = "Upload from computer"
+
+[fileSelectorPicker.sort]
+dateAsc = "Oldest first"
+dateDesc = "Newest first"
+dateLabel = "Latest"
+nameAsc = "A to Z"
+nameDesc = "Z to A"
+nameLabel = "A–Z"
+
+[fileSelectorPicker.tabs]
+saved = "Saved files"
+upload = "Upload"
+workbench = "Workbench"
+
+[fileSidebar]
+addFiles = "Add files"
+collapse = "Collapse sidebar"
+dropHint = "Open files to get started"
+expand = "Expand sidebar"
+files = "Files"
+googleDrive = "Google Drive"
+googleDriveDisabled = "Google Drive is not configured"
+noFiles = "No files yet"
+openFileManager = "Open file manager"
+openFromComputer = "Open from computer"
+openSettings = "Open settings"
+search = "Search"
+searchPlaceholder = "Search files..."
+
[fileToPDF]
credit = "This service uses LibreOffice and Unoconv for file conversion."
header = "Convert any file to PDF"
@@ -4592,7 +4637,7 @@ goToFileEditor = "Go to file editor"
submit = "Merge"
tags = "merge,Page operations,Back end,server side"
title = "Merge"
-viewerModeHint = "Merge needs 2 or more files. Head to the file editor to select them."
+viewerModeHint = "Merge needs 2 or more files. Head to the file editor to add them."
[merge.error]
failed = "An error occurred while merging the PDFs."
@@ -4615,7 +4660,7 @@ title = "Remove Digital Signature"
ascending = "Ascending"
dateModified = "Date Modified"
descending = "Descending"
-description = "Files will be merged in the order they're selected. Drag to reorder or sort below."
+description = "Files will be merged in the order shown. Drag to reorder or sort below."
filename = "File Name"
label = "Sort By"
sort = "Sort"
@@ -4859,7 +4904,7 @@ toolInterface = "This is the <strong>Crop</strong> tool interface. As you can se
viewer = "The <strong>Viewer</strong> lets you read and annotate your PDFs."
viewSwitcher = "Use these controls to select how you want to view your PDFs."
workbench = "This is the <strong>Workbench</strong> - the main area where you view and edit your PDFs."
-wrapUp = "You're all set! You've learnt about the main areas of the app and how to use them. Click the <strong>Help</strong> button whenever you like to see this tour again."
+wrapUp = "You're all set! You can replay this tour anytime — just open <strong>Settings</strong> and find it here in the <strong>Tours</strong> section under Help."
[onboarding.buttons]
back = "Back"
@@ -4924,7 +4969,6 @@ fileUpload = "Use the <strong>Files</strong> button to upload or pick a recent P
leftPanel = "The left <strong>Tools</strong> panel lists everything you can do. Browse categories or search to find a tool quickly."
pageEditorView = "Switch to the Page Editor to reorder, rotate, or delete pages."
quickAccess = "Start at the <strong>Quick Access</strong> rail to jump between Reader, Automate, your files, and all the tours."
-rightRail = "The <strong>Right Rail</strong> holds quick actions to select files, change theme or language, and download results."
topBar = "The top bar lets you swap between <strong>Viewer</strong>, <strong>Page Editor</strong>, and <strong>Active Files</strong>."
wrapUp = "That is what is new in V2. Open the <strong>Tours</strong> menu anytime to replay this, the Tools tour, or the Admin tour."
@@ -4996,8 +5040,8 @@ text = "Foreground places the overlay on top of the page. Background places it b
title = "Overlay Position"
[pageEdit]
-deselectAll = "Select None"
-selectAll = "Select All"
+deselectAll = "None"
+selectAll = "Check All"
[pageEditor]
actualSize = "Actual Size"
@@ -6525,9 +6569,10 @@ title = "High Contrast"
text = "Completely invert all colours in the PDF, creating a negative-like effect. Useful for creating dark mode versions of documents or reducing eye strain in low-light conditions."
title = "Invert All Colours"
-[rightRail]
+[workbenchBar]
annotations = "Annotations"
applyRedactionsFirst = "Apply redactions first"
+closeAll = "Close All Files"
closePdf = "Close PDF"
closeSelected = "Close Selected Files"
deleteSelected = "Delete Selected Pages"
@@ -6557,6 +6602,7 @@ search = "Search PDF"
selectAll = "Select All"
selectByNumber = "Select by Page Numbers"
selectLanguage = "Select language"
+share = "Share"
toggleAnnotations = "Toggle Annotations Visibility"
toggleAttachments = "Toggle Attachments"
toggleBookmarks = "Toggle Bookmarks"
@@ -6564,6 +6610,9 @@ toggleComments = "Comments"
toggleLayers = "Toggle Layers"
toggleSidebar = "Toggle Sidebar"
toggleTheme = "Toggle Theme"
+activeFiles = "Active Files"
+multiTool = "Multi-Tool"
+viewer = "Viewer"
[rotate]
rotateLeft = "Rotate Anticlockwise"
@@ -6797,7 +6846,7 @@ defaultPdfEditorChecking = "Checking..."
defaultPdfEditorInactive = "Another application is set as default"
defaultPdfEditorSet = "Already Default"
defaultStartupView = "Default view on launch"
-defaultStartupViewDescription = "Choose which tab is active in the left column when the app starts"
+defaultStartupViewDescription = "Choose which view is active when the app starts"
defaultToolPickerMode = "Default tool picker mode"
defaultToolPickerModeDescription = "Choose whether the tool picker opens in fullscreen or sidebar by default"
defaultViewerZoom = "Default reader zoom"
@@ -6807,8 +6856,14 @@ hideUnavailableConversions = "Hide unavailable conversions"
hideUnavailableConversionsDescription = "Remove disabled conversion options in the Convert tool instead of showing them greyed out."
hideUnavailableTools = "Hide unavailable tools"
hideUnavailableToolsDescription = "Remove tools that have been disabled by your server instead of showing them greyed out."
+language = "Language"
+languageDescription = "Choose the display language"
logout = "Log out"
setAsDefault = "Set as Default"
+theme = "Theme"
+themeDark = "Dark"
+themeDescription = "Switch between light and dark mode"
+themeLight = "Light"
title = "General"
user = "User"
@@ -6983,6 +7038,20 @@ title = "Team"
enableLoginFirst = "Enable login mode first"
requiresEnterprise = "Requires Enterprise license"
+[settings.help]
+label = "Tours"
+title = "Help"
+
+[settings.help.adminTour]
+description = "Explore team management, system settings, and enterprise features."
+start = "Start"
+title = "Admin Tour"
+
+[settings.help.toolsTour]
+description = "Walk through uploading files, picking a tool, and reviewing results."
+start = "Start"
+title = "Tools Tour"
+
[settings.workspace]
people = "People"
teams = "Teams"
@@ -7580,8 +7649,8 @@ accessLimitedCommenter = "Comment access is coming soon. Ask the owner for edito
accessLimitedTitle = "Limited access"
accessLimitedViewer = "This link is view-only. Ask the owner for editor access if you need to download."
addUser = "Add"
-bulkDescription = "Create one link to share all selected files with signed-in users."
-bulkTitle = "Share selected files"
+bulkDescription = "Create one link to share all checked files with signed-in users."
+bulkTitle = "Share checked files"
commenterHint = "Commenting is coming soon."
copied = "Link copied to clipboard"
copy = "Copy"
@@ -7600,7 +7669,7 @@ errorTitle = "Share failed"
expiredBody = "This share link is invalid or has expired."
expiredTitle = "Link expired"
failure = "Unable to generate a share link. Please try again."
-fileCount = "{{count}} files selected"
+fileCount = "{{count}} files"
fileLabel = "File"
generate = "Generate Link"
generated = "Share link generated"
@@ -7656,12 +7725,12 @@ viewed = "Viewed"
viewsCount = "Views: {{count}}"
[storageUpload]
-bulkDescription = "This uploads the selected files to your server storage."
-bulkTitle = "Upload selected files"
+bulkDescription = "This uploads the checked files to your server storage."
+bulkTitle = "Upload checked files"
description = "This uploads the current file to server storage for your own access."
errorTitle = "Upload failed"
failure = "Upload failed. Please check your login and storage settings."
-fileCount = "{{count}} files selected"
+fileCount = "{{count}} files"
fileLabel = "File"
hint = "Public links and access modes are controlled by your server settings."
more = " +{{count}} more"
@@ -7821,19 +7890,26 @@ settings = "Settings"
[tool]
endpointUnavailable = "This tool is unavailable on your server."
endpointUnavailableClickable = "Not available in this mode. Click to sign in."
+filesLoading = "Files are still loading, please wait."
+filesLoadingProgress = "{{loaded}} / {{total}} files loading..."
invalidParams = "Fill in the required settings."
noFiles = "Add a file to get started."
scopeFiles = "files"
scopeThisFile = "this file"
selectFilesHint = "Select files in Active Files to run this tool"
singleFileScope = "Only applying to: {{fileName}}"
-viewerMode = "Switch to the file editor to select multiple files."
+viewerMode = "Switch to the file editor to add multiple files."
[toolPanel]
+allTools = "All tools"
alpha = "Alpha"
+backToTools = "Back to tools"
+collapse = "Collapse panel"
comingSoon = "Coming soon:"
+expand = "Expand panel"
placeholder = "Choose a tool to get started"
premiumFeature = "Premium feature:"
+search = "Search tools"
[toolPanel.fullscreen]
comingSoon = "Coming soon:"
@@ -8384,6 +8460,7 @@ bullet3 = "Image will be resized to fit signature area"
description = "Upload a pre-created signature image. Ideal if you have a scanned signature or company logo."
title = "Upload Signature Image"
+
[workspace]
title = "Workspace"
diff --git a/frontend/src/core/components/AppLayout.tsx b/frontend/src/core/components/AppLayout.tsx
index ca26374345..1f0e969777 100644
--- a/frontend/src/core/components/AppLayout.tsx
+++ b/frontend/src/core/components/AppLayout.tsx
@@ -16,8 +16,7 @@ export function AppLayout({ children }: AppLayoutProps) {
return (
<>
<style>{`
- .h-screen,
- .right-rail {
+ .h-screen {
height: 100% !important;
}
`}</style>
diff --git a/frontend/src/core/components/AppProviders.tsx b/frontend/src/core/components/AppProviders.tsx
index c32b00c401..4f6f5566a5 100644
--- a/frontend/src/core/components/AppProviders.tsx
+++ b/frontend/src/core/components/AppProviders.tsx
@@ -17,7 +17,7 @@ import {
AppConfigRetryOptions,
useAppConfig,
} from "@app/contexts/AppConfigContext";
-import { RightRailProvider } from "@app/contexts/RightRailContext";
+import { WorkbenchBarProvider } from "@app/contexts/WorkbenchBarContext";
import { ViewerProvider } from "@app/contexts/ViewerContext";
import { SignatureProvider } from "@app/contexts/SignatureContext";
import { AnnotationProvider } from "@app/contexts/AnnotationContext";
@@ -139,13 +139,13 @@ export function AppProviders({
<RedactionProvider>
<FormFillProvider>
<AnnotationProvider>
- <RightRailProvider>
+ <WorkbenchBarProvider>
<TourOrchestrationProvider>
<AdminTourOrchestrationProvider>
{children}
</AdminTourOrchestrationProvider>
</TourOrchestrationProvider>
- </RightRailProvider>
+ </WorkbenchBarProvider>
</AnnotationProvider>
</FormFillProvider>
</RedactionProvider>
diff --git a/frontend/src/core/components/FileManager.tsx b/frontend/src/core/components/FileManager.tsx
index 0b56ddbb6c..ea54093dcd 100644
--- a/frontend/src/core/components/FileManager.tsx
+++ b/frontend/src/core/components/FileManager.tsx
@@ -2,6 +2,7 @@ import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Modal } from "@mantine/core";
import { Dropzone } from "@mantine/dropzone";
import { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
import { useFileManager } from "@app/hooks/useFileManager";
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
import { useAppConfig } from "@app/contexts/AppConfigContext";
@@ -17,6 +18,7 @@ import {
} from "@app/services/googleDrivePickerService";
import { loadScript } from "@app/utils/scriptLoader";
import { useAllFiles } from "@app/contexts/FileContext";
+import { useFileActions } from "@app/contexts/file/fileHooks";
interface FileManagerProps {
selectedTool?: Tool | null;
@@ -28,6 +30,7 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
closeFilesModal,
onFileUpload,
onRecentFileSelect,
+ maxSelectable,
} = useFilesModalContext();
const { config } = useAppConfig();
const [recentFiles, setRecentFiles] = useState<StirlingFileStub[]>([]);
@@ -35,6 +38,7 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
const [isMobile, setIsMobile] = useState(false);
const { loadRecentFiles, handleRemoveFile, loading } = useFileManager();
+ const { actions: fileActions } = useFileActions();
// Get active file IDs from FileContext to show which files are already loaded
const { fileIds: activeFileIds } = useAllFiles();
@@ -83,11 +87,24 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
const handleRemoveFileByIndex = useCallback(
async (index: number) => {
- await handleRemoveFile(index, recentFiles, setRecentFiles);
+ await handleRemoveFile(
+ index,
+ recentFiles,
+ setRecentFiles,
+ (fileId) => {
+ fileActions.removeFiles([fileId], false);
+ },
+ refreshRecentFiles,
+ );
},
- [handleRemoveFile, recentFiles],
+ [handleRemoveFile, recentFiles, fileActions, refreshRecentFiles],
);
+ const handleBulkRemove = useCallback((fileIds: FileId[]) => {
+ const idSet = new Set(fileIds as string[]);
+ setRecentFiles((prev) => prev.filter((f) => !idSet.has(f.id as string)));
+ }, []);
+
useEffect(() => {
const checkMobile = () => setIsMobile(window.innerWidth < 1030);
checkMobile();
@@ -211,7 +228,9 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
onClose={closeFilesModal}
isFileSupported={isFileSupported}
isOpen={isFilesModalOpen}
+ maxSelectable={maxSelectable}
onFileRemove={handleRemoveFileByIndex}
+ onBulkRemove={handleBulkRemove}
modalHeight={modalHeight}
refreshRecentFiles={refreshRecentFiles}
isLoading={loading}
diff --git a/frontend/src/core/components/fileEditor/AddFileCard.tsx b/frontend/src/core/components/fileEditor/AddFileCard.tsx
index 7a566b032a..5fc62680b3 100644
--- a/frontend/src/core/components/fileEditor/AddFileCard.tsx
+++ b/frontend/src/core/components/fileEditor/AddFileCard.tsx
@@ -1,7 +1,6 @@
import React, { useRef, useState } from "react";
import { Button, Group } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import AddIcon from "@mui/icons-material/Add";
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
import LocalIcon from "@app/components/shared/LocalIcon";
import { Wordmark } from "@app/components/shared/Wordmark";
@@ -69,7 +68,7 @@ const AddFileCard = ({
/>
<div
- className={`${styles.addFileCard} w-[18rem] h-[22rem] select-none flex flex-col shadow-sm transition-all relative cursor-pointer`}
+ className={`${styles.addFileCard} select-none flex flex-col transition-all relative cursor-pointer`}
tabIndex={0}
role="button"
aria-label={t("fileEditor.addFiles", "Add files")}
@@ -81,17 +80,6 @@ const AddFileCard = ({
}
}}
>
- {/* Header bar - matches FileEditorThumbnail structure */}
- <div className={`${styles.header} ${styles.addFileHeader}`}>
- <div className={styles.logoMark}>
- <AddIcon sx={{ color: "inherit", fontSize: "1.5rem" }} />
- </div>
- <div className={styles.headerIndex}>
- {t("fileEditor.addFiles", "Add Files")}
- </div>
- <div className={styles.kebab} />
- </div>
-
{/* Main content area */}
<div className={styles.addFileContent}>
{/* Stirling PDF Branding */}
diff --git a/frontend/src/core/components/fileEditor/FileEditor.module.css b/frontend/src/core/components/fileEditor/FileEditor.module.css
index 43ef0d1af9..2e601f8f7f 100644
--- a/frontend/src/core/components/fileEditor/FileEditor.module.css
+++ b/frontend/src/core/components/fileEditor/FileEditor.module.css
@@ -328,42 +328,33 @@
========================= */
.addFileCard {
+ width: 260px;
+ max-width: 260px;
+ height: calc(310px - 0.5rem);
+ margin: 0.5rem auto 0;
background: var(--file-card-bg);
- border: 2px dashed var(--border-default);
- border-radius: 0.0625rem;
+ border: 1.5px solid var(--border-default);
+ border-radius: 12px;
+ box-shadow: var(--shadow-md);
cursor: pointer;
- transition: all 0.18s ease;
- max-width: 100%;
- max-height: 100%;
+ transition:
+ box-shadow 0.18s ease,
+ transform 0.2s ease,
+ border-color 0.18s ease;
overflow: hidden;
- margin-left: 0.5rem;
- margin-right: 0.5rem;
- opacity: 0.7;
}
.addFileCard:hover {
- opacity: 1;
- border-color: var(--color-blue-500);
- box-shadow: var(--shadow-md);
- transform: translateY(-2px);
+ box-shadow: var(--shadow-lg);
+ transform: translateY(-1px);
+ border-color: var(--accent-interactive);
}
-.addFileCard:focus {
- outline: 2px solid var(--color-blue-500);
+.addFileCard:focus-visible {
+ outline: 2px solid var(--accent-interactive);
outline-offset: 2px;
}
-.addFileHeader {
- background: var(--bg-subtle);
- color: var(--text-secondary);
- border-bottom: 1px solid var(--border-default);
-}
-
-.addFileCard:hover .addFileHeader {
- background: var(--color-blue-500);
- color: white;
-}
-
.addFileContent {
flex: 1;
display: flex;
diff --git a/frontend/src/core/components/fileEditor/FileEditor.tsx b/frontend/src/core/components/fileEditor/FileEditor.tsx
index c24f632b38..3ddd5ca403 100644
--- a/frontend/src/core/components/fileEditor/FileEditor.tsx
+++ b/frontend/src/core/components/fileEditor/FileEditor.tsx
@@ -1,13 +1,12 @@
-import { useState, useCallback, useRef, useMemo, useEffect } from "react";
+import { useState, useCallback, useMemo, useEffect } from "react";
import { flushSync } from "react-dom";
-import { Text, Center, Box, LoadingOverlay, Stack } from "@mantine/core";
+import { Center, Box, LoadingOverlay } from "@mantine/core";
import { Dropzone } from "@mantine/dropzone";
import {
useFileSelection,
useFileState,
useFileManagement,
useFileActions,
- useFileContext,
} from "@app/contexts/FileContext";
import { useNavigationActions } from "@app/contexts/NavigationContext";
import { useViewer } from "@app/contexts/ViewerContext";
@@ -19,7 +18,6 @@ import FilePickerModal from "@app/components/shared/FilePickerModal";
import { FileId, StirlingFile } from "@app/types/fileContext";
import { alert } from "@app/components/toast";
import { downloadFile } from "@app/services/downloadService";
-import { useFileEditorRightRailButtons } from "@app/components/fileEditor/fileEditorRightRailButtons";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
interface FileEditorProps {
@@ -46,17 +44,13 @@ const FileEditor = ({
const { state, selectors } = useFileState();
const { addFiles, removeFiles, reorderFiles } = useFileManagement();
const { actions: fileActions } = useFileActions();
- const { actions: fileContextActions } = useFileContext();
- const { clearAllFileErrors } = fileContextActions;
+ const { selectedFileIds, setSelectedFiles } = useFileSelection();
// Extract needed values from state (memoized to prevent infinite loops)
const activeStirlingFileStubs = useMemo(
() => selectors.getStirlingFileStubs(),
[state.files.byId, state.files.ids],
);
- const selectedFileIds = state.ui.selectedFileIds;
- const totalItems = state.files.ids.length;
- const selectedCount = selectedFileIds.length;
// Get navigation actions
const { actions: navActions } = useNavigationActions();
@@ -64,9 +58,6 @@ const FileEditor = ({
// Get viewer context for setting active file index and ID
const { setActiveFileIndex, setActiveFileId } = useViewer();
- // Get file selection context
- const { setSelectedFiles } = useFileSelection();
-
const [_status, _setStatus] = useState<string | null>(null);
const [_error, _setError] = useState<string | null>(null);
@@ -93,7 +84,6 @@ const FileEditor = ({
expandable: true,
});
}, []);
- const [selectionMode, setSelectionMode] = useState(toolMode);
// Current tool (for enforcing maxFiles limits)
const { selectedTool } = useToolWorkflow();
@@ -104,65 +94,7 @@ const FileEditor = ({
return !toolMode || rawMax == null || rawMax < 0 ? Infinity : rawMax;
}, [selectedTool?.maxFiles, toolMode]);
- // Enable selection mode automatically in tool mode
- useEffect(() => {
- if (toolMode) {
- setSelectionMode(true);
- }
- }, [toolMode]);
const [showFilePickerModal, setShowFilePickerModal] = useState(false);
- // Get selected file IDs from context (defensive programming)
- const contextSelectedIds = Array.isArray(selectedFileIds)
- ? selectedFileIds
- : [];
-
- // Create refs for frequently changing values to stabilize callbacks
- const contextSelectedIdsRef = useRef<FileId[]>([]);
- contextSelectedIdsRef.current = contextSelectedIds;
-
- // Use activeStirlingFileStubs directly - no conversion needed
- const localSelectedIds = contextSelectedIds;
-
- const handleSelectAllFiles = useCallback(() => {
- // Respect maxAllowed: if limited, select the last N files
- const allIds = state.files.ids;
- const idsToSelect = Number.isFinite(maxAllowed)
- ? allIds.slice(-maxAllowed)
- : allIds;
- setSelectedFiles(idsToSelect);
- try {
- clearAllFileErrors();
- } catch (error) {
- if (process.env.NODE_ENV === "development") {
- console.warn("Failed to clear file errors on select all:", error);
- }
- }
- }, [state.files.ids, setSelectedFiles, clearAllFileErrors, maxAllowed]);
-
- const handleDeselectAllFiles = useCallback(() => {
- setSelectedFiles([]);
- try {
- clearAllFileErrors();
- } catch (error) {
- if (process.env.NODE_ENV === "development") {
- console.warn("Failed to clear file errors on deselect:", error);
- }
- }
- }, [setSelectedFiles, clearAllFileErrors]);
-
- const handleCloseSelectedFiles = useCallback(() => {
- if (selectedFileIds.length === 0) return;
- void removeFiles(selectedFileIds, false);
- setSelectedFiles([]);
- }, [selectedFileIds, removeFiles, setSelectedFiles]);
-
- useFileEditorRightRailButtons({
- totalItems,
- selectedCount,
- onSelectAll: handleSelectAllFiles,
- onDeselectAll: handleDeselectAllFiles,
- onCloseSelected: handleCloseSelectedFiles,
- });
// Process uploaded files using context
// ZIP extraction is now handled automatically in FileContext based on user preferences
@@ -199,56 +131,6 @@ const FileEditor = ({
[addFiles, showStatus, showError, selectors, maxAllowed, setSelectedFiles],
);
- const toggleFile = useCallback(
- (fileId: FileId) => {
- const currentSelectedIds = contextSelectedIdsRef.current;
-
- const targetRecord = activeStirlingFileStubs.find((r) => r.id === fileId);
- if (!targetRecord) return;
-
- const contextFileId = fileId; // No need to create a new ID
- const isSelected = currentSelectedIds.includes(contextFileId);
-
- let newSelection: FileId[];
-
- if (isSelected) {
- // Remove file from selection
- newSelection = currentSelectedIds.filter((id) => id !== contextFileId);
- } else {
- // Add file to selection
- // Determine max files allowed from the active tool (negative or undefined means unlimited)
- const rawMax = selectedTool?.maxFiles;
- const maxAllowed =
- !toolMode || rawMax == null || rawMax < 0 ? Infinity : rawMax;
-
- if (maxAllowed === 1) {
- // Only one file allowed -> replace selection with the new file
- newSelection = [contextFileId];
- } else {
- // If at capacity, drop the oldest selected and append the new one
- if (
- Number.isFinite(maxAllowed) &&
- currentSelectedIds.length >= maxAllowed
- ) {
- newSelection = [...currentSelectedIds.slice(1), contextFileId];
- } else {
- newSelection = [...currentSelectedIds, contextFileId];
- }
- }
- }
-
- // Update context (this automatically updates tool selection since they use the same action)
- setSelectedFiles(newSelection);
- },
- [
- setSelectedFiles,
- toolMode,
- _setStatus,
- activeStirlingFileStubs,
- selectedTool?.maxFiles,
- ],
- );
-
// Enforce maxAllowed when tool changes or when an external action sets too many selected files
useEffect(() => {
if (Number.isFinite(maxAllowed) && selectedFileIds.length > maxAllowed) {
@@ -495,16 +377,7 @@ const FileEditor = ({
<Box p="md">
{activeStirlingFileStubs.length === 0 ? (
<Center h="60vh">
- <Stack align="center" gap="md">
- <Text size="lg" c="dimmed">
- 📁
- </Text>
- <Text c="dimmed">No files loaded</Text>
- <Text size="sm" c="dimmed">
- Upload PDF files, ZIP archives, or load from storage to get
- started
- </Text>
- </Stack>
+ <AddFileCard onFileSelect={handleFileUpload} />
</Center>
) : (
<div
@@ -531,12 +404,8 @@ const FileEditor = ({
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}
diff --git a/frontend/src/core/components/fileEditor/FileEditorStatusDot.tsx b/frontend/src/core/components/fileEditor/FileEditorStatusDot.tsx
new file mode 100644
index 0000000000..d28ee13681
--- /dev/null
+++ b/frontend/src/core/components/fileEditor/FileEditorStatusDot.tsx
@@ -0,0 +1,9 @@
+import { StirlingFileStub } from "@app/types/fileContext";
+
+interface FileEditorStatusDotProps {
+ file: StirlingFileStub;
+}
+
+export function FileEditorStatusDot(_props: FileEditorStatusDotProps) {
+ return null;
+}
diff --git a/frontend/src/core/components/fileEditor/FileEditorThumbnail.module.css b/frontend/src/core/components/fileEditor/FileEditorThumbnail.module.css
new file mode 100644
index 0000000000..fcd0335238
--- /dev/null
+++ b/frontend/src/core/components/fileEditor/FileEditorThumbnail.module.css
@@ -0,0 +1,266 @@
+.card {
+ width: 260px;
+ max-width: 260px;
+ margin: 0 auto;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0;
+ padding: 10px 10px 12px;
+ position: relative;
+ --file-text-height: 58px;
+ --file-text-bottom: 12px;
+ --thumb-text-gap: 6px;
+ padding-bottom: calc(
+ var(--file-text-bottom) + var(--file-text-height) + var(--thumb-text-gap)
+ );
+ user-select: none;
+ cursor: pointer;
+}
+
+/* Inner wrapper — centers [toolChain + thumbnail + hover menu] as a unit */
+.thumbInner {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ position: relative;
+ width: 100%;
+ max-width: 100%;
+}
+
+/* Groups toolchain bar + thumbnail so they center together inside thumbWrap */
+.thumbUnit {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ width: 100%;
+ max-height: 100%;
+}
+
+/* ToolChain bar sits directly above the thumbnail card — always rendered for consistent sizing */
+.toolChainBar {
+ flex-shrink: 0;
+ width: 100%;
+ height: 22px;
+ text-align: center;
+ overflow: hidden;
+ white-space: nowrap;
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ line-height: 22px;
+ margin-bottom: 4px;
+}
+
+.card:hover .toolChainBar,
+.card:focus-within .toolChainBar {
+ opacity: 1;
+}
+
+.thumbWrap {
+ width: 100%;
+ position: relative;
+ height: 310px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.thumbContainer {
+ aspect-ratio: var(--thumb-aspect, 8.5 / 11);
+ width: 100%;
+ max-width: 100%;
+ max-height: 100%;
+ border-radius: 12px;
+ box-shadow: var(--shadow-md);
+ overflow: hidden;
+ position: relative;
+ background: var(--bg-surface);
+ transition:
+ box-shadow 0.15s ease,
+ transform 0.2s ease;
+}
+
+.thumbContainer:hover {
+ transform: translateY(-1px);
+ box-shadow: var(--shadow-lg);
+}
+
+.thumbImage {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ border-radius: 12px;
+ background: var(--bg-surface);
+ display: block;
+ position: relative;
+ z-index: 1;
+}
+
+/* Text block pinned below thumbnail */
+.fileText {
+ position: absolute;
+ left: 10px;
+ right: 10px;
+ bottom: var(--file-text-bottom);
+ height: var(--file-text-height);
+ text-align: center;
+ pointer-events: none;
+ --file-name-line-height: 18px;
+ --file-name-lines: 2;
+ --file-meta-line-height: 14px;
+ --file-meta-gap: 4px;
+}
+
+.fileName {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text-primary);
+ line-height: var(--file-name-line-height);
+ height: calc(var(--file-name-lines) * var(--file-name-line-height));
+ margin: 0;
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: calc(var(--file-meta-line-height) + var(--file-meta-gap));
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ overflow-wrap: break-word;
+ word-break: normal;
+}
+
+.fileMeta {
+ font-size: 11px;
+ color: var(--text-secondary);
+ line-height: var(--file-meta-line-height);
+ height: var(--file-meta-line-height);
+ overflow: hidden;
+ margin: 0;
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+/* CSS-hover driven menu visibility */
+.card [data-hover-action-menu-mode="cssHover"][data-force-visible="false"] {
+ opacity: 0;
+ pointer-events: none;
+}
+
+.card:hover
+ [data-hover-action-menu-mode="cssHover"][data-force-visible="false"],
+.card:focus-within
+ [data-hover-action-menu-mode="cssHover"][data-force-visible="false"] {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+/* Error overlay */
+.errorOverlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(220, 38, 38, 0.12);
+ border-radius: 12px;
+ z-index: 2;
+ pointer-events: none;
+}
+
+.errorPill {
+ background: var(--mantine-color-red-6);
+ color: white;
+ border-radius: 12px;
+ padding: 4px 12px;
+ font-size: 12px;
+ font-weight: 600;
+}
+
+/* Badges row pinned to top-left of thumbnail - always visible */
+.thumbBadges {
+ position: absolute;
+ top: 6px;
+ left: 6px;
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ z-index: 3;
+ pointer-events: none;
+}
+
+.thumbBadgesRight {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ z-index: 3;
+ pointer-events: auto;
+}
+
+.statusDot {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.15);
+}
+
+.ownershipBadge {
+ background: var(--mantine-color-blue-6);
+ color: white;
+ border-radius: 6px;
+ padding: 2px 7px;
+ font-size: 10px;
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+.versionBadgeThumb {
+ background: var(--mantine-color-blue-6);
+ border-radius: 4px;
+ padding: 1px 5px;
+ font-size: 10px;
+ font-weight: 700;
+ color: white;
+ line-height: 16px;
+ white-space: nowrap;
+}
+
+.pinnedBadge {
+ background: var(--mantine-color-yellow-6);
+ color: white;
+ border-radius: 4px;
+ padding: 2px 4px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ line-height: 1;
+}
+
+.dragHandle {
+ position: absolute;
+ bottom: 6px;
+ right: 6px;
+ cursor: grab;
+ color: var(--text-secondary);
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ pointer-events: none;
+}
+
+.card:hover .dragHandle,
+.card:focus-within .dragHandle {
+ opacity: 0.5;
+ pointer-events: auto;
+}
diff --git a/frontend/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/src/core/components/fileEditor/FileEditorThumbnail.tsx
index cf5ca7da23..0b78d4e261 100644
--- a/frontend/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -1,14 +1,12 @@
import React, { useState, useCallback, useRef, useMemo } from "react";
import {
Text,
- ActionIcon,
- CheckboxIndicator,
- Tooltip,
Modal,
Button,
Group,
Stack,
- Loader,
+ ActionIcon,
+ Tooltip,
} from "@mantine/core";
import { useIsMobile } from "@app/hooks/useIsMobile";
import { alert } from "@app/components/toast";
@@ -21,7 +19,6 @@ import UnarchiveIcon from "@mui/icons-material/Unarchive";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import LinkIcon from "@mui/icons-material/Link";
import PushPinIcon from "@mui/icons-material/PushPin";
-import PushPinOutlinedIcon from "@mui/icons-material/PushPinOutlined";
import LockOpenIcon from "@mui/icons-material/LockOpen";
import DragIndicatorIcon from "@mui/icons-material/DragIndicator";
import {
@@ -31,11 +28,10 @@ import {
import { StirlingFileStub } from "@app/types/fileContext";
import { zipFileService } from "@app/services/zipFileService";
-import styles from "@app/components/fileEditor/FileEditor.module.css";
+import styles from "@app/components/fileEditor/FileEditorThumbnail.module.css";
import { useFileContext } from "@app/contexts/FileContext";
import { useFileState } from "@app/contexts/file/fileHooks";
import { FileId } from "@app/types/file";
-import { formatFileSize } from "@app/utils/fileUtils";
import ToolChain from "@app/components/shared/ToolChain";
import HoverActionMenu, {
HoverAction,
@@ -45,18 +41,17 @@ import { PrivateContent } from "@app/components/shared/PrivateContent";
import UploadToServerModal from "@app/components/shared/UploadToServerModal";
import ShareFileModal from "@app/components/shared/ShareFileModal";
import { useAppConfig } from "@app/contexts/AppConfigContext";
-import FileEditorFileName from "@app/components/fileEditor/FileEditorFileName";
+import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
+import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
+import { truncateCenter } from "@app/utils/textUtils";
+import { FileEditorStatusDot } from "@app/components/fileEditor/FileEditorStatusDot";
interface FileEditorThumbnailProps {
file: StirlingFileStub;
index: number;
totalFiles: number;
- selectedFiles: FileId[];
- selectionMode: boolean;
- onToggleFile: (fileId: FileId) => void;
onCloseFile: (fileId: FileId) => void;
onViewFile: (fileId: FileId) => void;
- _onSetStatus: (status: string) => void;
onReorderFiles?: (
sourceFileId: FileId,
targetFileId: FileId,
@@ -70,12 +65,8 @@ interface FileEditorThumbnailProps {
const FileEditorThumbnail = ({
file,
- index,
- selectedFiles,
- onToggleFile,
onCloseFile,
onViewFile,
- _onSetStatus,
onReorderFiles,
onDownloadFile,
onUnzipFile,
@@ -95,41 +86,41 @@ const FileEditorThumbnail = ({
openEncryptedUnlockPrompt,
} = useFileContext();
const { state, selectors } = useFileState();
- const hasError = state.ui.errorFileIds.includes(file.id);
-
- // ---- Drag state ----
- const [isDragging, setIsDragging] = useState(false);
- const [isDragOver, setIsDragOver] = useState(false);
- const dragElementRef = useRef<HTMLDivElement | null>(null);
- const [showHoverMenu, setShowHoverMenu] = useState(false);
const isMobile = useIsMobile();
- const [showCloseModal, setShowCloseModal] = useState(false);
- const [showUploadModal, setShowUploadModal] = useState(false);
- const [showShareModal, setShowShareModal] = useState(false);
- const [showSharedEditNotice, setShowSharedEditNotice] = useState(false);
- const sharedEditNoticeShownRef = useRef(false);
- // Resolve the actual File object for pin/unpin operations
- const actualFile = useMemo(() => {
- return activeFiles.find((f) => f.fileId === file.id);
- }, [activeFiles, file.id]);
+ const actualFile = useMemo(
+ () => activeFiles.find((f) => f.fileId === file.id),
+ [activeFiles, file.id],
+ );
const isPinned = actualFile ? isFilePinned(actualFile) : false;
- // Check if this is a ZIP file
const isZipFile = zipFileService.isZipFileStub(file);
+ const hasError = state.ui.errorFileIds.includes(file.id);
const pageCount = file.processedFile?.totalPages || 0;
- const isEncrypted = Boolean(file.processedFile?.isEncrypted);
+ const {
+ isEncrypted,
+ thumbnail: displayThumbnail,
+ isGenerating: isThumbGenerating,
+ } = useFileThumbnail(file);
+
+ // Aspect ratio from page dimensions, falling back to letter size
+ const firstPage = file.processedFile?.pages?.[0];
+ const firstPageRotation = firstPage?.rotation ?? 0;
+ const isLandscape = firstPageRotation === 90 || firstPageRotation === 270;
+ const thumbAspect = (() => {
+ const w = firstPage?.width;
+ const h = firstPage?.height;
+ if (w && h && w > 0 && h > 0) {
+ // width/height are effective (post-rotation) dims from PDFium, so use
+ // them directly — no swapping needed.
+ return `${w} / ${h}`;
+ }
+ return isLandscape ? "11 / 8.5" : "8.5 / 11";
+ })();
const handleRef = useRef<HTMLSpanElement | null>(null);
-
- // ---- Selection ----
- const isSelected = selectedFiles.includes(file.id);
-
- // ---- Meta formatting ----
- const prettySize = useMemo(() => {
- return formatFileSize(file.size);
- }, [file.size]);
+ const dragElementRef = useRef<HTMLDivElement | null>(null);
const extUpper = useMemo(() => {
const m = /\.([a-z0-9]+)$/i.exec(file.name ?? "");
@@ -143,6 +134,7 @@ const FileEditorThumbnail = ({
const isCBZ = extLower === "cbz";
const isCBR = extLower === "cbr";
+
const uploadEnabled = config?.storageEnabled === true;
const sharingEnabled =
uploadEnabled && config?.storageSharingEnabled === true;
@@ -178,7 +170,13 @@ const FileEditorThumbnail = ({
}).format(d);
}, [file.lastModified]);
- // ---- Drag & drop wiring ----
+ const [isDragging, setIsDragging] = useState(false);
+ const [showCloseModal, setShowCloseModal] = useState(false);
+ const [showUploadModal, setShowUploadModal] = useState(false);
+ const [showShareModal, setShowShareModal] = useState(false);
+ const [showSharedEditNotice, setShowSharedEditNotice] = useState(false);
+ const sharedEditNoticeShownRef = useRef(false);
+
const fileElementRef = useCallback(
(element: HTMLDivElement | null) => {
if (!element) return;
@@ -191,14 +189,10 @@ const FileEditorThumbnail = ({
type: "file",
fileId: file.id,
fileName: file.name,
- selectedFiles: [file.id], // Always drag only this file, ignore selection state
+ selectedFiles: [file.id],
}),
- onDragStart: () => {
- setIsDragging(true);
- },
- onDrop: () => {
- setIsDragging(false);
- },
+ onDragStart: () => setIsDragging(true),
+ onDrop: () => setIsDragging(false),
});
const dropCleanup = dropTargetForElements({
@@ -211,10 +205,7 @@ const FileEditorThumbnail = ({
const sourceData = source.data;
return sourceData.type === "file" && sourceData.fileId !== file.id;
},
- onDragEnter: () => setIsDragOver(true),
- onDragLeave: () => setIsDragOver(false),
onDrop: ({ source }) => {
- setIsDragOver(false);
const sourceData = source.data;
if (sourceData.type === "file" && onReorderFiles) {
const sourceFileId = sourceData.fileId as FileId;
@@ -229,13 +220,14 @@ const FileEditorThumbnail = ({
dropCleanup();
};
},
- [file.id, file.name, selectedFiles, onReorderFiles],
+ [file.id, file.name, onReorderFiles],
);
- // Handle close with confirmation
- const handleCloseWithConfirmation = useCallback(() => {
- setShowCloseModal(true);
- }, []);
+ const handleCloseWithConfirmation = useCallback(
+ () => setShowCloseModal(true),
+ [],
+ );
+ const handleCancelClose = useCallback(() => setShowCloseModal(false), []);
const handleConfirmClose = useCallback(() => {
onCloseFile(file.id);
@@ -278,7 +270,6 @@ const FileEditorThumbnail = ({
return;
}
}
- // Then close
onCloseFile(file.id);
alert({
alertType: "success",
@@ -296,11 +287,6 @@ const FileEditorThumbnail = ({
fileActions,
]);
- const handleCancelClose = useCallback(() => {
- setShowCloseModal(false);
- }, []);
-
- // Build hover menu actions
const hoverActions = useMemo<HoverAction[]>(
() => [
{
@@ -312,6 +298,36 @@ const FileEditorThumbnail = ({
onViewFile(file.id);
},
},
+ {
+ id: "pin",
+ icon: <PushPinIcon style={{ fontSize: 20 }} />,
+ label: isPinned
+ ? t("unpin", "Unpin File (replace after tool run)")
+ : t("pin", "Pin File (keep active after tool run)"),
+ dataTour: "file-card-pin",
+ onClick: (e) => {
+ e.stopPropagation();
+ if (actualFile) {
+ if (isPinned) {
+ unpinFile(actualFile);
+ alert({
+ alertType: "neutral",
+ title: `Unpinned ${file.name}`,
+ expandable: false,
+ durationMs: 3000,
+ });
+ } else {
+ pinFile(actualFile);
+ alert({
+ alertType: "success",
+ title: `Pinned ${file.name}`,
+ expandable: false,
+ durationMs: 3000,
+ });
+ }
+ }
+ },
+ },
{
id: "download",
icon: <DownloadOutlinedIcon style={{ fontSize: 20 }} />,
@@ -321,36 +337,32 @@ const FileEditorThumbnail = ({
onDownloadFile(file.id);
},
},
- ...(canUpload || canShare
+ ...(canUpload
+ ? [
+ {
+ id: "upload",
+ icon: <CloudUploadIcon style={{ fontSize: 20 }} />,
+ label: isUploaded
+ ? t("fileManager.updateOnServer", "Update on Server")
+ : t("fileManager.uploadToServer", "Upload to Server"),
+ onClick: (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setShowUploadModal(true);
+ },
+ },
+ ]
+ : []),
+ ...(canShare
? [
- ...(canUpload
- ? [
- {
- id: "upload",
- icon: <CloudUploadIcon style={{ fontSize: 20 }} />,
- label: isUploaded
- ? t("fileManager.updateOnServer", "Update on Server")
- : t("fileManager.uploadToServer", "Upload to Server"),
- onClick: (e: React.MouseEvent) => {
- e.stopPropagation();
- setShowUploadModal(true);
- },
- },
- ]
- : []),
- ...(canShare
- ? [
- {
- id: "share",
- icon: <LinkIcon style={{ fontSize: 20 }} />,
- label: t("fileManager.share", "Share"),
- onClick: (e: React.MouseEvent) => {
- e.stopPropagation();
- setShowShareModal(true);
- },
- },
- ]
- : []),
+ {
+ id: "share",
+ icon: <LinkIcon style={{ fontSize: 20 }} />,
+ label: t("fileManager.share", "Share"),
+ onClick: (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setShowShareModal(true);
+ },
+ },
]
: []),
{
@@ -389,7 +401,10 @@ const FileEditorThumbnail = ({
isZipFile,
isCBZ,
isCBR,
+ isPinned,
+ actualFile,
terminology,
+ DownloadOutlinedIcon,
onViewFile,
onDownloadFile,
onUnzipFile,
@@ -397,13 +412,13 @@ const FileEditorThumbnail = ({
canUpload,
canShare,
isUploaded,
+ pinFile,
+ unpinFile,
],
);
- // ---- Card interactions ----
const handleCardClick = () => {
if (!isSupported) return;
- // Clear error state if file has an error (click to clear error)
if (hasError) {
try {
fileActions.clearFileError(file.id);
@@ -415,7 +430,6 @@ const FileEditorThumbnail = ({
sharedEditNoticeShownRef.current = true;
setShowSharedEditNotice(true);
}
- onToggleFile(file.id);
};
const handleCardDoubleClick = () => {
@@ -423,12 +437,9 @@ const FileEditorThumbnail = ({
onViewFile(file.id);
};
- // ---- Style helpers ----
- const getHeaderClassName = () => {
- if (hasError) return styles.headerError;
- if (!isSupported) return styles.headerUnsupported;
- return isSelected ? styles.headerSelected : styles.headerResting;
- };
+ const metaLine = [dateLabel, extUpper ? `${extUpper} file` : "", pageLabel]
+ .filter(Boolean)
+ .join(" - ");
return (
<div
@@ -436,268 +447,130 @@ const FileEditorThumbnail = ({
data-file-id={file.id}
data-testid="file-thumbnail"
data-tour="file-card-checkbox"
- data-selected={isSelected}
data-supported={isSupported}
- className={`${styles.card} w-[18rem] h-[22rem] select-none flex flex-col shadow-sm transition-all relative`}
- style={
- {
- opacity: isDragging ? 0.4 : 1,
- outline: isDragOver
- ? "3px dashed var(--mantine-color-blue-5, #3b82f6)"
- : undefined,
- outlineOffset: isDragOver ? "2px" : undefined,
- transform: isDragOver ? "scale(1.02)" : undefined,
- transition:
- "outline 120ms ease, transform 120ms ease, opacity 120ms ease",
- // Tag each card with a stable, unique view-transition-name so the
- // browser can animate the reorder (see FileEditor.handleReorderFiles,
- // which dispatches reorderFiles inside document.startViewTransition).
- viewTransitionName: `file-card-${file.id}`,
- } as React.CSSProperties
- }
+ className={`${styles.card} select-none`}
+ style={{ opacity: isDragging ? 0.9 : 1 }}
tabIndex={0}
role="listitem"
- aria-selected={isSelected}
onClick={handleCardClick}
- onMouseEnter={() => setShowHoverMenu(true)}
- onMouseLeave={() => setShowHoverMenu(false)}
onDoubleClick={handleCardDoubleClick}
>
- {/* Header bar */}
- <div
- className={`${styles.header} ${getHeaderClassName()}`}
- data-has-error={hasError}
- >
- {/* Logo/checkbox area */}
- <div className={styles.logoMark}>
- {hasError ? (
- <div className={styles.errorPill}>
- <span>{t("error._value", "Error")}</span>
- </div>
- ) : isSupported ? (
- <CheckboxIndicator
- checked={isSelected}
- onChange={() => onToggleFile(file.id)}
- color="var(--checkbox-checked-bg)"
- />
- ) : (
- <div className={styles.unsupportedPill}>
- <span>{t("unsupported", "Unsupported")}</span>
+ <div className={styles.thumbInner}>
+ {/* Thumbnail area */}
+ <div className={styles.thumbWrap}>
+ {/* thumbUnit groups toolchain + card so they center together, keeping text tight above the card */}
+ <div className={styles.thumbUnit}>
+ {/* Tool chain bar — always rendered for consistent height, content only when history exists */}
+ <div className={styles.toolChainBar}>
+ {file.toolHistory && file.toolHistory.length > 0 && (
+ <ToolChain
+ toolChain={file.toolHistory}
+ displayStyle="text"
+ size="xs"
+ maxWidth="100%"
+ color="var(--mantine-color-gray-7)"
+ />
+ )}
</div>
- )}
- </div>
-
- {/* Centered index */}
- <div
- className={styles.headerIndex}
- aria-label={`Position ${index + 1}`}
- >
- {index + 1}
- </div>
- {/* Action buttons group */}
- <div className={styles.headerActions}>
- {isEncrypted && (
- <Tooltip
- label={t(
- "encryptedPdfUnlock.unlockPrompt",
- "Unlock PDF to continue",
- )}
+ <div
+ className={styles.thumbContainer}
+ data-supported={isSupported}
+ style={{ "--thumb-aspect": thumbAspect } as React.CSSProperties}
>
- <ActionIcon
- aria-label={t(
- "encryptedPdfUnlock.unlockPrompt",
- "Unlock PDF to continue",
- )}
- variant="subtle"
- className={styles.headerIconButton}
- onClick={(e) => {
- e.stopPropagation();
- openEncryptedUnlockPrompt(file.id);
- }}
- >
- <LockOpenIcon fontSize="small" />
- </ActionIcon>
- </Tooltip>
- )}
- {/* Pin/Unpin icon */}
- <Tooltip
- label={
- isPinned
- ? t("unpin", "Unpin File (replace after tool run)")
- : t("pin", "Pin File (keep active after tool run)")
- }
- >
- <ActionIcon
- aria-label={
- isPinned
- ? t("unpin", "Unpin File (replace after tool run)")
- : t("pin", "Pin File (keep active after tool run)")
- }
- variant="subtle"
- className={isPinned ? styles.pinned : styles.headerIconButton}
- data-tour="file-card-pin"
- onClick={(e) => {
- e.stopPropagation();
- if (actualFile) {
- if (isPinned) {
- unpinFile(actualFile);
- alert({
- alertType: "neutral",
- title: `Unpinned ${file.name}`,
- expandable: false,
- durationMs: 3000,
- });
- } else {
- pinFile(actualFile);
- alert({
- alertType: "success",
- title: `Pinned ${file.name}`,
- expandable: false,
- durationMs: 3000,
- });
- }
- }
- }}
- >
- {isPinned ? (
- <PushPinIcon fontSize="small" />
- ) : (
- <PushPinOutlinedIcon fontSize="small" />
+ {/* Error overlay */}
+ {hasError && (
+ <div className={styles.errorOverlay}>
+ <span className={styles.errorPill}>
+ {t("error._value", "Error")}
+ </span>
+ </div>
)}
- </ActionIcon>
- </Tooltip>
- </div>
- </div>
- {/* Title + meta line */}
- <div
- style={{
- padding: "0.5rem",
- textAlign: "center",
- background: "var(--file-card-bg)",
- marginTop: "0.5rem",
- marginBottom: "0.5rem",
- }}
- >
- <Text
- size="lg"
- fw={700}
- className={styles.title}
- title={file.name}
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- gap: "0.25rem",
- }}
- >
- <FileEditorFileName file={file} />
- </Text>
- <Text
- size="sm"
- c="dimmed"
- className={styles.meta}
- lineClamp={3}
- title={`${extUpper || "FILE"} • ${prettySize}`}
- >
- {/* e.g., v2 - Jan 29, 2025 - PDF file - 3 Pages */}
- {`v${file.versionNumber} - `}
- {dateLabel}
- {extUpper ? ` - ${extUpper} file` : ""}
- {pageLabel ? ` - ${pageLabel}` : ""}
- </Text>
- </div>
-
- {/* Preview area */}
- <div
- className={`${styles.previewBox} mx-6 mb-4 relative flex-1`}
- style={
- isSupported || hasError
- ? undefined
- : { filter: "grayscale(80%)", opacity: 0.6 }
- }
- >
- <div className={styles.previewPaper}>
- {file.thumbnailUrl ? (
- <PrivateContent>
- <img
- src={file.thumbnailUrl}
- alt={file.name}
- draggable={false}
- loading="lazy"
- decoding="async"
- onError={(e) => {
- const img = e.currentTarget;
- img.style.display = "none";
- img.parentElement?.setAttribute("data-thumb-missing", "true");
- }}
- style={{
- maxWidth: "80%",
- maxHeight: "80%",
- objectFit: "contain",
- borderRadius: 0,
- background: "#ffffff",
- border: "1px solid var(--border-default)",
- display: "block",
- marginLeft: "auto",
- marginRight: "auto",
- alignSelf: "start",
+ {/* Thumbnail image or loading state */}
+ <DocumentThumbnail
+ file={file}
+ thumbnail={displayThumbnail || undefined}
+ isEncrypted={isEncrypted}
+ isLoading={
+ !isEncrypted &&
+ !displayThumbnail &&
+ (isThumbGenerating ||
+ file.type?.startsWith("application/pdf") ||
+ file.type?.startsWith("image/"))
+ }
+ iconSize="6rem"
+ imgClassName={styles.thumbImage}
+ onImageError={(e) => {
+ e.currentTarget.style.display = "none";
}}
/>
- </PrivateContent>
- ) : file.type?.startsWith("application/pdf") ? (
- <Stack
- align="center"
- justify="center"
- gap="xs"
- style={{ height: "100%" }}
- >
- <Loader size="sm" />
- <Text size="xs" c="dimmed">
- Loading thumbnail...
- </Text>
- </Stack>
- ) : null}
- </div>
- {/* Drag handle (span wrapper so we can attach a ref reliably) */}
- <span ref={handleRef} className={styles.dragHandle} aria-hidden>
- <DragIndicatorIcon fontSize="small" />
- </span>
-
- {/* Tool chain display at bottom */}
- {file.toolHistory && (
- <div
- style={{
- position: "absolute",
- bottom: "4px",
- left: "4px",
- right: "4px",
- padding: "4px 6px",
- textAlign: "center",
- fontWeight: 600,
- overflow: "hidden",
- whiteSpace: "nowrap",
- }}
- >
- <ToolChain
- toolChain={file.toolHistory}
- displayStyle="text"
- size="xs"
- maxWidth={"100%"}
- color="var(--mantine-color-gray-7)"
- />
+ {/* Badges — top-left: version, pin, ownership, encrypted */}
+ <div className={styles.thumbBadges}>
+ <span className={styles.versionBadgeThumb}>
+ v{file.versionNumber}
+ </span>
+ {isPinned && (
+ <span className={styles.pinnedBadge}>
+ <PushPinIcon style={{ fontSize: 12 }} />
+ </span>
+ )}
+ {isSharedFile && !isOwnedOrLocal && (
+ <span className={styles.ownershipBadge}>
+ {t("fileManager.sharedWithYou", "Shared")}
+ </span>
+ )}
+ {isEncrypted && (
+ <Tooltip
+ label={t(
+ "encryptedPdfUnlock.unlockPrompt",
+ "Unlock PDF to continue",
+ )}
+ >
+ <ActionIcon
+ size="xs"
+ variant="filled"
+ color="yellow"
+ onClick={(e) => {
+ e.stopPropagation();
+ openEncryptedUnlockPrompt(file.id);
+ }}
+ style={{ pointerEvents: "auto" }}
+ >
+ <LockOpenIcon style={{ fontSize: 12 }} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </div>
+
+ <FileEditorStatusDot file={file} />
+ </div>
</div>
- )}
+ {/* end thumbUnit */}
+
+ {/* Drag handle */}
+ <span ref={handleRef} className={styles.dragHandle} aria-hidden>
+ <DragIndicatorIcon fontSize="small" />
+ </span>
+ </div>
+
+ {/* Hover action menu — visibility driven by CSS on desktop, always shown on mobile */}
+ <HoverActionMenu
+ show={isMobile}
+ actions={hoverActions}
+ position="outside"
+ visibility="cssHover"
+ />
</div>
- {/* Hover Menu */}
- <HoverActionMenu
- show={showHoverMenu || isMobile}
- actions={hoverActions}
- position="outside"
- />
+ {/* File name + meta */}
+ <div className={styles.fileText}>
+ <p className={styles.fileName}>
+ <PrivateContent>{truncateCenter(file.name, 40)}</PrivateContent>
+ </p>
+ <p className={styles.fileMeta}>{metaLine}</p>
+ </div>
{/* Close Confirmation Modal */}
<Modal
@@ -714,7 +587,7 @@ const FileEditorThumbnail = ({
{t("confirmCloseUnsaved", "This file has unsaved changes.")}
</Text>
<Text size="sm" c="dimmed" fw={500}>
- {file.name}
+ <PrivateContent>{file.name}</PrivateContent>
</Text>
<Group justify="flex-end" gap="sm">
<Button variant="light" onClick={handleCancelClose}>
@@ -741,7 +614,7 @@ const FileEditorThumbnail = ({
)}
</Text>
<Text size="sm" c="dimmed" fw={500}>
- {file.name}
+ <PrivateContent>{file.name}</PrivateContent>
</Text>
<Group justify="flex-end" gap="sm">
<Button variant="light" onClick={handleCancelClose}>
@@ -759,6 +632,8 @@ const FileEditorThumbnail = ({
)}
</Stack>
</Modal>
+
+ {/* Shared edit notice modal */}
<Modal
opened={showSharedEditNotice}
onClose={() => setShowSharedEditNotice(false)}
diff --git a/frontend/src/core/components/fileEditor/fileEditorRightRailButtons.tsx b/frontend/src/core/components/fileEditor/fileEditorRightRailButtons.tsx
deleted file mode 100644
index 8c5383457f..0000000000
--- a/frontend/src/core/components/fileEditor/fileEditorRightRailButtons.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import {
- useRightRailButtons,
- RightRailButtonWithAction,
-} from "@app/hooks/useRightRailButtons";
-import LocalIcon from "@app/components/shared/LocalIcon";
-
-interface FileEditorRightRailButtonsParams {
- totalItems: number;
- selectedCount: number;
- onSelectAll: () => void;
- onDeselectAll: () => void;
- onCloseSelected: () => void;
-}
-
-export function useFileEditorRightRailButtons({
- totalItems,
- selectedCount,
- onSelectAll,
- onDeselectAll,
- onCloseSelected,
-}: FileEditorRightRailButtonsParams) {
- const { t, i18n } = useTranslation();
-
- const buttons = useMemo<RightRailButtonWithAction[]>(
- () => [
- {
- id: "file-select-all",
- icon: <LocalIcon icon="select-all" width="1.5rem" height="1.5rem" />,
- tooltip: t("rightRail.selectAll", "Select All"),
- ariaLabel:
- typeof t === "function"
- ? t("rightRail.selectAll", "Select All")
- : "Select All",
- section: "top" as const,
- order: 10,
- disabled: totalItems === 0 || selectedCount === totalItems,
- visible: totalItems > 0,
- onClick: onSelectAll,
- },
- {
- id: "file-deselect-all",
- icon: (
- <LocalIcon
- icon="crop-square-outline"
- width="1.5rem"
- height="1.5rem"
- />
- ),
- tooltip: t("rightRail.deselectAll", "Deselect All"),
- ariaLabel:
- typeof t === "function"
- ? t("rightRail.deselectAll", "Deselect All")
- : "Deselect All",
- section: "top" as const,
- order: 20,
- disabled: selectedCount === 0,
- visible: totalItems > 0,
- onClick: onDeselectAll,
- },
- {
- id: "file-close-selected",
- icon: <LocalIcon icon="close-rounded" width="1.5rem" height="1.5rem" />,
- tooltip: t("rightRail.closeSelected", "Close Selected Files"),
- ariaLabel:
- typeof t === "function"
- ? t("rightRail.closeSelected", "Close Selected Files")
- : "Close Selected Files",
- section: "top" as const,
- order: 30,
- disabled: selectedCount === 0,
- visible: totalItems > 0,
- onClick: onCloseSelected,
- },
- ],
- [
- t,
- i18n.language,
- totalItems,
- selectedCount,
- onSelectAll,
- onDeselectAll,
- onCloseSelected,
- ],
- );
-
- useRightRailButtons(buttons);
-}
diff --git a/frontend/src/core/components/fileManager/CompactFileDetails.tsx b/frontend/src/core/components/fileManager/CompactFileDetails.tsx
index d8717ee7e3..09ca9a10b1 100644
--- a/frontend/src/core/components/fileManager/CompactFileDetails.tsx
+++ b/frontend/src/core/components/fileManager/CompactFileDetails.tsx
@@ -18,6 +18,7 @@ interface CompactFileDetailsProps {
onPrevious: () => void;
onNext: () => void;
onOpenFiles: () => void;
+ canCloseAll?: boolean;
}
const CompactFileDetails: React.FC<CompactFileDetailsProps> = ({
@@ -30,6 +31,7 @@ const CompactFileDetails: React.FC<CompactFileDetailsProps> = ({
onPrevious,
onNext,
onOpenFiles,
+ canCloseAll = false,
}) => {
const { t } = useTranslation();
const hasSelection = selectedFiles.length > 0;
@@ -94,7 +96,7 @@ const CompactFileDetails: React.FC<CompactFileDetailsProps> = ({
<Box style={{ flex: 1, minWidth: 0 }}>
<Text size="sm" fw={500} truncate>
<PrivateContent>
- {currentFile ? currentFile.name : "No file selected"}
+ {currentFile ? currentFile.name : "No file loaded"}
</PrivateContent>
</Text>
<Text size="xs" c="dimmed">
@@ -149,18 +151,21 @@ const CompactFileDetails: React.FC<CompactFileDetailsProps> = ({
<Button
size="sm"
onClick={onOpenFiles}
- disabled={!hasSelection}
+ disabled={!hasSelection && !canCloseAll}
fullWidth
style={{
- backgroundColor: hasSelection
- ? "var(--btn-open-file)"
- : "var(--mantine-color-gray-4)",
+ backgroundColor:
+ hasSelection || canCloseAll
+ ? "var(--btn-open-file)"
+ : "var(--mantine-color-gray-4)",
color: "white",
}}
>
- {selectedFiles.length > 1
- ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)
- : t("fileManager.openFile", "Open File")}
+ {canCloseAll
+ ? t("fileManager.closeAllFiles", "Close all files")
+ : selectedFiles.length > 1
+ ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)
+ : t("fileManager.openFile", "Open File")}
</Button>
</Stack>
);
diff --git a/frontend/src/core/components/fileManager/FileDetails.tsx b/frontend/src/core/components/fileManager/FileDetails.tsx
index dd6b3e7143..4621559ae8 100644
--- a/frontend/src/core/components/fileManager/FileDetails.tsx
+++ b/frontend/src/core/components/fileManager/FileDetails.tsx
@@ -12,7 +12,8 @@ interface FileDetailsProps {
}
const FileDetails: React.FC<FileDetailsProps> = ({ compact = false }) => {
- const { selectedFiles, onOpenFiles, modalHeight } = useFileManagerContext();
+ const { selectedFiles, onOpenFiles, modalHeight, activeFileIds } =
+ useFileManagerContext();
const { t } = useTranslation();
const [currentFileIndex, setCurrentFileIndex] = useState(0);
const [isAnimating, setIsAnimating] = useState(false);
@@ -21,6 +22,9 @@ const FileDetails: React.FC<FileDetailsProps> = ({ compact = false }) => {
const currentFile =
selectedFiles.length > 0 ? selectedFiles[currentFileIndex] : null;
const hasSelection = selectedFiles.length > 0;
+ const hasActiveFiles = activeFileIds.length > 0;
+ // Enable "Close all files" when nothing is checked but files are open in workbench
+ const canCloseAll = !hasSelection && hasActiveFiles;
// Use IndexedDB hook for the current file
const { thumbnail: currentThumbnail } = useIndexedDBThumbnail(currentFile);
@@ -71,6 +75,7 @@ const FileDetails: React.FC<FileDetailsProps> = ({ compact = false }) => {
onPrevious={handlePrevious}
onNext={handleNext}
onOpenFiles={onOpenFiles}
+ canCloseAll={canCloseAll}
/>
);
}
@@ -104,18 +109,21 @@ const FileDetails: React.FC<FileDetailsProps> = ({ compact = false }) => {
<Button
size="md"
onClick={onOpenFiles}
- disabled={!hasSelection}
+ disabled={!hasSelection && !canCloseAll}
fullWidth
style={{
- backgroundColor: hasSelection
- ? "var(--btn-open-file)"
- : "var(--mantine-color-gray-4)",
+ backgroundColor:
+ hasSelection || canCloseAll
+ ? "var(--btn-open-file)"
+ : "var(--mantine-color-gray-4)",
color: "white",
}}
>
- {selectedFiles.length > 1
- ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)
- : t("fileManager.openFile", "Open File")}
+ {canCloseAll
+ ? t("fileManager.closeAllFiles", "Close all files")
+ : selectedFiles.length > 1
+ ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)
+ : t("fileManager.openFile", "Open File")}
</Button>
</Stack>
);
diff --git a/frontend/src/core/components/fileManager/FileHistoryGroup.tsx b/frontend/src/core/components/fileManager/FileHistoryGroup.tsx
index cda54edf71..a405bd37a5 100644
--- a/frontend/src/core/components/fileManager/FileHistoryGroup.tsx
+++ b/frontend/src/core/components/fileManager/FileHistoryGroup.tsx
@@ -11,7 +11,6 @@ interface FileHistoryGroupProps {
onDownloadSingle: (file: StirlingFileStub) => void;
onFileDoubleClick: (file: StirlingFileStub) => void;
onHistoryFileRemove: (file: StirlingFileStub) => void;
- isFileSupported: (fileName: string) => boolean;
}
const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({
@@ -21,7 +20,6 @@ const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({
onDownloadSingle,
onFileDoubleClick,
onHistoryFileRemove,
- isFileSupported,
}) => {
const { t } = useTranslation();
@@ -50,7 +48,6 @@ const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({
key={`history-${historyFile.id}-${historyFile.versionNumber || 1}`}
file={historyFile}
isSelected={false} // History files are not selectable
- isSupported={isFileSupported(historyFile.name)}
onSelect={() => {}} // No selection for history files
onRemove={() => onHistoryFileRemove(historyFile)} // Remove specific history file
onDownload={() => onDownloadSingle(historyFile)}
diff --git a/frontend/src/core/components/fileManager/FileListArea.tsx b/frontend/src/core/components/fileManager/FileListArea.tsx
index 467ac398e1..4ee5d7f2bd 100644
--- a/frontend/src/core/components/fileManager/FileListArea.tsx
+++ b/frontend/src/core/components/fileManager/FileListArea.tsx
@@ -28,7 +28,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
onHistoryFileRemove,
onFileDoubleClick,
onDownloadSingle,
- isFileSupported,
isLoading,
activeFileIds,
} = useFileManagerContext();
@@ -65,7 +64,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
<FileListItem
file={file}
isSelected={selectedFilesSet.has(file.id)}
- isSupported={isFileSupported(file.name)}
onSelect={(shiftKey) => onFileSelect(file, index, shiftKey)}
onRemove={() => onFileRemove(index)}
onDownload={() => onDownloadSingle(file)}
@@ -82,7 +80,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
onDownloadSingle={onDownloadSingle}
onFileDoubleClick={onFileDoubleClick}
onHistoryFileRemove={onHistoryFileRemove}
- isFileSupported={isFileSupported}
/>
</React.Fragment>
);
diff --git a/frontend/src/core/components/fileManager/FileListItem.tsx b/frontend/src/core/components/fileManager/FileListItem.tsx
index 88b2b4e58b..6cf1251d65 100644
--- a/frontend/src/core/components/fileManager/FileListItem.tsx
+++ b/frontend/src/core/components/fileManager/FileListItem.tsx
@@ -39,7 +39,6 @@ import { alert } from "@app/components/toast";
interface FileListItemProps {
file: StirlingFileStub;
isSelected: boolean;
- isSupported: boolean;
onSelect: (shiftKey?: boolean) => void;
onRemove: () => void;
onDownload?: () => void;
@@ -53,7 +52,6 @@ interface FileListItemProps {
const FileListItem: React.FC<FileListItemProps> = ({
file,
isSelected,
- isSupported,
onSelect,
onRemove,
onDownload,
@@ -187,15 +185,12 @@ const FileListItem: React.FC<FileListItemProps> = ({
<Box
p="sm"
style={{
- cursor: isHistoryFile || isActive ? "default" : "pointer",
- backgroundColor: isActive
- ? "var(--file-active-bg)"
- : isSelected
+ cursor: isHistoryFile ? "default" : "pointer",
+ backgroundColor:
+ isSelected || shouldShowHovered
? "var(--mantine-color-gray-1)"
- : shouldShowHovered
- ? "var(--mantine-color-gray-1)"
- : "var(--bg-file-list)",
- opacity: isSupported ? 1 : 0.5,
+ : "var(--bg-file-list)",
+ opacity: 1,
transition: "background-color 0.15s ease",
userSelect: "none",
WebkitUserSelect: "none",
@@ -206,9 +201,7 @@ const FileListItem: React.FC<FileListItemProps> = ({
? "3px solid var(--mantine-color-blue-4)"
: "none", // Visual indicator for history
}}
- onClick={
- isHistoryFile || isActive ? undefined : (e) => onSelect(e.shiftKey)
- }
+ onClick={isHistoryFile ? undefined : (e) => onSelect(e.shiftKey)}
onDoubleClick={onDoubleClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
@@ -218,16 +211,14 @@ const FileListItem: React.FC<FileListItemProps> = ({
<Box>
{/* Checkbox for regular files only */}
<Checkbox
- checked={isActive || isSelected}
+ checked={isSelected}
onChange={() => {}} // Handled by parent onClick
size="sm"
pl="sm"
pr="xs"
- disabled={isActive}
- color={isActive ? "green" : undefined}
styles={{
input: {
- cursor: isActive ? "not-allowed" : "pointer",
+ cursor: "pointer",
},
}}
/>
diff --git a/frontend/src/core/components/fileManager/FileSourceButtons.tsx b/frontend/src/core/components/fileManager/FileSourceButtons.tsx
index f6551132cf..6905f1bc75 100644
--- a/frontend/src/core/components/fileManager/FileSourceButtons.tsx
+++ b/frontend/src/core/components/fileManager/FileSourceButtons.tsx
@@ -10,28 +10,12 @@ import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useIsMobile } from "@app/hooks/useIsMobile";
import MobileUploadModal from "@app/components/shared/MobileUploadModal";
+import { GoogleDriveIcon } from "@app/components/shared/CloudStorageIcons";
interface FileSourceButtonsProps {
horizontal?: boolean;
}
-/**
- * Google Drive icon component - displays the branded SVG icon
- * Shows grayscale when disabled
- */
-const GoogleDriveIcon: React.FC<{ disabled?: boolean }> = ({ disabled }) => (
- <img
- src="/images/google-drive.svg"
- alt="Google Drive"
- style={{
- width: "20px",
- height: "20px",
- opacity: disabled ? 0.5 : 1,
- filter: disabled ? "grayscale(100%)" : "none",
- }}
- />
-);
-
const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({
horizontal = false,
}) => {
@@ -144,7 +128,7 @@ const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({
<Button
variant="subtle"
color="var(--mantine-color-gray-6)"
- leftSection={<GoogleDriveIcon disabled={!isGoogleDriveEnabled} />}
+ leftSection={<GoogleDriveIcon colored={isGoogleDriveEnabled} />}
justify={horizontal ? "center" : "flex-start"}
onClick={handleGoogleDriveClick}
fullWidth={!horizontal}
diff --git a/frontend/src/core/components/layout/Workbench.module.css b/frontend/src/core/components/layout/Workbench.module.css
index 73d2e402f4..51138d2ac3 100644
--- a/frontend/src/core/components/layout/Workbench.module.css
+++ b/frontend/src/core/components/layout/Workbench.module.css
@@ -1,3 +1,24 @@
+/* WorkbenchBar slide-in/out animation using CSS grid trick */
+.workbenchBarWrapper {
+ display: grid;
+ grid-template-rows: 1fr;
+ transition: grid-template-rows 280ms ease;
+}
+
+.workbenchBarWrapper[data-hidden="true"] {
+ grid-template-rows: 0fr;
+}
+
+.workbenchBarWrapper[data-no-transition="true"] {
+ transition: none;
+}
+
+/* Direct child must have min-height: 0 so the row can collapse below content size */
+.workbenchBarInner {
+ min-height: 0;
+ overflow: hidden;
+}
+
.workbenchScrollable {
overflow-y: auto !important;
overflow-x: hidden !important;
diff --git a/frontend/src/core/components/layout/Workbench.tsx b/frontend/src/core/components/layout/Workbench.tsx
index 3650368444..4d99f1b642 100644
--- a/frontend/src/core/components/layout/Workbench.tsx
+++ b/frontend/src/core/components/layout/Workbench.tsx
@@ -1,21 +1,19 @@
-import { Suspense, lazy, useCallback } from "react";
+import { useEffect, useState, Suspense, lazy } from "react";
import { Box, Loader, Center } from "@mantine/core";
import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useFileHandler } from "@app/hooks/useFileHandler";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
+import { useFileState } from "@app/contexts/FileContext";
import {
useNavigationState,
useNavigationActions,
- useNavigationGuard,
} from "@app/contexts/NavigationContext";
import { isBaseWorkbench } from "@app/types/workbench";
-import { useViewer } from "@app/contexts/ViewerContext";
+import { VIEWER_SUPPORTED_EXTENSIONS } from "@app/utils/fileUtils";
import { useAppConfig } from "@app/contexts/AppConfigContext";
-import { FileId } from "@app/types/file";
import styles from "@app/components/layout/Workbench.module.css";
-import TopControls from "@app/components/shared/TopControls";
+import WorkbenchBar from "@app/components/shared/WorkbenchBar";
import LandingPage from "@app/components/shared/LandingPage";
import Footer from "@app/components/shared/Footer";
import DismissAllErrorsButton from "@app/components/shared/DismissAllErrorsButton";
@@ -37,7 +35,6 @@ export default function Workbench() {
// Use context-based hooks to eliminate all prop drilling
const { selectors } = useFileState();
- const { actions: fileActions } = useFileActions();
const { workbench: currentView } = useNavigationState();
const { actions: navActions } = useNavigationActions();
const setCurrentView = navActions.setWorkbench;
@@ -61,34 +58,15 @@ export default function Workbench() {
const { toolRegistry } = useToolWorkflow();
const selectedTool = selectedToolId ? toolRegistry[selectedToolId] : null;
const { addFiles } = useFileHandler();
+ const hasFiles = activeFiles.length > 0;
- // Get active file index from ViewerContext
- const { activeFileIndex, setActiveFileIndex } = useViewer();
-
- // Get navigation guard for unsaved changes check when switching files
- const { requestNavigation } = useNavigationGuard();
-
- // Wrap file selection to check for unsaved changes before switching
- // requestNavigation will show the modal if there are unsaved changes, otherwise navigate immediately
- const handleFileSelect = useCallback(
- (index: number) => {
- // Don't do anything if selecting the same file
- if (index === activeFileIndex) return;
-
- // requestNavigation handles the unsaved changes check internally
- requestNavigation(() => {
- setActiveFileIndex(index);
- });
- },
- [activeFileIndex, requestNavigation, setActiveFileIndex],
- );
-
- const handleFileRemove = useCallback(
- async (fileId: FileId) => {
- await fileActions.removeFiles([fileId], false); // false = don't delete from IndexedDB, just remove from context
- },
- [fileActions],
- );
+ // Enable bar transitions after first paint so the initial hidden state shows
+ // without animating (landing page on load shouldn't animate the bar up).
+ const [barTransitionEnabled, setBarTransitionEnabled] = useState(false);
+ useEffect(() => {
+ const raf = requestAnimationFrame(() => setBarTransitionEnabled(true));
+ return () => cancelAnimationFrame(raf);
+ }, []);
const handlePreviewClose = () => {
setPreviewFile(null);
@@ -130,7 +108,9 @@ export default function Workbench() {
return (
<FileEditor
toolMode={!!selectedToolId}
- supportedExtensions={selectedTool?.supportedFormats || ["pdf"]}
+ supportedExtensions={
+ selectedTool?.supportedFormats || VIEWER_SUPPORTED_EXTENSIONS
+ }
{...(!selectedToolId && {
onOpenPageEditor: () => {
setCurrentView("pageEditor");
@@ -150,8 +130,6 @@ export default function Workbench() {
setSidebarsVisible={setSidebarsVisible}
previewFile={previewFile}
onClose={handlePreviewClose}
- activeFileIndex={activeFileIndex}
- setActiveFileIndex={setActiveFileIndex}
/>
);
@@ -195,7 +173,7 @@ export default function Workbench() {
);
default:
- return <LandingPage />;
+ return null;
}
};
@@ -209,27 +187,23 @@ export default function Workbench() {
: { backgroundColor: "var(--bg-background)" }
}
>
- {/* Top Controls */}
- {activeFiles.length > 0 &&
- !customWorkbenchViews.find((v) => v.workbenchId === currentView)
- ?.hideTopControls && (
- <TopControls
- currentView={currentView}
- setCurrentView={setCurrentView}
- customViews={customWorkbenchViews}
- activeFiles={activeFiles.map((f) => {
- const stub = selectors.getStirlingFileStub(f.fileId);
- return {
- fileId: f.fileId,
- name: f.name,
- versionNumber: stub?.versionNumber,
- };
- })}
- currentFileIndex={activeFileIndex}
- onFileSelect={handleFileSelect}
- onFileRemove={handleFileRemove}
- />
- )}
+ {/* Workbench Bar - animates in/out based on file presence */}
+ {!customWorkbenchViews.find((v) => v.workbenchId === currentView)
+ ?.hideTopControls && (
+ <div
+ className={styles.workbenchBarWrapper}
+ data-hidden={String(!hasFiles)}
+ data-no-transition={String(!barTransitionEnabled)}
+ >
+ <div className={styles.workbenchBarInner}>
+ <WorkbenchBar
+ currentView={currentView}
+ setCurrentView={setCurrentView}
+ hasFiles={hasFiles}
+ />
+ </div>
+ </div>
+ )}
{/* Dismiss All Errors Button */}
<DismissAllErrorsButton />
diff --git a/frontend/src/core/components/onboarding/Onboarding.tsx b/frontend/src/core/components/onboarding/Onboarding.tsx
index d215c0e734..86976784e9 100644
--- a/frontend/src/core/components/onboarding/Onboarding.tsx
+++ b/frontend/src/core/components/onboarding/Onboarding.tsx
@@ -232,12 +232,15 @@ export default function Onboarding() {
loadSampleFile: tourOrch.loadSampleFile,
switchToActiveFiles: tourOrch.switchToActiveFiles,
pinFile: tourOrch.pinFile,
+ revealFileCardHoverMenu: tourOrch.revealFileCardHoverMenu,
modifyCropSettings: tourOrch.modifyCropSettings,
executeTool: tourOrch.executeTool,
openFilesModal,
+ openSettingsHelpSection: () =>
+ adminTourOrch.navigateToSection("help"),
},
}),
- [t, tourOrch, closeFilesModal, openFilesModal],
+ [t, tourOrch, adminTourOrch, closeFilesModal, openFilesModal],
);
const whatsNewStepsConfig = useMemo(
@@ -253,7 +256,6 @@ export default function Onboarding() {
switchToViewer: tourOrch.switchToViewer,
switchToPageEditor: tourOrch.switchToPageEditor,
switchToActiveFiles: tourOrch.switchToActiveFiles,
- selectFirstFile: tourOrch.selectFirstFile,
},
}),
[t, tourOrch, closeFilesModal, openFilesModal],
diff --git a/frontend/src/core/components/onboarding/adminStepsConfig.ts b/frontend/src/core/components/onboarding/adminStepsConfig.ts
index 4d33abb57c..1d8083201c 100644
--- a/frontend/src/core/components/onboarding/adminStepsConfig.ts
+++ b/frontend/src/core/components/onboarding/adminStepsConfig.ts
@@ -4,6 +4,10 @@ import {
addGlowToElements,
removeAllGlows,
} from "@app/components/onboarding/tourGlow";
+import {
+ waitForElement,
+ waitForHighlightable,
+} from "@app/components/onboarding/tourUtils";
export enum AdminTourStep {
WELCOME,
@@ -57,7 +61,7 @@ export function createAdminStepsConfig({
selector: '[data-tour="config-button"]',
content: t(
"adminOnboarding.configButton",
- "Click the <strong>Config</strong> button to access all system settings and administrative controls.",
+ "Open <strong>Settings</strong> to access all system configuration and administrative controls.",
),
position: "right",
padding: 10,
@@ -204,15 +208,18 @@ export function createAdminStepsConfig({
},
},
[AdminTourStep.WRAP_UP]: {
- selector: '[data-tour="help-button"]',
+ selector: '[data-tour="admin-help-nav"]',
content: t(
"adminOnboarding.wrapUp",
- "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. Access this tour anytime from the <strong>Help</strong> menu.",
+ "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. You can replay it anytime — just open <strong>Settings</strong> and find it here in the <strong>Tours</strong> section under Help.",
),
position: "right",
padding: 10,
- action: () => {
+ action: async () => {
removeAllGlows();
+ navigateToSection("help");
+ await waitForElement('[data-tour="admin-help-nav"]', 5000);
+ await waitForHighlightable('[data-tour="admin-help-nav"]', 5000);
},
},
};
diff --git a/frontend/src/core/components/onboarding/tourUtils.ts b/frontend/src/core/components/onboarding/tourUtils.ts
new file mode 100644
index 0000000000..e6d8828d39
--- /dev/null
+++ b/frontend/src/core/components/onboarding/tourUtils.ts
@@ -0,0 +1,110 @@
+/**
+ * Waits for a CSS selector to appear in the DOM using MutationObserver.
+ * Resolves immediately if already present; resolves after timeoutMs if it
+ * never appears (no throw — tour steps are best-effort).
+ */
+export function waitForElement(
+ selector: string,
+ timeoutMs = 7000,
+): Promise<void> {
+ return new Promise((resolve) => {
+ if (typeof document === "undefined") {
+ resolve();
+ return;
+ }
+
+ if (document.querySelector(selector)) {
+ resolve();
+ return;
+ }
+
+ const observer = new MutationObserver(() => {
+ if (document.querySelector(selector)) {
+ clearTimeout(timer);
+ observer.disconnect();
+ resolve();
+ }
+ });
+
+ const timer = setTimeout(() => {
+ observer.disconnect();
+ resolve();
+ }, timeoutMs);
+
+ observer.observe(document.body, { childList: true, subtree: true });
+ });
+}
+
+const nudgeReactour = () => {
+ window.dispatchEvent(new Event("resize"));
+ requestAnimationFrame(() => window.dispatchEvent(new Event("resize")));
+};
+
+/**
+ * Waits for a CSS selector to be present AND have a non-zero bounding box,
+ * then nudges Reactour to recalculate its spotlight position.
+ *
+ * Uses MutationObserver to detect element insertion, then ResizeObserver to
+ * detect when the element receives layout dimensions.
+ */
+export function waitForHighlightable(
+ selector: string,
+ timeoutMs = 7000,
+): Promise<void> {
+ return new Promise((resolve) => {
+ if (typeof document === "undefined") {
+ resolve();
+ return;
+ }
+
+ let mutationObserver: MutationObserver | null = null;
+ let resizeObserver: ResizeObserver | null = null;
+
+ const cleanup = () => {
+ mutationObserver?.disconnect();
+ resizeObserver?.disconnect();
+ };
+
+ const done = () => {
+ clearTimeout(timer);
+ cleanup();
+ nudgeReactour();
+ resolve();
+ };
+
+ const timer = setTimeout(done, timeoutMs);
+
+ const watchLayout = (el: HTMLElement) => {
+ if (el.getClientRects().length > 0) {
+ done();
+ return;
+ }
+ resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ if (entry.contentRect.width > 0 || entry.contentRect.height > 0) {
+ done();
+ return;
+ }
+ }
+ });
+ resizeObserver.observe(el);
+ };
+
+ const el = document.querySelector<HTMLElement>(selector);
+ if (el) {
+ watchLayout(el);
+ return;
+ }
+
+ mutationObserver = new MutationObserver(() => {
+ const found = document.querySelector<HTMLElement>(selector);
+ if (found) {
+ mutationObserver!.disconnect();
+ mutationObserver = null;
+ watchLayout(found);
+ }
+ });
+
+ mutationObserver.observe(document.body, { childList: true, subtree: true });
+ });
+}
diff --git a/frontend/src/core/components/onboarding/userStepsConfig.ts b/frontend/src/core/components/onboarding/userStepsConfig.ts
index f5805cbf68..e8a52803da 100644
--- a/frontend/src/core/components/onboarding/userStepsConfig.ts
+++ b/frontend/src/core/components/onboarding/userStepsConfig.ts
@@ -1,5 +1,9 @@
import type { StepType } from "@reactour/tour";
import type { TFunction } from "i18next";
+import {
+ waitForElement,
+ waitForHighlightable,
+} from "@app/components/onboarding/tourUtils";
export enum TourStep {
ALL_TOOLS,
@@ -26,9 +30,11 @@ interface UserStepActions {
loadSampleFile: () => void;
switchToActiveFiles: () => void;
pinFile: () => void;
+ revealFileCardHoverMenu: () => void;
modifyCropSettings: () => void;
executeTool: () => void;
openFilesModal: () => void;
+ openSettingsHelpSection: () => void;
}
interface CreateUserStepsConfigArgs {
@@ -48,9 +54,11 @@ export function createUserStepsConfig({
loadSampleFile,
switchToActiveFiles,
pinFile,
+ revealFileCardHoverMenu,
modifyCropSettings,
executeTool,
openFilesModal,
+ openSettingsHelpSection,
} = actions;
return {
@@ -95,7 +103,7 @@ export function createUserStepsConfig({
),
position: "right",
padding: 10,
- action: () => openFilesModal(),
+ actionAfter: () => openFilesModal(),
},
[TourStep.FILE_SOURCES]: {
selector: '[data-tour="file-sources"]',
@@ -105,6 +113,10 @@ export function createUserStepsConfig({
),
position: "right",
padding: 0,
+ action: async () => {
+ await waitForElement('[data-tour="file-sources"]', 5000);
+ await waitForHighlightable('[data-tour="file-sources"]', 5000);
+ },
actionAfter: () => {
loadSampleFile();
closeFilesModal();
@@ -184,16 +196,22 @@ export function createUserStepsConfig({
),
position: "left",
padding: 10,
- action: () => pinFile(),
+ action: () => revealFileCardHoverMenu(),
+ actionAfter: () => pinFile(),
},
[TourStep.WRAP_UP]: {
- selector: '[data-tour="help-button"]',
+ selector: '[data-tour="admin-help-nav"]',
content: t(
"onboarding.wrapUp",
- "You're all set! You've learnt about the main areas of the app and how to use them. Click the <strong>Help</strong> button whenever you like to see this tour again.",
+ "You're all set! You can replay this tour anytime — just open <strong>Settings</strong> and find it here in the <strong>Tours</strong> section under Help.",
),
position: "right",
padding: 10,
+ action: async () => {
+ openSettingsHelpSection();
+ await waitForElement('[data-tour="admin-help-nav"]', 5000);
+ await waitForHighlightable('[data-tour="admin-help-nav"]', 5000);
+ },
},
};
}
diff --git a/frontend/src/core/components/onboarding/whatsNewStepsConfig.ts b/frontend/src/core/components/onboarding/whatsNewStepsConfig.ts
index 4501d89739..a5ba0b8c33 100644
--- a/frontend/src/core/components/onboarding/whatsNewStepsConfig.ts
+++ b/frontend/src/core/components/onboarding/whatsNewStepsConfig.ts
@@ -1,58 +1,14 @@
import type { StepType } from "@reactour/tour";
import type { TFunction } from "i18next";
-
-async function waitForElement(
- selector: string,
- timeoutMs = 7000,
- intervalMs = 100,
-): Promise<void> {
- if (typeof document === "undefined") return;
- const start = Date.now();
- // Immediate hit
- if (document.querySelector(selector)) return;
-
- return new Promise((resolve) => {
- const check = () => {
- if (document.querySelector(selector) || Date.now() - start >= timeoutMs) {
- resolve();
- return;
- }
- setTimeout(check, intervalMs);
- };
- check();
- });
-}
-
-async function waitForHighlightable(
- selector: string,
- timeoutMs = 7000,
- intervalMs = 500,
-): Promise<void> {
- if (typeof document === "undefined") return;
- const start = Date.now();
-
- return new Promise((resolve) => {
- const check = () => {
- const el = document.querySelector<HTMLElement>(selector);
- const isVisible = !!el && el.getClientRects().length > 0;
- if (isVisible || Date.now() - start >= timeoutMs) {
- // Nudge Reactour to recalc positions in case layout shifted
- window.dispatchEvent(new Event("resize"));
- requestAnimationFrame(() => window.dispatchEvent(new Event("resize")));
- resolve();
- return;
- }
- setTimeout(check, intervalMs);
- };
- check();
- });
-}
+import {
+ waitForElement,
+ waitForHighlightable,
+} from "@app/components/onboarding/tourUtils";
export enum WhatsNewTourStep {
QUICK_ACCESS,
LEFT_PANEL,
FILE_UPLOAD,
- RIGHT_RAIL,
TOP_BAR,
PAGE_EDITOR_VIEW,
ACTIVE_FILES_VIEW,
@@ -68,7 +24,6 @@ interface WhatsNewStepActions {
switchToViewer: () => void;
switchToPageEditor: () => void;
switchToActiveFiles: () => void;
- selectFirstFile: () => void;
}
interface CreateWhatsNewStepsConfigArgs {
@@ -89,7 +44,6 @@ export function createWhatsNewStepsConfig({
switchToViewer,
switchToPageEditor,
switchToActiveFiles,
- selectFirstFile,
} = actions;
return {
@@ -124,34 +78,15 @@ export function createWhatsNewStepsConfig({
),
position: "right",
padding: 10,
- action: async () => {
- openFilesModal();
- await waitForElement('[data-tour="file-sources"]', 5000, 100);
- },
actionAfter: async () => {
+ openFilesModal();
+ await waitForElement('[data-tour="file-sources"]', 5000);
await Promise.resolve(loadSampleFile());
closeFilesModal();
switchToViewer();
// wait for file render and top controls to mount
- await waitForElement('[data-tour="view-switcher"]', 7000, 100);
- await waitForHighlightable('[data-tour="view-switcher"]', 7000, 500);
- },
- },
- [WhatsNewTourStep.RIGHT_RAIL]: {
- selector: '[data-tour="right-rail-controls"]',
- highlightedSelectors: [
- '[data-tour="right-rail-controls"]',
- '[data-tour="right-rail-settings"]',
- ],
- content: t(
- "onboarding.whatsNew.rightRail",
- "The <strong>Right Rail</strong> holds quick actions to select files, change theme or language, and download results.",
- ),
- position: "left",
- padding: 10,
- action: async () => {
- await waitForElement('[data-tour="right-rail-controls"]', 7000, 100);
- selectFirstFile();
+ await waitForElement('[data-tour="view-switcher"]', 7000);
+ await waitForHighlightable('[data-tour="view-switcher"]', 7000);
},
},
[WhatsNewTourStep.TOP_BAR]: {
@@ -165,8 +100,8 @@ export function createWhatsNewStepsConfig({
// Ensure the switcher has mounted before this step renders
action: async () => {
switchToViewer();
- await waitForElement('[data-tour="view-switcher"]', 7000, 100);
- await waitForHighlightable('[data-tour="view-switcher"]', 7000, 500);
+ await waitForElement('[data-tour="view-switcher"]', 7000);
+ await waitForHighlightable('[data-tour="view-switcher"]', 7000);
},
},
[WhatsNewTourStep.PAGE_EDITOR_VIEW]: {
@@ -179,8 +114,8 @@ export function createWhatsNewStepsConfig({
padding: 8,
action: async () => {
switchToPageEditor();
- await waitForElement('[data-tour="view-switcher"]', 7000, 100);
- await waitForHighlightable('[data-tour="view-switcher"]', 7000, 500);
+ await waitForElement('[data-tour="view-switcher"]', 7000);
+ await waitForHighlightable('[data-tour="view-switcher"]', 7000);
},
},
[WhatsNewTourStep.ACTIVE_FILES_VIEW]: {
@@ -193,8 +128,8 @@ export function createWhatsNewStepsConfig({
padding: 8,
action: async () => {
switchToActiveFiles();
- await waitForElement('[data-tour="view-switcher"]', 7000, 100);
- await waitForHighlightable('[data-tour="view-switcher"]', 7000, 500);
+ await waitForElement('[data-tour="view-switcher"]', 7000);
+ await waitForHighlightable('[data-tour="view-switcher"]', 7000);
},
},
[WhatsNewTourStep.WRAP_UP]: {
diff --git a/frontend/src/core/components/pageEditor/PageEditor.tsx b/frontend/src/core/components/pageEditor/PageEditor.tsx
index ea78c7a722..dcbb0f0879 100644
--- a/frontend/src/core/components/pageEditor/PageEditor.tsx
+++ b/frontend/src/core/components/pageEditor/PageEditor.tsx
@@ -17,7 +17,7 @@ import { GRID_CONSTANTS } from "@app/components/pageEditor/constants";
import { useInitialPageDocument } from "@app/components/pageEditor/hooks/useInitialPageDocument";
import { usePageDocument } from "@app/components/pageEditor/hooks/usePageDocument";
import { usePageEditorState } from "@app/components/pageEditor/hooks/usePageEditorState";
-import { usePageEditorRightRailButtons } from "@app/components/pageEditor/pageEditorRightRailButtons";
+import { usePageEditorWorkbenchBarButtons } from "@app/components/pageEditor/pageEditorWorkbenchBarButtons";
import { useFileColorMap } from "@app/components/pageEditor/hooks/useFileColorMap";
import { useWheelZoom } from "@app/hooks/useWheelZoom";
import { useEditedDocumentState } from "@app/components/pageEditor/hooks/useEditedDocumentState";
@@ -168,6 +168,16 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
}, [pageEditorFiles]);
const activeFilesSignature = selectors.getFilesSignature();
+ // Check if there are any PDF files in FileContext (bypasses fileOrder, which is
+ // populated asynchronously via effect). Used to avoid a one-render flash of
+ // "No PDF files loaded" when PageEditor first mounts after files are added.
+ const hasPdfFiles = useMemo(() => {
+ return state.files.ids.some((id) => {
+ const stub = selectors.getStirlingFileStub(id);
+ return stub?.name?.toLowerCase().endsWith(".pdf") ?? false;
+ });
+ }, [state.files.ids, selectors]);
+
// UI state
const globalProcessing = state.ui.isProcessing;
@@ -448,11 +458,10 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
unregisterNavigationWarningHandlers,
]);
- // Derived values for right rail and usePageEditorRightRailButtons (must be after displayDocument)
+ // Derived values for usePageEditorWorkbenchBarButtons (must be after displayDocument)
const selectedPageCount = selectedPageIds.length;
- const activeFileIds = selectedFileIds;
- usePageEditorRightRailButtons({
+ usePageEditorWorkbenchBarButtons({
totalPages,
selectedPageCount,
csvInput,
@@ -466,8 +475,6 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
onExportSelected,
onSaveChanges: applyChanges,
exportLoading,
- activeFileCount: activeFileIds.length,
- closePdf,
});
// Export preview function - defined after export functions to avoid circular dependency
@@ -677,23 +684,21 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
>
<LoadingOverlay visible={globalProcessing && !initialDocument} />
- {!initialDocument &&
- !globalProcessing &&
- selectedFileIds.length === 0 && (
- <Center h="100%">
- <Stack align="center" gap="md">
- <Text size="lg" c="dimmed">
- 📄
- </Text>
- <Text c="dimmed">No PDF files loaded</Text>
- <Text size="sm" c="dimmed">
- Add files to start editing pages
- </Text>
- </Stack>
- </Center>
- )}
-
- {!initialDocument && globalProcessing && (
+ {!initialDocument && !globalProcessing && !hasPdfFiles && (
+ <Center h="100%">
+ <Stack align="center" gap="md">
+ <Text size="lg" c="dimmed">
+ 📄
+ </Text>
+ <Text c="dimmed">No PDF files loaded</Text>
+ <Text size="sm" c="dimmed">
+ Add files to start editing pages
+ </Text>
+ </Stack>
+ </Center>
+ )}
+
+ {!initialDocument && (globalProcessing || hasPdfFiles) && (
<Box p={0}>
<SkeletonLoader type="controls" />
<SkeletonLoader type="pageGrid" count={8} />
diff --git a/frontend/src/core/components/pageEditor/PageEditorControls.tsx b/frontend/src/core/components/pageEditor/PageEditorControls.tsx
index 7fba942688..a2eaac84d3 100644
--- a/frontend/src/core/components/pageEditor/PageEditorControls.tsx
+++ b/frontend/src/core/components/pageEditor/PageEditorControls.tsx
@@ -25,7 +25,6 @@ interface PageEditorControlsProps {
onPageBreak: () => void;
onPageBreakAll: () => void;
- // Export functions (moved to right rail)
onExportAll: () => void;
exportLoading: boolean;
@@ -138,9 +137,7 @@ const PageEditorControls = ({
disabled={!canUndo}
variant="subtle"
style={{
- color: canUndo
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ color: canUndo ? "var(--text-secondary)" : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -154,9 +151,7 @@ const PageEditorControls = ({
disabled={!canRedo}
variant="subtle"
style={{
- color: canRedo
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ color: canRedo ? "var(--text-secondary)" : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -183,8 +178,8 @@ const PageEditorControls = ({
style={{
color:
selectedPageIds.length > 0
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ ? "var(--text-secondary)"
+ : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -200,8 +195,8 @@ const PageEditorControls = ({
style={{
color:
selectedPageIds.length > 0
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ ? "var(--text-secondary)"
+ : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -217,8 +212,8 @@ const PageEditorControls = ({
style={{
color:
selectedPageIds.length > 0
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ ? "var(--text-secondary)"
+ : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -234,8 +229,8 @@ const PageEditorControls = ({
style={{
color:
selectedPageIds.length > 0
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ ? "var(--text-secondary)"
+ : "var(--text-muted)",
}}
radius="md"
size="lg"
@@ -251,8 +246,8 @@ const PageEditorControls = ({
style={{
color:
selectedPageIds.length > 0
- ? "var(--right-rail-icon)"
- : "var(--right-rail-icon-disabled)",
+ ? "var(--text-secondary)"
+ : "var(--text-muted)",
}}
radius="md"
size="lg"
diff --git a/frontend/src/core/components/pageEditor/PageSelectByNumberButton.tsx b/frontend/src/core/components/pageEditor/PageSelectByNumberButton.tsx
index 1b35bed994..fff0b8ef8f 100644
--- a/frontend/src/core/components/pageEditor/PageSelectByNumberButton.tsx
+++ b/frontend/src/core/components/pageEditor/PageSelectByNumberButton.tsx
@@ -27,19 +27,18 @@ export default function PageSelectByNumberButton({
return (
<Tooltip
content={label}
- position="left"
+ position="bottom"
offset={12}
arrow
portalTarget={document.body}
>
- <div className={`right-rail-fade enter`}>
+ <div>
<Popover position="left" withArrow shadow="md" offset={8}>
<Popover.Target>
<div style={{ display: "inline-flex" }}>
<ActionIcon
variant="subtle"
radius="md"
- className="right-rail-icon"
disabled={disabled || totalPages === 0}
aria-label={label}
>
diff --git a/frontend/src/core/components/pageEditor/pageEditorRightRailButtons.tsx b/frontend/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx
similarity index 78%
rename from frontend/src/core/components/pageEditor/pageEditorRightRailButtons.tsx
rename to frontend/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx
index 97a5ffff16..ea47676c05 100644
--- a/frontend/src/core/components/pageEditor/pageEditorRightRailButtons.tsx
+++ b/frontend/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx
@@ -1,13 +1,13 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import {
- useRightRailButtons,
- RightRailButtonWithAction,
-} from "@app/hooks/useRightRailButtons";
+ useWorkbenchBarButtons,
+ WorkbenchBarButtonWithAction,
+} from "@app/hooks/useWorkbenchBarButtons";
import LocalIcon from "@app/components/shared/LocalIcon";
import PageSelectByNumberButton from "@app/components/pageEditor/PageSelectByNumberButton";
-interface PageEditorRightRailButtonsParams {
+interface PageEditorWorkbenchBarButtonsParams {
totalPages: number;
selectedPageCount: number;
csvInput: string;
@@ -21,12 +21,10 @@ interface PageEditorRightRailButtonsParams {
onExportSelected: () => void;
onSaveChanges: () => void;
exportLoading: boolean;
- activeFileCount: number;
- closePdf: () => void;
}
-export function usePageEditorRightRailButtons(
- params: PageEditorRightRailButtonsParams,
+export function usePageEditorWorkbenchBarButtons(
+ params: PageEditorWorkbenchBarButtonsParams,
) {
const {
totalPages,
@@ -42,31 +40,27 @@ export function usePageEditorRightRailButtons(
onExportSelected,
onSaveChanges,
exportLoading,
- activeFileCount,
- closePdf,
} = params;
const { t, i18n } = useTranslation();
// Lift i18n labels out of memo for clarity
- const selectAllLabel = t("rightRail.selectAll", "Select All");
- const deselectAllLabel = t("rightRail.deselectAll", "Deselect All");
+ const selectAllLabel = t("workbenchBar.selectAll", "Select All");
+ const deselectAllLabel = t("workbenchBar.deselectAll", "Deselect All");
const selectByNumberLabel = t(
- "rightRail.selectByNumber",
+ "workbenchBar.selectByNumber",
"Select by Page Numbers",
);
const deleteSelectedLabel = t(
- "rightRail.deleteSelected",
+ "workbenchBar.deleteSelected",
"Delete Selected Pages",
);
const exportSelectedLabel = t(
- "rightRail.exportSelected",
+ "workbenchBar.exportSelected",
"Export Selected Pages",
);
- const saveChangesLabel = t("rightRail.saveChanges", "Save Changes");
- const closePdfLabel = t("rightRail.closePdf", "Close PDF");
-
- const buttons = useMemo<RightRailButtonWithAction[]>(() => {
+ const saveChangesLabel = t("workbenchBar.saveChanges", "Save Changes");
+ const buttons = useMemo<WorkbenchBarButtonWithAction[]>(() => {
return [
{
id: "page-select-all",
@@ -156,17 +150,6 @@ export function usePageEditorRightRailButtons(
visible: totalPages > 0,
onClick: onSaveChanges,
},
- {
- id: "page-close-pdf",
- icon: <LocalIcon icon="close-rounded" width="1.5rem" height="1.5rem" />,
- tooltip: closePdfLabel,
- ariaLabel: closePdfLabel,
- section: "top" as const,
- order: 60,
- disabled: activeFileCount === 0,
- visible: activeFileCount > 0,
- onClick: closePdf,
- },
];
}, [
t,
@@ -177,7 +160,6 @@ export function usePageEditorRightRailButtons(
deleteSelectedLabel,
exportSelectedLabel,
saveChangesLabel,
- closePdfLabel,
totalPages,
selectedPageCount,
csvInput,
@@ -191,9 +173,7 @@ export function usePageEditorRightRailButtons(
onExportSelected,
onSaveChanges,
exportLoading,
- activeFileCount,
- closePdf,
]);
- useRightRailButtons(buttons);
+ useWorkbenchBarButtons(buttons);
}
diff --git a/frontend/src/core/components/rightRail/RightRailFooterExtensions.tsx b/frontend/src/core/components/rightRail/RightRailFooterExtensions.tsx
deleted file mode 100644
index 1a90673d6a..0000000000
--- a/frontend/src/core/components/rightRail/RightRailFooterExtensions.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-interface RightRailFooterExtensionsProps {
- className?: string;
-}
-
-export function RightRailFooterExtensions(
- _props: RightRailFooterExtensionsProps,
-) {
- return null;
-}
diff --git a/frontend/src/core/components/shared/AppConfigModal.tsx b/frontend/src/core/components/shared/AppConfigModal.tsx
index 3e031f600e..a8d9b706d3 100644
--- a/frontend/src/core/components/shared/AppConfigModal.tsx
+++ b/frontend/src/core/components/shared/AppConfigModal.tsx
@@ -108,11 +108,26 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({
const runningEE = config?.runningEE ?? false;
const loginEnabled = config?.enableLogin ?? false;
+ const handleClose = useCallback(async () => {
+ const canProceed = await confirmIfDirty();
+ if (!canProceed) return;
+
+ // Navigate back to home when closing modal
+ navigate("/", { replace: true });
+ onClose();
+ }, [confirmIfDirty, navigate, onClose]);
+
+ // Synchronous wrapper for contexts (e.g. tour buttons) that need () => void
+ const handleCloseSync = useCallback(() => {
+ void handleClose();
+ }, [handleClose]);
+
// Left navigation structure and icons
const configNavSections = useConfigNavSections(
isAdmin,
runningEE,
loginEnabled,
+ handleCloseSync,
);
const activeLabel = useMemo(() => {
@@ -131,15 +146,6 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({
return null;
}, [configNavSections, active]);
- const handleClose = useCallback(async () => {
- const canProceed = await confirmIfDirty();
- if (!canProceed) return;
-
- // Navigate back to home when closing modal
- navigate("/", { replace: true });
- onClose();
- }, [confirmIfDirty, navigate, onClose]);
-
const handleNavigation = useCallback(
async (key: NavKey) => {
const canProceed = await confirmIfDirty();
diff --git a/frontend/src/core/components/shared/BulkShareModal.tsx b/frontend/src/core/components/shared/BulkShareModal.tsx
index 72fc9a007d..978b321232 100644
--- a/frontend/src/core/components/shared/BulkShareModal.tsx
+++ b/frontend/src/core/components/shared/BulkShareModal.tsx
@@ -207,7 +207,7 @@ const BulkShareModal: React.FC<BulkShareModalProps> = ({
)}
</Text>
<Text size="sm" c="dimmed">
- {t("storageShare.fileCount", "{{count}} files selected", {
+ {t("storageShare.fileCount", "{{count}} files", {
count: files.length,
})}
</Text>
diff --git a/frontend/src/core/components/shared/BulkUploadToServerModal.tsx b/frontend/src/core/components/shared/BulkUploadToServerModal.tsx
index 8dd250851e..f0ff3be54e 100644
--- a/frontend/src/core/components/shared/BulkUploadToServerModal.tsx
+++ b/frontend/src/core/components/shared/BulkUploadToServerModal.tsx
@@ -116,7 +116,7 @@ const BulkUploadToServerModal: React.FC<BulkUploadToServerModalProps> = ({
)}
</Text>
<Text size="sm" c="dimmed">
- {t("storageUpload.fileCount", "{{count}} files selected", {
+ {t("storageUpload.fileCount", "{{count}} files", {
count: files.length,
})}
</Text>
diff --git a/frontend/src/core/components/shared/CloudStorageIcons.tsx b/frontend/src/core/components/shared/CloudStorageIcons.tsx
new file mode 100644
index 0000000000..2393a72f74
--- /dev/null
+++ b/frontend/src/core/components/shared/CloudStorageIcons.tsx
@@ -0,0 +1,79 @@
+import React from "react";
+
+interface CloudIconProps extends React.SVGProps<SVGSVGElement> {
+ colored?: boolean;
+}
+
+/**
+ * Google Drive icon with brand-color hover support.
+ * Pass `colored={true}` to render the official tri-color logo;
+ * omit / pass `colored={false}` for a uniform muted/current-color version.
+ */
+export function GoogleDriveIcon({ colored, ...rest }: CloudIconProps) {
+ return (
+ <svg viewBox="0 0 87.3 78" width={18} height={18} {...rest}>
+ <path
+ d="M6.6 66.85l3.85 6.65c.8 1.4 1.95 2.5 3.3 3.3l13.75-23.8H0c0 1.55.4 3.1 1.2 4.5z"
+ fill={colored ? "#0066DA" : "currentColor"}
+ opacity={colored ? 1 : 0.5}
+ />
+ <path
+ d="M43.65 25L29.9 1.2c-1.35.8-2.5 1.9-3.3 3.3L1.2 52.35c-.8 1.4-1.2 2.95-1.2 4.5h27.5z"
+ fill={colored ? "#00AC47" : "currentColor"}
+ opacity={colored ? 1 : 0.4}
+ />
+ <path
+ d="M73.55 76.8c1.35-.8 2.5-1.9 3.3-3.3l1.6-2.75 7.65-13.25c.8-1.4 1.2-2.95 1.2-4.5H59.85L73.55 76.8z"
+ fill={colored ? "#EA4335" : "currentColor"}
+ opacity={colored ? 1 : 0.5}
+ />
+ <path
+ d="M43.65 25L57.4 1.2c-1.35-.8-2.9-1.2-4.5-1.2H34.4c-1.6 0-3.15.45-4.5 1.2z"
+ fill={colored ? "#00832D" : "currentColor"}
+ opacity={colored ? 1 : 0.45}
+ />
+ <path
+ d="M59.85 53H27.5l-13.75 23.8c1.35.8 2.9 1.2 4.5 1.2h50.8c1.6 0 3.15-.45 4.5-1.2z"
+ fill={colored ? "#2684FC" : "currentColor"}
+ opacity={colored ? 1 : 0.55}
+ />
+ <path
+ d="M73.4 26.5L60.7 4.5c-.8-1.4-1.95-2.5-3.3-3.3L43.65 25l16.2 28h27.45c0-1.55-.4-3.1-1.2-4.5z"
+ fill={colored ? "#FFBA00" : "currentColor"}
+ opacity={colored ? 1 : 0.5}
+ />
+ </svg>
+ );
+}
+
+/**
+ * OneDrive icon with brand-color hover support.
+ * FOR FUTURE USE — OneDrive integration is not yet implemented.
+ */
+export function OneDriveIcon({ colored, ...rest }: CloudIconProps) {
+ return (
+ <svg viewBox="0 0 24 24" width={18} height={18} {...rest}>
+ <path
+ d="M19.35 10.04A7.49 7.49 0 0012 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 000 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z"
+ fill={colored ? "#0078D4" : "currentColor"}
+ opacity={colored ? 1 : 0.5}
+ />
+ </svg>
+ );
+}
+
+/**
+ * Dropbox icon with brand-color hover support.
+ * FOR FUTURE USE — Dropbox integration is not yet implemented.
+ */
+export function DropboxIcon({ colored, ...rest }: CloudIconProps) {
+ return (
+ <svg viewBox="0 0 16 16" width={18} height={18} {...rest}>
+ <path
+ d="M8.01 4.555L4.005 7.11 8.01 9.665 4.005 12.22 0 9.651l4.005-2.555L0 4.555 4.005 2 8.01 4.555zm-4.026 8.487l4.006-2.555 4.005 2.555-4.005 2.555-4.006-2.555zm4.026-3.39l4.005-2.556L8.01 4.555 11.995 2 16 4.555l-4.005 2.555L16 9.665l-4.005 2.555L8.01 9.652z"
+ fill={colored ? "#0061FF" : "currentColor"}
+ opacity={colored ? 1 : 0.5}
+ />
+ </svg>
+ );
+}
diff --git a/frontend/src/core/components/shared/FileCard.tsx b/frontend/src/core/components/shared/FileCard.tsx
index 6bb1f8ee84..2837f22a86 100644
--- a/frontend/src/core/components/shared/FileCard.tsx
+++ b/frontend/src/core/components/shared/FileCard.tsx
@@ -7,21 +7,18 @@ import {
Badge,
Button,
Box,
- Image,
- ThemeIcon,
ActionIcon,
Tooltip,
- Loader,
} from "@mantine/core";
import { useTranslation } from "react-i18next";
-import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import StorageIcon from "@mui/icons-material/Storage";
import VisibilityIcon from "@mui/icons-material/Visibility";
import EditIcon from "@mui/icons-material/Edit";
import { StirlingFileStub } from "@app/types/fileContext";
import { getFileSize, getFileDate } from "@app/utils/fileUtils";
-import { useIndexedDBThumbnail } from "@app/hooks/useIndexedDBThumbnail";
+import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
+import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
interface FileCardProps {
file: File;
@@ -47,15 +44,15 @@ const FileCard = ({
isSupported = true,
}: FileCardProps) => {
const { t } = useTranslation();
- // Use record thumbnail if available, otherwise fall back to IndexedDB lookup
- const { thumbnail: indexedDBThumb, isGenerating } =
- useIndexedDBThumbnail(fileStub);
- const thumb = fileStub?.thumbnailUrl || indexedDBThumb;
+ const {
+ isEncrypted,
+ thumbnail: thumb,
+ isGenerating,
+ } = useFileThumbnail(fileStub);
const [isHovered, setIsHovered] = useState(false);
- // Show loading state during hydration: PDF file without thumbnail yet
const isPdf = file.type === "application/pdf";
- const isHydrating = isPdf && !thumb && !isGenerating;
+ const isHydrating = isPdf && !isEncrypted && !thumb && !isGenerating;
return (
<Card
@@ -73,8 +70,7 @@ const FileCard = ({
? "2px solid var(--mantine-color-blue-6)"
: undefined,
backgroundColor: isSelected ? "var(--mantine-color-blue-0)" : undefined,
- opacity: isSupported ? 1 : 0.5,
- filter: isSupported ? "none" : "grayscale(50%)",
+ opacity: 1,
}}
onDoubleClick={onDoubleClick}
onMouseEnter={() => setIsHovered(true)}
@@ -146,51 +142,13 @@ const FileCard = ({
)}
</div>
)}
- {thumb ? (
- <Image
- src={thumb}
- alt="PDF thumbnail"
- height={110}
- width={80}
- fit="contain"
- radius="sm"
- />
- ) : isGenerating || isHydrating ? (
- <Stack align="center" justify="center" gap="xs">
- <Loader size="sm" />
- <Text size="xs" c="dimmed">
- Loading...
- </Text>
- </Stack>
- ) : (
- <div
- style={{
- display: "flex",
- flexDirection: "column",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <ThemeIcon
- variant="light"
- color={file.size > 100 * 1024 * 1024 ? "orange" : "red"}
- size={60}
- radius="sm"
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <PictureAsPdfIcon style={{ fontSize: 40 }} />
- </ThemeIcon>
- {file.size > 100 * 1024 * 1024 && (
- <Text size="xs" c="dimmed" mt={4}>
- Large File
- </Text>
- )}
- </div>
- )}
+ <DocumentThumbnail
+ file={file}
+ thumbnail={thumb || undefined}
+ isEncrypted={isEncrypted}
+ isLoading={isGenerating || isHydrating}
+ iconSize="3rem"
+ />
</Box>
<Text fw={500} size="sm" lineClamp={1} ta="center">
diff --git a/frontend/src/core/components/shared/FileDocIcon.tsx b/frontend/src/core/components/shared/FileDocIcon.tsx
new file mode 100644
index 0000000000..135162c54d
--- /dev/null
+++ b/frontend/src/core/components/shared/FileDocIcon.tsx
@@ -0,0 +1,204 @@
+export type FileDocVariant =
+ | "pdf"
+ | "spreadsheet"
+ | "doc"
+ | "image"
+ | "archive"
+ | "code"
+ | "generic";
+
+export const VARIANT_COLORS: Record<FileDocVariant, string> = {
+ pdf: "#DC2626",
+ spreadsheet: "#16a34a",
+ doc: "#2563eb",
+ image: "#7c3aed",
+ archive: "#ea580c",
+ code: "#0891b2",
+ generic: "#71717a",
+};
+
+export function FileDocIcon({
+ color,
+ variant,
+ className,
+ style,
+}: {
+ color?: string;
+ variant: FileDocVariant;
+ className?: string;
+ style?: React.CSSProperties;
+}) {
+ color ??= VARIANT_COLORS[variant];
+ const foldX = 10.5;
+ const foldY = 5.5;
+
+ let interior: React.ReactNode;
+ if (variant === "spreadsheet") {
+ // Outer border of the grid
+ const gx1 = 3,
+ gy1 = 8,
+ gx2 = 13,
+ gy2 = 17;
+ // Column divider x, row divider y positions
+ const colX = 8;
+ const row1Y = 11,
+ row2Y = 14;
+ interior = (
+ <g opacity="0.7" stroke={color} strokeWidth="1" fill="none">
+ <rect x={gx1} y={gy1} width={gx2 - gx1} height={gy2 - gy1} rx="0.5" />
+ <line x1={colX} y1={gy1} x2={colX} y2={gy2} />
+ <line x1={gx1} y1={row1Y} x2={gx2} y2={row1Y} />
+ <line x1={gx1} y1={row2Y} x2={gx2} y2={row2Y} />
+ </g>
+ );
+ } else if (variant === "image") {
+ interior = (
+ <>
+ <polyline
+ points="2.5,16 5.5,11.5 8,14 10,12 13.5,16"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ fill="none"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ <circle
+ cx="11"
+ cy="9.5"
+ r="1.3"
+ stroke={color}
+ strokeWidth="1"
+ opacity="0.6"
+ fill="none"
+ />
+ </>
+ );
+ } else if (variant === "code") {
+ interior = (
+ <>
+ <polyline
+ points="6,9.5 3.5,12.5 6,15.5"
+ stroke={color}
+ strokeWidth="1.3"
+ opacity="0.7"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <polyline
+ points="10,9.5 12.5,12.5 10,15.5"
+ stroke={color}
+ strokeWidth="1.3"
+ opacity="0.7"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </>
+ );
+ } else if (variant === "archive") {
+ interior = (
+ <>
+ <line
+ x1="5"
+ y1="9.5"
+ x2="11"
+ y2="9.5"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeDasharray="2,1.5"
+ strokeLinecap="round"
+ />
+ <line
+ x1="5"
+ y1="12"
+ x2="11"
+ y2="12"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeDasharray="2,1.5"
+ strokeLinecap="round"
+ />
+ <line
+ x1="5"
+ y1="14.5"
+ x2="11"
+ y2="14.5"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeDasharray="2,1.5"
+ strokeLinecap="round"
+ />
+ </>
+ );
+ } else {
+ // pdf, doc, generic — text lines
+ interior = (
+ <>
+ <line
+ x1="3.5"
+ y1="9.5"
+ x2="12.5"
+ y2="9.5"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeLinecap="round"
+ />
+ <line
+ x1="3.5"
+ y1="12"
+ x2="12.5"
+ y2="12"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeLinecap="round"
+ />
+ <line
+ x1="3.5"
+ y1="14.5"
+ x2="8.5"
+ y2="14.5"
+ stroke={color}
+ strokeWidth="1.1"
+ opacity="0.6"
+ strokeLinecap="round"
+ />
+ </>
+ );
+ }
+
+ return (
+ <svg
+ className={className}
+ style={{ width: 16, height: 20, ...style }}
+ viewBox="0 0 16 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ {/* Document outline with top-right page fold */}
+ <path
+ d={`M 1.5,1 H ${foldX} L 15,${foldY} V 18.5 Q 15,19 14.5,19 H 1.5 Q 1,19 1,18.5 V 1.5 Q 1,1 1.5,1 Z`}
+ stroke={color}
+ strokeWidth="1.3"
+ fill="none"
+ strokeLinejoin="round"
+ />
+ {/* Fold corner triangle */}
+ <path
+ d={`M ${foldX},1 L ${foldX},${foldY} L 15,${foldY} Z`}
+ stroke={color}
+ strokeWidth="1.3"
+ fill={color}
+ fillOpacity="0.2"
+ strokeLinejoin="round"
+ />
+ {interior}
+ </svg>
+ );
+}
diff --git a/frontend/src/core/components/shared/FileDropdownMenu.tsx b/frontend/src/core/components/shared/FileDropdownMenu.tsx
index ce38049af0..9a0b7ee5b7 100644
--- a/frontend/src/core/components/shared/FileDropdownMenu.tsx
+++ b/frontend/src/core/components/shared/FileDropdownMenu.tsx
@@ -51,7 +51,7 @@ export const FileDropdownMenu: React.FC<FileDropdownMenuProps> = ({
</Menu.Target>
<Menu.Dropdown
style={{
- backgroundColor: "var(--right-rail-bg)",
+ backgroundColor: "var(--bg-file-manager)",
border: "1px solid var(--border-subtle)",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
diff --git a/frontend/src/core/components/shared/FilePickerModal.tsx b/frontend/src/core/components/shared/FilePickerModal.tsx
index 16f35f9fb1..da1bb91b6c 100644
--- a/frontend/src/core/components/shared/FilePickerModal.tsx
+++ b/frontend/src/core/components/shared/FilePickerModal.tsx
@@ -8,13 +8,11 @@ import {
Checkbox,
ScrollArea,
Box,
- Image,
Badge,
- ThemeIcon,
SimpleGrid,
} from "@mantine/core";
-import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useTranslation } from "react-i18next";
+import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
import { FileId } from "@app/types/file";
import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
@@ -200,26 +198,23 @@ const FilePickerModal = ({
height: 80,
border: "1px solid var(--mantine-color-gray-3)",
borderRadius: 4,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- backgroundColor: "var(--mantine-color-gray-0)",
+ backgroundColor: "white",
flexShrink: 0,
+ overflow: "hidden",
}}
>
- {file.thumbnail ? (
- <Image
- src={file.thumbnail}
- alt="PDF thumbnail"
- height={70}
- width={50}
- fit="contain"
- />
- ) : (
- <ThemeIcon variant="light" color="red" size={40}>
- <PictureAsPdfIcon style={{ fontSize: 24 }} />
- </ThemeIcon>
- )}
+ <DocumentThumbnail
+ file={file}
+ thumbnail={
+ file.processedFile?.isEncrypted
+ ? undefined
+ : file.thumbnail
+ }
+ isEncrypted={Boolean(
+ file.processedFile?.isEncrypted,
+ )}
+ iconSize="2rem"
+ />
</Box>
{/* File info */}
diff --git a/frontend/src/core/components/shared/FileSelectorPicker.module.css b/frontend/src/core/components/shared/FileSelectorPicker.module.css
new file mode 100644
index 0000000000..7d9b0251db
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSelectorPicker.module.css
@@ -0,0 +1,283 @@
+/* ── Trigger ─────────────────────────────────────── */
+.trigger {
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-md);
+ padding: 0.5rem 0.75rem;
+ background: var(--bg-surface);
+ cursor: pointer;
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ user-select: none;
+ transition:
+ border-color 0.12s ease,
+ box-shadow 0.12s ease;
+}
+
+.trigger:hover:not(.triggerDisabled) {
+ border-color: var(--mantine-color-blue-5);
+}
+
+.triggerDisabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ pointer-events: none;
+}
+
+.triggerOpen {
+ border-color: var(--mantine-color-blue-5);
+ box-shadow: 0 0 0 2px
+ color-mix(in srgb, var(--mantine-color-blue-5) 20%, transparent);
+}
+
+/* ── Popover dropdown ────────────────────────────── */
+.dropdown {
+ padding: 0;
+ overflow: hidden;
+ border-radius: var(--radius-md) !important;
+ min-width: 340px;
+}
+
+/* ── Header area (tabs + sort) ───────────────────── */
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.3rem 0.45rem;
+ gap: 0.4rem;
+ border-bottom: 1px solid var(--border-default);
+ background: var(--bg-surface);
+}
+
+.tabGroup {
+ display: flex;
+ align-items: stretch;
+ flex: 1;
+ min-width: 0;
+}
+
+/* One slim row: Saved files | Workbench | Upload (text only, no icon) */
+.slimTabBar {
+ display: flex;
+ align-items: stretch;
+ flex: 1;
+ min-width: 0;
+ min-height: 24px;
+ max-height: 26px;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-sm);
+ background: color-mix(
+ in srgb,
+ var(--mantine-color-default-hover) 85%,
+ transparent
+ );
+ padding: 1px;
+ gap: 1px;
+ box-sizing: border-box;
+}
+
+.slimTab,
+.slimTabActive {
+ flex: 1 1 0;
+ min-width: 0;
+ margin: 0;
+ border: none;
+ cursor: pointer;
+ font-size: 0.6875rem;
+ font-weight: 500;
+ line-height: 1.15;
+ letter-spacing: 0.01em;
+ padding: 1px 0.35rem;
+ border-radius: calc(var(--radius-sm) - 2px);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ transition:
+ background 0.1s ease,
+ color 0.1s ease;
+}
+
+.slimTab {
+ background: transparent;
+ color: var(--mantine-color-dimmed);
+}
+
+.slimTab:hover {
+ color: var(--mantine-color-text);
+ background: color-mix(in srgb, var(--mantine-color-body) 60%, transparent);
+}
+
+.slimTabActive {
+ background: var(--mantine-color-blue-filled);
+ color: #fff;
+}
+
+.slimTabUpload {
+ flex: 0 0 auto;
+ margin: 0;
+ border: none;
+ cursor: pointer;
+ font-size: 0.6875rem;
+ font-weight: 500;
+ line-height: 1.15;
+ padding: 1px 0.45rem;
+ border-radius: calc(var(--radius-sm) - 2px);
+ white-space: nowrap;
+ background: transparent;
+ color: var(--mantine-color-dimmed);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 2.75rem;
+}
+
+.slimTabUpload:hover:not(:disabled) {
+ color: var(--mantine-color-blue-filled);
+ background: color-mix(in srgb, var(--mantine-color-blue-1) 35%, transparent);
+}
+
+.slimTabUpload:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+/* ── Sort button group ───────────────────────────── */
+.sortGroup {
+ display: flex;
+ gap: 2px;
+ background: var(--mantine-color-default-hover);
+ border-radius: var(--radius-sm);
+ padding: 2px;
+}
+
+.sortBtn {
+ padding: 2px 8px;
+ font-size: 0.7rem;
+ border-radius: calc(var(--radius-sm) - 2px);
+ cursor: pointer;
+ border: none;
+ background: transparent;
+ color: var(--mantine-color-dimmed);
+ line-height: 1.6;
+ transition:
+ background 0.1s,
+ color 0.1s;
+ white-space: nowrap;
+}
+
+.sortBtn:hover {
+ color: var(--mantine-color-text);
+}
+
+.sortBtnActive {
+ background: var(--mantine-color-blue-filled);
+ color: white;
+}
+
+.sortArrow {
+ opacity: 0.85;
+ font-size: 0.65rem;
+ vertical-align: middle;
+}
+
+/* ── Search / filter row ─────────────────────────── */
+.searchRow {
+ padding: 0.3rem 0.45rem;
+ border-bottom: 1px solid var(--border-default);
+ background: var(--bg-surface);
+}
+
+.searchInput {
+ width: 100%;
+ box-sizing: border-box;
+ height: 1.625rem;
+ padding: 0 0.5rem;
+ font-size: 0.7rem;
+ border: 1px solid var(--border-subtle, var(--border-default));
+ border-radius: var(--radius-sm);
+ background: var(--mantine-color-default-hover);
+ color: var(--mantine-color-text);
+ outline: none;
+ transition: border-color 0.12s ease;
+}
+
+.searchInput::placeholder {
+ color: var(--mantine-color-dimmed);
+}
+
+.searchInput:focus {
+ border-color: var(--mantine-color-blue-5);
+}
+
+/* hide browser clear button in Safari */
+.searchInput::-webkit-search-cancel-button {
+ -webkit-appearance: none;
+}
+
+/* ── Scrollable file list ────────────────────────── */
+.list {
+ padding: 0;
+}
+
+/* ── Individual file row ─────────────────────────── */
+.fileItem {
+ width: 100%;
+ padding: 0.625rem 0.875rem;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ cursor: pointer;
+ background: transparent;
+ border: none;
+ border-top: 1px solid var(--border-default);
+ text-align: left;
+ transition: background 0.08s ease;
+}
+
+.fileItem:first-child {
+ border-top: none;
+}
+
+.fileItem:hover:not(:disabled) {
+ background: var(--mantine-color-default-hover);
+}
+
+.fileItem:disabled {
+ cursor: wait;
+}
+
+.fileItemContent {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.fileName {
+ font-size: 0.8125rem;
+ font-weight: 500;
+ color: var(--mantine-color-text);
+}
+
+.fileMeta {
+ font-size: 0.6875rem;
+ color: var(--mantine-color-dimmed);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* ── Empty / loading states ──────────────────────── */
+.emptyState {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 2.5rem 1rem;
+ flex-direction: column;
+ gap: 0.5rem;
+ color: var(--mantine-color-dimmed);
+}
diff --git a/frontend/src/core/components/shared/FileSelectorPicker.tsx b/frontend/src/core/components/shared/FileSelectorPicker.tsx
new file mode 100644
index 0000000000..feaa5f6b9f
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSelectorPicker.tsx
@@ -0,0 +1,632 @@
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
+import { createPortal } from "react-dom";
+import { Box, Popover, ScrollArea, Text, Loader } from "@mantine/core";
+import AddIcon from "@mui/icons-material/Add";
+import { useTranslation } from "react-i18next";
+import {
+ createStirlingFile,
+ createFileId,
+ createNewStirlingFileStub,
+} from "@app/types/fileContext";
+import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+import { useAllFiles } from "@app/contexts/FileContext";
+import { useIndexedDB } from "@app/contexts/IndexedDBContext";
+import { useFileContext } from "@app/contexts/file/fileHooks";
+import { useFileManager } from "@app/hooks/useFileManager";
+import { fileStorage } from "@app/services/fileStorage";
+import apiClient from "@app/services/apiClient";
+import {
+ parseContentDispositionFilename,
+ extractLatestFilesFromBundle,
+} from "@app/services/shareBundleUtils";
+import { truncateCenter } from "@app/utils/textUtils";
+import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
+import styles from "@app/components/shared/FileSelectorPicker.module.css";
+import "@app/components/shared/FileSidebarFileItem.css";
+
+const LS_TAB = "filePicker.tab";
+const LS_SORT = "filePicker.sort";
+const LS_SORT_DIR = "filePicker.sortDir";
+
+function lsGet<const T extends readonly string[]>(
+ key: string,
+ fallback: T[number],
+ valid: T,
+): T[number] {
+ try {
+ const v = localStorage.getItem(key);
+ const allowed = valid as readonly string[];
+ if (v && allowed.includes(v)) return v as T[number];
+ } catch {
+ /* ignore */
+ }
+ return fallback;
+}
+
+function lsSet(key: string, value: string) {
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ /* ignore */
+ }
+}
+
+function formatBytes(bytes: number): string {
+ if (!bytes) return "";
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+function formatDate(ms: number | undefined): string {
+ if (!ms) return "";
+ return new Date(ms).toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ });
+}
+
+function buildMeta(stub: StirlingFileStub): string {
+ const parts: string[] = [];
+ const pages = stub.processedFile?.totalPages;
+ if (pages) parts.push(`${pages} ${pages === 1 ? "page" : "pages"}`);
+ const size = formatBytes(stub.size ?? 0);
+ if (size) parts.push(size);
+ const date = formatDate(stub.lastModified || stub.createdAt);
+ if (date) parts.push(date);
+ return parts.join(" · ");
+}
+
+export interface FileSelectorResult {
+ stub: StirlingFileStub;
+ stirlingFile: StirlingFile;
+}
+
+export interface FileSelectorPickerProps {
+ placeholder?: string;
+ /** FileIds to hide from both lists (e.g. the other slot's current selection) */
+ excludeIds?: string[];
+ disabled?: boolean;
+ /** Optional data-testid applied to the trigger box */
+ testId?: string;
+ /**
+ * Called with the stub (for display) and the ready-to-use StirlingFile (for processing).
+ * Files are NOT added to the workbench — data is loaded inline.
+ */
+ onSelect: (result: FileSelectorResult) => void;
+}
+
+export function FileSelectorPicker({
+ placeholder,
+ excludeIds = [],
+ disabled = false,
+ testId,
+ onSelect,
+}: FileSelectorPickerProps) {
+ const { t } = useTranslation();
+ const [isOpen, setIsOpen] = useState(false);
+ const [activeTab, setActiveTab] = useState<"workbench" | "saved">(() =>
+ lsGet(LS_TAB, "saved", ["workbench", "saved"]),
+ );
+ const [sortBy, setSortBy] = useState<"date" | "name">(() =>
+ lsGet(LS_SORT, "date", ["date", "name"]),
+ );
+ const [sortDir, setSortDir] = useState<"asc" | "desc">(() =>
+ lsGet(LS_SORT_DIR, "desc", ["asc", "desc"]),
+ );
+ const [savedStubs, setSavedStubs] = useState<StirlingFileStub[]>([]);
+ const [savedLoading, setSavedLoading] = useState(false);
+ const [loadingId, setLoadingId] = useState<string | null>(null);
+ const [uploadBusy, setUploadBusy] = useState(false);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [hoveredStub, setHoveredStub] = useState<{
+ rect: DOMRect;
+ stub: StirlingFileStub;
+ } | null>(null);
+ const [hoveredThumbnail, setHoveredThumbnail] = useState<string | null>(null);
+ const thumbCancelRef = useRef<boolean>(false);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const { fileStubs: workbenchStubs } = useAllFiles();
+ const indexedDB = useIndexedDB();
+ const { selectors } = useFileContext();
+ const { loadRecentFiles } = useFileManager();
+
+ // Load thumbnail lazily when hovering over a file row
+ useEffect(() => {
+ if (!hoveredStub) {
+ setHoveredThumbnail(null);
+ return;
+ }
+ if (hoveredStub.stub.thumbnailUrl) {
+ setHoveredThumbnail(hoveredStub.stub.thumbnailUrl);
+ return;
+ }
+ thumbCancelRef.current = false;
+ setHoveredThumbnail(null);
+ (async () => {
+ try {
+ const file = await indexedDB.loadFile(hoveredStub.stub.id as FileId);
+ if (!file || thumbCancelRef.current) return;
+ const thumbnail = await generateThumbnailForFile(file);
+ if (thumbCancelRef.current || !thumbnail) return;
+ setHoveredThumbnail(thumbnail);
+ void indexedDB.updateThumbnail(
+ hoveredStub.stub.id as FileId,
+ thumbnail,
+ );
+ } catch {
+ // non-critical
+ }
+ })();
+ return () => {
+ thumbCancelRef.current = true;
+ };
+ }, [hoveredStub, indexedDB]);
+
+ const handleTabChange = useCallback((tab: "workbench" | "saved") => {
+ lsSet(LS_TAB, tab);
+ setActiveTab(tab);
+ }, []);
+
+ const handleSortChange = useCallback(
+ (sort: "date" | "name") => {
+ if (sort === sortBy) {
+ const newDir = sortDir === "asc" ? "desc" : "asc";
+ lsSet(LS_SORT_DIR, newDir);
+ setSortDir(newDir);
+ } else {
+ const defaultDir: "asc" | "desc" = sort === "name" ? "asc" : "desc";
+ lsSet(LS_SORT, sort);
+ lsSet(LS_SORT_DIR, defaultDir);
+ setSortBy(sort);
+ setSortDir(defaultDir);
+ }
+ },
+ [sortBy, sortDir],
+ );
+
+ // Sync tab/sort from localStorage whenever this picker opens.
+ // Both slot pickers mount simultaneously so their useState initialisers run at
+ // the same time — a tab change in one picker writes to localStorage but the
+ // other picker's React state is stale. Re-reading on open fixes that.
+ useEffect(() => {
+ if (!isOpen) return;
+ setActiveTab(lsGet(LS_TAB, "saved", ["workbench", "saved"]));
+ setSortBy(lsGet(LS_SORT, "date", ["date", "name"]));
+ setSortDir(lsGet(LS_SORT_DIR, "desc", ["asc", "desc"]));
+ }, [isOpen]);
+
+ // Load saved files when the saved tab is active and the picker is open
+ useEffect(() => {
+ if (activeTab !== "saved" || !isOpen) return;
+ setSavedLoading(true);
+ loadRecentFiles()
+ .then(setSavedStubs)
+ .finally(() => setSavedLoading(false));
+ }, [activeTab, isOpen, loadRecentFiles]);
+
+ const workbenchIdSet = useMemo(
+ () => new Set(workbenchStubs.map((s) => s.id)),
+ [workbenchStubs],
+ );
+
+ const displayStubs = useMemo(() => {
+ const base = activeTab === "workbench" ? workbenchStubs : savedStubs;
+ const q = searchQuery.trim().toLowerCase();
+ const filtered = base.filter(
+ (s) =>
+ !excludeIds.includes(s.id) && (!q || s.name.toLowerCase().includes(q)),
+ );
+ const dir = sortDir === "asc" ? 1 : -1;
+ return [...filtered].sort((a, b) =>
+ sortBy === "name"
+ ? dir * a.name.localeCompare(b.name)
+ : dir *
+ ((a.lastModified || a.createdAt || 0) -
+ (b.lastModified || b.createdAt || 0)),
+ );
+ }, [
+ activeTab,
+ workbenchStubs,
+ savedStubs,
+ excludeIds,
+ sortBy,
+ sortDir,
+ searchQuery,
+ ]);
+
+ const loadAndSelect = useCallback(
+ async (stub: StirlingFileStub) => {
+ if (loadingId) return;
+
+ // Workbench file — get StirlingFile directly from FileContext (no loading needed)
+ if (workbenchIdSet.has(stub.id)) {
+ const sf = selectors.getFile(stub.id as FileId);
+ if (sf) {
+ // Prefer the workbench stub (has thumbnail) over the saved stub (may not)
+ const workbenchStub =
+ selectors.getStirlingFileStub(stub.id as FileId) ?? stub;
+ onSelect({ stub: workbenchStub, stirlingFile: sf });
+ setIsOpen(false);
+ }
+ return;
+ }
+
+ // Saved file — load bytes without touching the workbench
+ setLoadingId(stub.id);
+ try {
+ let stirlingFile: StirlingFile | null = null;
+
+ if (stub.remoteShareToken) {
+ const res = await apiClient.get(
+ `/api/v1/storage/share-links/${stub.remoteShareToken}`,
+ {
+ responseType: "blob",
+ suppressErrorToast: true,
+ skipAuthRedirect: true,
+ } as any,
+ );
+ const ct =
+ res.headers?.["content-type"] ||
+ res.headers?.["Content-Type"] ||
+ "";
+ const disp =
+ res.headers?.["content-disposition"] ||
+ res.headers?.["Content-Disposition"] ||
+ "";
+ const files = await extractLatestFilesFromBundle(
+ res.data as Blob,
+ parseContentDispositionFilename(disp) || "shared-file",
+ ct,
+ );
+ if (files[0])
+ stirlingFile = createStirlingFile(files[0], createFileId());
+ } else if (stub.remoteStorageId) {
+ const res = await apiClient.get(
+ `/api/v1/storage/files/${stub.remoteStorageId}/download`,
+ {
+ responseType: "blob",
+ suppressErrorToast: true,
+ skipAuthRedirect: true,
+ } as any,
+ );
+ const ct =
+ res.headers?.["content-type"] ||
+ res.headers?.["Content-Type"] ||
+ "";
+ const disp =
+ res.headers?.["content-disposition"] ||
+ res.headers?.["Content-Disposition"] ||
+ "";
+ const files = await extractLatestFilesFromBundle(
+ res.data as Blob,
+ parseContentDispositionFilename(disp) || stub.name,
+ ct,
+ );
+ if (files[0])
+ stirlingFile = createStirlingFile(files[0], stub.id as FileId);
+ } else {
+ // Local IndexedDB file
+ const localFile = await fileStorage.getStirlingFile(stub.id);
+ if (localFile) stirlingFile = localFile;
+ }
+
+ if (stirlingFile) {
+ // Generate thumbnail on-the-fly if the stub doesn't already have one
+ let resolvedStub = stub;
+ if (!resolvedStub.thumbnailUrl) {
+ try {
+ const thumbnail = await generateThumbnailForFile(stirlingFile);
+ if (thumbnail) {
+ resolvedStub = { ...stub, thumbnailUrl: thumbnail };
+ // Persist so subsequent opens don't regenerate
+ void fileStorage.updateThumbnail(
+ stirlingFile.fileId as FileId,
+ thumbnail,
+ );
+ }
+ } catch {
+ // Non-fatal — thumbnail simply won't show
+ }
+ }
+ onSelect({ stub: resolvedStub, stirlingFile });
+ setIsOpen(false);
+ }
+ } catch (err) {
+ console.error("FileSelectorPicker: failed to load file", err);
+ } finally {
+ setLoadingId(null);
+ }
+ },
+ [loadingId, workbenchIdSet, selectors, onSelect],
+ );
+
+ const handleUpload = useCallback(
+ async (file: File | null) => {
+ if (!file || uploadBusy || disabled) return;
+ setUploadBusy(true);
+ try {
+ const id = createFileId();
+ let stub = createNewStirlingFileStub(file, id);
+ const stirlingFile = createStirlingFile(file, id);
+ // Generate a first-page thumbnail for the uploaded file
+ try {
+ const thumbnail = await generateThumbnailForFile(file);
+ if (thumbnail) stub = { ...stub, thumbnailUrl: thumbnail };
+ } catch {
+ // Non-fatal — thumbnail simply won't show
+ }
+ await fileStorage.storeStirlingFile(stirlingFile, stub);
+ lsSet(LS_TAB, "saved");
+ setActiveTab("saved");
+ const refreshed = await loadRecentFiles();
+ setSavedStubs(refreshed);
+ onSelect({ stub, stirlingFile });
+ setIsOpen(false);
+ } catch (err) {
+ console.error("FileSelectorPicker: upload failed", err);
+ } finally {
+ setUploadBusy(false);
+ }
+ },
+ [disabled, loadRecentFiles, onSelect, uploadBusy],
+ );
+
+ const triggerClass = [
+ styles.trigger,
+ disabled ? styles.triggerDisabled : "",
+ isOpen ? styles.triggerOpen : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ return (
+ <>
+ <Popover
+ opened={isOpen}
+ onChange={setIsOpen}
+ onClose={() => {
+ setIsOpen(false);
+ setSearchQuery("");
+ }}
+ position="bottom-start"
+ withinPortal
+ shadow="md"
+ closeOnClickOutside
+ clickOutsideEvents={["mousedown", "touchstart"]}
+ >
+ <Popover.Target>
+ <Box
+ className={triggerClass}
+ style={{ width: "100%" }}
+ data-testid={testId}
+ onClick={() => {
+ if (!disabled) setIsOpen((o) => !o);
+ }}
+ role="button"
+ tabIndex={disabled ? -1 : 0}
+ onKeyDown={(e) => {
+ if (!disabled && (e.key === "Enter" || e.key === " "))
+ setIsOpen((o) => !o);
+ }}
+ aria-expanded={isOpen}
+ aria-haspopup="listbox"
+ >
+ <Text
+ size="sm"
+ c="dimmed"
+ style={{
+ flex: 1,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {placeholder ||
+ t("fileSelectorPicker.placeholder", "Select file")}
+ </Text>
+ <AddIcon
+ style={{
+ fontSize: 18,
+ color: "var(--mantine-color-dimmed)",
+ flexShrink: 0,
+ }}
+ />
+ </Box>
+ </Popover.Target>
+
+ <Popover.Dropdown className={styles.dropdown}>
+ <div className={styles.header}>
+ <div className={styles.tabGroup}>
+ <div
+ className={styles.slimTabBar}
+ role="group"
+ aria-label={t(
+ "fileSelectorPicker.tabListLabel",
+ "Saved files, workbench, upload",
+ )}
+ >
+ <button
+ type="button"
+ aria-pressed={activeTab === "saved"}
+ className={
+ activeTab === "saved"
+ ? styles.slimTabActive
+ : styles.slimTab
+ }
+ onClick={() => handleTabChange("saved")}
+ >
+ {t("fileSelectorPicker.tabs.saved", "Saved files")}
+ </button>
+ <button
+ type="button"
+ aria-pressed={activeTab === "workbench"}
+ className={
+ activeTab === "workbench"
+ ? styles.slimTabActive
+ : styles.slimTab
+ }
+ onClick={() => handleTabChange("workbench")}
+ >
+ {t("fileSelectorPicker.tabs.workbench", "Workbench")}
+ </button>
+ <button
+ type="button"
+ data-testid="file-selector-upload-btn"
+ className={styles.slimTabUpload}
+ aria-label={t(
+ "fileSelectorPicker.upload",
+ "Upload from computer",
+ )}
+ title={t("fileSelectorPicker.upload", "Upload from computer")}
+ disabled={disabled || uploadBusy}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ {uploadBusy ? (
+ <Loader size={11} />
+ ) : (
+ t("fileSelectorPicker.tabs.upload", "Upload")
+ )}
+ </button>
+ </div>
+ </div>
+
+ <div className={styles.sortGroup}>
+ <button
+ type="button"
+ className={[
+ styles.sortBtn,
+ sortBy === "date" ? styles.sortBtnActive : "",
+ ].join(" ")}
+ onClick={() => handleSortChange("date")}
+ title={
+ sortDir === "desc"
+ ? t("fileSelectorPicker.sort.dateDesc", "Newest first")
+ : t("fileSelectorPicker.sort.dateAsc", "Oldest first")
+ }
+ >
+ {t("fileSelectorPicker.sort.dateLabel", "Latest")}
+ {sortBy === "date" && (
+ <span className={styles.sortArrow}>
+ {sortDir === "desc" ? " ↓" : " ↑"}
+ </span>
+ )}
+ </button>
+ <button
+ type="button"
+ className={[
+ styles.sortBtn,
+ sortBy === "name" ? styles.sortBtnActive : "",
+ ].join(" ")}
+ onClick={() => handleSortChange("name")}
+ title={
+ sortDir === "asc"
+ ? t("fileSelectorPicker.sort.nameAsc", "A to Z")
+ : t("fileSelectorPicker.sort.nameDesc", "Z to A")
+ }
+ >
+ {t("fileSelectorPicker.sort.nameLabel", "A–Z")}
+ {sortBy === "name" && (
+ <span className={styles.sortArrow}>
+ {sortDir === "asc" ? " ↑" : " ↓"}
+ </span>
+ )}
+ </button>
+ </div>
+ </div>
+
+ <div className={styles.searchRow}>
+ <input
+ className={styles.searchInput}
+ type="search"
+ placeholder={t("fileSelectorPicker.search", "Filter files…")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ autoComplete="off"
+ spellCheck={false}
+ />
+ </div>
+
+ <ScrollArea h={260} className={styles.list}>
+ {savedLoading ? (
+ <div className={styles.emptyState}>
+ <Loader size="sm" />
+ </div>
+ ) : displayStubs.length === 0 ? (
+ <div className={styles.emptyState}>
+ <Text size="sm">
+ {t("fileSelectorPicker.empty", "No files available")}
+ </Text>
+ </div>
+ ) : (
+ displayStubs.map((stub) => {
+ const meta = buildMeta(stub);
+ const isItemLoading = loadingId === stub.id;
+ return (
+ <button
+ key={stub.id}
+ type="button"
+ className={styles.fileItem}
+ onClick={() => void loadAndSelect(stub)}
+ disabled={!!loadingId}
+ onMouseEnter={(e) =>
+ setHoveredStub({
+ rect: e.currentTarget.getBoundingClientRect(),
+ stub,
+ })
+ }
+ onMouseLeave={() => setHoveredStub(null)}
+ >
+ <div className={styles.fileItemContent}>
+ <span className={styles.fileName} title={stub.name}>
+ {truncateCenter(stub.name, 48)}
+ </span>
+ {meta && <span className={styles.fileMeta}>{meta}</span>}
+ </div>
+ {isItemLoading && <Loader size="xs" />}
+ </button>
+ );
+ })
+ )}
+ </ScrollArea>
+
+ {hoveredStub &&
+ hoveredThumbnail &&
+ createPortal(
+ <div
+ className="file-sidebar-thumb-tooltip"
+ style={{
+ top: hoveredStub.rect.top + hoveredStub.rect.height / 2,
+ left: hoveredStub.rect.left - 170,
+ }}
+ >
+ <img
+ src={hoveredThumbnail}
+ alt=""
+ className="file-sidebar-thumb-img"
+ />
+ </div>,
+ document.body,
+ )}
+ </Popover.Dropdown>
+ </Popover>
+ {/* Hidden file input lives outside the Popover so it is always in the DOM.
+ Tests can target it directly with setInputFiles without opening the popover. */}
+ <input
+ ref={fileInputRef}
+ type="file"
+ data-testid={testId ? `${testId}-input` : "file-selector-upload-input"}
+ accept=".pdf,application/pdf"
+ style={{ display: "none" }}
+ onChange={(e) => {
+ const file = e.target.files?.[0] ?? null;
+ void handleUpload(file);
+ e.target.value = "";
+ }}
+ />
+ </>
+ );
+}
diff --git a/frontend/src/core/components/shared/FileSidebar.css b/frontend/src/core/components/shared/FileSidebar.css
new file mode 100644
index 0000000000..76681c6353
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSidebar.css
@@ -0,0 +1,408 @@
+/* ========== FILE SIDEBAR ========== */
+
+.file-sidebar {
+ background-color: var(--bg-toolbar);
+ border-right: 1px solid var(--border-subtle);
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ position: relative;
+ z-index: 10;
+ transition:
+ width 0.22s cubic-bezier(0.4, 0, 0.2, 1),
+ min-width 0.22s cubic-bezier(0.4, 0, 0.2, 1),
+ max-width 0.22s cubic-bezier(0.4, 0, 0.2, 1);
+ flex-shrink: 0;
+}
+
+.file-sidebar-inner {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+}
+
+/* ---- Header ---- */
+.file-sidebar-header {
+ display: flex;
+ align-items: center;
+ height: 48px;
+ padding: 0 14px;
+ gap: 10px;
+ cursor: pointer;
+ border-radius: 4px;
+ margin: 4px 4px 0 4px;
+ flex-shrink: 0;
+ transition: background-color 0.15s ease;
+}
+
+/* Icons stay left-aligned during animation; overflow:hidden on inner clips text naturally */
+
+.file-sidebar-header:hover {
+ background-color: var(--bg-hover);
+}
+
+.file-sidebar-menu-icon {
+ color: var(--text-muted) !important;
+ font-size: 18px !important;
+ flex-shrink: 0;
+}
+
+.file-sidebar-brand-text {
+ height: 22px;
+ width: auto;
+ flex-shrink: 0;
+}
+
+/* ---- Search row ---- */
+.file-sidebar-search-row {
+ display: flex;
+ align-items: center;
+ min-height: 32px;
+ padding: 0 14px;
+ gap: 0;
+ cursor: pointer;
+ border-radius: 4px;
+ margin: 0 4px;
+ flex-shrink: 0;
+ transition: background-color 0.15s ease;
+}
+
+.file-sidebar-search-row:not(.active):hover {
+ background-color: var(--bg-hover);
+}
+
+.file-sidebar-search-icon {
+ color: var(--text-muted) !important;
+ font-size: 18px !important;
+ flex-shrink: 0;
+}
+
+.file-sidebar-search-close {
+ cursor: pointer;
+}
+
+.file-sidebar-search-input {
+ flex: 1;
+ background: transparent;
+ border: none;
+ outline: none;
+ font-size: 14px;
+ color: var(--text-primary);
+ margin-left: 12px;
+ min-width: 0;
+}
+
+.file-sidebar-search-input::placeholder {
+ color: var(--text-muted);
+}
+
+.file-sidebar-search-label {
+ margin-left: 12px;
+ font-size: 14px;
+ color: var(--text-secondary);
+}
+
+/* ---- Scrollable content ---- */
+/* This is a flex column — action rows are fixed, only the file list scrolls */
+.file-sidebar-scroll {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.file-sidebar-scroll::-webkit-scrollbar {
+ width: 4px;
+}
+.file-sidebar-scroll::-webkit-scrollbar-track {
+ background: transparent;
+}
+.file-sidebar-scroll::-webkit-scrollbar-thumb {
+ background: rgb(var(--border));
+ border-radius: 2px;
+}
+
+/* ---- Action rows (Open from Computer, etc.) ---- */
+.file-sidebar-action-row {
+ display: flex;
+ align-items: center;
+ height: 32px;
+ padding: 0 14px;
+ cursor: pointer;
+ border-radius: 4px;
+ margin: 0 4px;
+ gap: 0;
+ transition: background-color 0.15s ease;
+ flex-shrink: 0;
+}
+
+.file-sidebar-action-row:hover {
+ background-color: var(--bg-hover);
+}
+
+.file-sidebar-action-icon {
+ color: var(--text-muted) !important;
+ font-size: 18px !important;
+ flex-shrink: 0;
+}
+
+.file-sidebar-action-label {
+ margin-left: 12px;
+ font-size: 14px;
+ color: var(--text-secondary);
+ white-space: nowrap;
+}
+
+/* ---- Cloud storage rows ---- */
+.file-sidebar-cloud-row {
+ display: flex;
+ align-items: center;
+ height: 32px;
+ padding: 0 14px;
+ cursor: pointer;
+ border-radius: 4px;
+ margin: 0 4px;
+ gap: 0;
+ transition: background-color 0.15s ease;
+ flex-shrink: 0;
+}
+
+.file-sidebar-cloud-row:not(.disabled):hover {
+ background-color: var(--bg-hover);
+}
+
+.file-sidebar-cloud-row.disabled {
+ cursor: default;
+ opacity: 0.5;
+}
+
+.file-sidebar-cloud-icon-wrapper {
+ position: relative;
+ width: 18px;
+ height: 18px;
+ flex-shrink: 0;
+}
+
+.file-sidebar-cloud-icon-gray {
+ position: absolute;
+ inset: 0;
+ transition: opacity 0.2s ease;
+ opacity: 1;
+}
+
+.file-sidebar-cloud-icon-color {
+ position: absolute;
+ inset: 0;
+ transition: opacity 0.2s ease;
+ opacity: 0;
+}
+
+.file-sidebar-cloud-row:not(.disabled):hover .file-sidebar-cloud-icon-gray {
+ opacity: 0;
+}
+
+.file-sidebar-cloud-row:not(.disabled):hover .file-sidebar-cloud-icon-color {
+ opacity: 1;
+}
+
+/* ---- Files section ---- */
+.file-sidebar-files-section {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ margin-top: 4px;
+}
+
+.file-sidebar-file-list {
+ flex: 1;
+ min-height: 0;
+ overflow-y: scroll;
+}
+
+.file-sidebar-file-list::-webkit-scrollbar {
+ width: 4px;
+}
+.file-sidebar-file-list::-webkit-scrollbar-track {
+ background: transparent;
+}
+.file-sidebar-file-list::-webkit-scrollbar-thumb {
+ background: rgb(var(--border));
+ border-radius: 2px;
+}
+.file-sidebar-file-list::-webkit-scrollbar-thumb:hover {
+ background: var(--text-muted);
+}
+
+.file-sidebar-section-divider {
+ border-top: 1px solid var(--border-subtle);
+ margin: 10px 14px 6px 14px;
+}
+
+.file-sidebar-section-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 14px 6px 14px;
+ margin: 4px 0 0 0;
+}
+
+.file-sidebar-section-header {
+ position: relative;
+ border-top: 1px solid var(--border-subtle);
+ padding-top: 10px;
+ margin-top: 4px;
+ flex-shrink: 0;
+}
+
+.file-sidebar-section-label {
+ font-size: 13px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ color: var(--text-muted);
+ text-transform: uppercase;
+}
+
+.file-sidebar-section-count {
+ font-size: 11px;
+ color: var(--text-muted);
+}
+
+.file-sidebar-section-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ border: none;
+ background: transparent;
+ border-radius: 4px;
+ cursor: pointer;
+ color: var(--text-muted);
+ padding: 0;
+ outline: none;
+ transition:
+ background-color 0.12s ease,
+ color 0.12s ease,
+ opacity 0.12s ease;
+}
+
+.file-sidebar-section-btn:focus-visible {
+ outline: 2px solid #3b82f6;
+ outline-offset: 1px;
+}
+
+.file-sidebar-section-btn:hover {
+ background-color: var(--bg-hover);
+ color: var(--text-primary);
+}
+
+.file-sidebar-section-btn-external {
+ opacity: 0;
+ pointer-events: none;
+}
+
+.file-sidebar-section-header:hover .file-sidebar-section-btn-external {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+.file-sidebar-section-btn-add {
+ margin-left: auto;
+}
+
+/* ---- Sidebar content fade (for collapsed state) ---- */
+/* Elements are conditionally rendered so use animation (not transition) to fade in from 0.
+ Delay until the width animation is nearly done (0.18s of 0.22s) to avoid squashed-text effect. */
+@keyframes sidebar-content-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+.sidebar-content-fade {
+ animation: sidebar-content-in 0.12s ease 0.18s both;
+}
+
+.file-sidebar[data-collapsed="true"] .sidebar-content-fade {
+ opacity: 0;
+ pointer-events: none;
+ animation: none;
+}
+
+/* ---- Bottom bar (user + settings) ---- */
+.file-sidebar-bottom-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ border-top: 1px solid var(--border-subtle);
+ flex-shrink: 0;
+ min-height: 48px;
+}
+
+/* Bottom bar settings icon tracks the right edge during collapse animation */
+
+.file-sidebar-bottom-avatar {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ background-color: var(--mantine-color-blue-6, #3b82f6);
+ color: #fff;
+ font-size: 12px;
+ font-weight: 600;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ user-select: none;
+}
+
+.file-sidebar-bottom-name {
+ flex: 1;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-primary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+}
+
+.file-sidebar-bottom-bar[role="button"]:hover {
+ background-color: var(--bg-hover);
+}
+
+.file-sidebar-bottom-bar[role="button"]:focus-visible {
+ outline: 2px solid #3b82f6;
+ outline-offset: -2px;
+}
+
+.file-sidebar-bottom-settings {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 6px;
+ color: var(--text-muted);
+ padding: 0;
+ flex-shrink: 0;
+ margin-left: auto;
+}
+
+.file-sidebar[data-collapsed="true"] .file-sidebar-bottom-settings {
+ width: 32px;
+ height: 32px;
+}
+
+.file-sidebar[data-collapsed="true"] .file-sidebar-bottom-bar {
+ justify-content: center;
+ padding: 8px 0;
+}
diff --git a/frontend/src/core/components/shared/FileSidebar.tsx b/frontend/src/core/components/shared/FileSidebar.tsx
new file mode 100644
index 0000000000..6ddf6f49de
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSidebar.tsx
@@ -0,0 +1,594 @@
+import React, {
+ useState,
+ useCallback,
+ useRef,
+ useEffect,
+ forwardRef,
+} from "react";
+import { Loader } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { useFileState, useFileActions } from "@app/contexts/file/fileHooks";
+import { useFilesModalContext } from "@app/contexts/FilesModalContext";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { useGoogleDrivePicker } from "@app/hooks/useGoogleDrivePicker";
+import {
+ useNavigationState,
+ useNavigationActions,
+ useNavigationGuard,
+} from "@app/contexts/NavigationContext";
+import { useViewer } from "@app/contexts/ViewerContext";
+import { useFileHandler } from "@app/hooks/useFileHandler";
+import { useIndexedDB } from "@app/contexts/IndexedDBContext";
+import { accountService } from "@app/services/accountService";
+import { GoogleDriveIcon } from "@app/components/shared/CloudStorageIcons";
+import { Wordmark } from "@app/components/shared/Wordmark";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import MenuIcon from "@mui/icons-material/Menu";
+import SearchIcon from "@mui/icons-material/Search";
+import FolderOpenIcon from "@mui/icons-material/FolderOpen";
+import CloseIcon from "@mui/icons-material/Close";
+import AddIcon from "@mui/icons-material/Add";
+import OpenInNewIcon from "@mui/icons-material/OpenInNew";
+import SettingsIcon from "@mui/icons-material/Settings";
+import type { FileId } from "@app/types/file";
+import { FileItem } from "@app/components/shared/FileSidebarFileItem";
+import "@app/components/shared/FileSidebar.css";
+
+const COLLAPSED_WIDTH = "3.5rem";
+const EXPANDED_WIDTH = "16.25rem"; // ~260px
+
+export interface FileSidebarProps {
+ collapsed?: boolean;
+ onToggleCollapse?: () => void;
+ onOpenSettings?: () => void;
+}
+
+const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
+ function FileSidebar(
+ { collapsed = false, onToggleCollapse, onOpenSettings },
+ ref,
+ ) {
+ const { t } = useTranslation();
+ const [searchActive, setSearchActive] = useState(false);
+ const [searchQuery, setSearchQuery] = useState("");
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const nativeFileInputRef = useRef<HTMLInputElement>(null);
+ // State (not ref) so setting it triggers a re-render — avoids racing addFiles state updates.
+ const [pendingViewFileId, setPendingViewFileId] = useState<string | null>(
+ null,
+ );
+
+ const { openFilesModal } = useFilesModalContext();
+ const { config } = useAppConfig();
+ const {
+ isEnabled: isGoogleDriveEnabled,
+ openPicker: openGoogleDrivePicker,
+ } = useGoogleDrivePicker();
+ const { state } = useFileState();
+ const { actions: fileActions } = useFileActions();
+ const { actions: navActions } = useNavigationActions();
+ const { workbench: currentWorkbench, selectedTool } = useNavigationState();
+ const isMultiTool =
+ currentWorkbench === "pageEditor" && selectedTool === "multiTool";
+ const { requestNavigation } = useNavigationGuard();
+ const { activeFileId, setActiveFileId } = useViewer();
+ const { addFiles } = useFileHandler();
+ const indexedDB = useIndexedDB();
+ const [displayName, setDisplayName] = useState<string>("Guest");
+
+ useEffect(() => {
+ if (!config?.enableLogin) return;
+ accountService
+ .getAccountData()
+ .then((data) => {
+ if (data?.username) setDisplayName(data.username);
+ })
+ .catch(() => {
+ /* not logged in or security disabled */
+ });
+ }, [config?.enableLogin]);
+
+ // Leaf files = user-visible files (excludes intermediate tool outputs)
+ const [allFileStubs, setAllFileStubs] = useState<StirlingFileStub[]>([]);
+ const [stubsLoaded, setStubsLoaded] = useState(false);
+
+ const refreshStubs = useCallback(async () => {
+ // Leaf files from IDB — same source as the file selection modal.
+ const stubs = await indexedDB.loadLeafMetadata();
+ const idbIds = new Set(stubs.map((s) => s.id as string));
+
+ // Also include workbench files not yet flushed to IDB.
+ const pendingStubs = state.files.ids
+ .map((id) => state.files.byId[id])
+ .filter(
+ (stub): stub is NonNullable<typeof stub> =>
+ !!stub && stub.isLeaf !== false && !idbIds.has(stub.id as string),
+ );
+
+ const allStubs = [...stubs, ...pendingStubs];
+ setAllFileStubs(
+ allStubs.sort((a, b) => (b.lastModified ?? 0) - (a.lastModified ?? 0)),
+ );
+ setStubsLoaded(true);
+ }, [indexedDB, state.files.ids, state.files.byId]);
+
+ // Refresh on mount, workbench changes, or external IndexedDB writes
+ useEffect(() => {
+ refreshStubs();
+ }, [refreshStubs, indexedDB.revision]);
+
+ // Once a pending file lands in state, open it in the viewer.
+ useEffect(() => {
+ if (!pendingViewFileId) return;
+ const isInWorkbench = state.files.ids.some(
+ (id) => (id as string) === pendingViewFileId,
+ );
+ if (isInWorkbench) {
+ setPendingViewFileId(null);
+ setActiveFileId(pendingViewFileId);
+ navActions.setWorkbench("viewer");
+ }
+ }, [pendingViewFileId, state.files.ids, setActiveFileId, navActions]);
+
+ const filteredFileStubs = searchQuery.trim()
+ ? allFileStubs.filter((stub) =>
+ stub.name.toLowerCase().includes(searchQuery.toLowerCase()),
+ )
+ : allFileStubs;
+
+ // Handle search activation
+ const handleSearchClick = useCallback(() => {
+ if (collapsed && onToggleCollapse) {
+ onToggleCollapse();
+ }
+ setSearchActive(true);
+ }, [collapsed, onToggleCollapse]);
+
+ const handleSearchClose = useCallback(() => {
+ setSearchActive(false);
+ setSearchQuery("");
+ }, []);
+
+ useEffect(() => {
+ if (searchActive && searchInputRef.current) {
+ searchInputRef.current.focus();
+ }
+ }, [searchActive]);
+
+ // Handle Google Drive
+ const handleGoogleDriveClick = useCallback(async () => {
+ if (!isGoogleDriveEnabled) return;
+ const files = await openGoogleDrivePicker({ multiple: true });
+ if (files.length > 0) {
+ await addFiles(files);
+ if (!isMultiTool) {
+ navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");
+ }
+ }
+ }, [
+ isGoogleDriveEnabled,
+ openGoogleDrivePicker,
+ addFiles,
+ navActions,
+ isMultiTool,
+ ]);
+
+ // Toggle file in/out of workbench
+ const handleFileClick = useCallback(
+ async (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (!stub) return;
+
+ const workbenchFileId = state.files.ids.find(
+ (id) => (id as string) === (stub.id as string),
+ );
+
+ if (workbenchFileId) {
+ // If this is the file currently open in the viewer, route through the
+ // navigation guard so the save modal fires when there are unsaved changes.
+ const isCurrentlyViewed = workbenchFileId === viewedWorkbenchId;
+ if (isCurrentlyViewed) {
+ requestNavigation(() => {
+ void fileActions.removeFiles([workbenchFileId], false);
+ });
+ return;
+ }
+ await fileActions.removeFiles([workbenchFileId], false);
+ } else {
+ // Re-add by stub to preserve its ID — addFiles() would create a new UUID + IDB entry.
+ const workbenchCount = state.files.ids.length;
+
+ if (workbenchCount > 0 && currentWorkbench === "viewer") {
+ navActions.setWorkbench("fileEditor");
+ }
+
+ await fileActions.addStirlingFileStubs([stub]);
+
+ if (isMultiTool) {
+ fileActions.setSelectedFiles([
+ ...state.ui.selectedFileIds,
+ stub.id,
+ ]);
+ } else {
+ if (workbenchCount === 0) {
+ navActions.setWorkbench("viewer");
+ } else {
+ navActions.setWorkbench("fileEditor");
+ }
+ }
+ }
+ },
+ [
+ allFileStubs,
+ state.files.ids,
+ state.ui.selectedFileIds,
+ fileActions,
+ navActions,
+ currentWorkbench,
+ activeFileId,
+ requestNavigation,
+ isMultiTool,
+ ],
+ );
+
+ // Which file is currently open in the viewer — stable ID, never index-derived.
+ const viewedWorkbenchId =
+ currentWorkbench === "viewer" ? activeFileId : null;
+
+ const handleEyeClick = useCallback(
+ async (fileId: FileId, _e: React.MouseEvent) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (!stub) return;
+
+ const isCurrentlyViewed = !!(
+ viewedWorkbenchId &&
+ (viewedWorkbenchId as string) === (stub.id as string)
+ );
+
+ if (isCurrentlyViewed) {
+ // Closing the currently-viewed file — guard against unsaved changes.
+ navActions.setWorkbench("fileEditor");
+ return;
+ }
+
+ // Switching to a different file while viewer is open — guard against unsaved changes.
+ const performSwitch = async () => {
+ const alreadyInWorkbench = state.files.ids.some(
+ (id) => (id as string) === (stub.id as string),
+ );
+
+ if (!alreadyInWorkbench) {
+ // Leave viewer before mutating workbench (prevents PSPDFKit crash).
+ if (state.files.ids.length > 0 && currentWorkbench === "viewer") {
+ navActions.setWorkbench("fileEditor");
+ }
+ await fileActions.addStirlingFileStubs([stub]);
+ }
+
+ // Route through pendingViewFileId so both setActiveFileIndex + setWorkbench fire together.
+ setPendingViewFileId(stub.id as string);
+ };
+
+ if (currentWorkbench === "viewer" && viewedWorkbenchId) {
+ requestNavigation(() => {
+ void performSwitch();
+ });
+ } else {
+ await performSwitch();
+ }
+ },
+ [
+ allFileStubs,
+ viewedWorkbenchId,
+ state.files.ids,
+ fileActions,
+ navActions,
+ currentWorkbench,
+ setPendingViewFileId,
+ requestNavigation,
+ ],
+ );
+
+ const handleNativeFilePick = useCallback(
+ async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files ?? []);
+ if (files.length > 0) {
+ await addFiles(files);
+ if (!isMultiTool) {
+ navActions.setWorkbench(
+ files.length === 1 ? "viewer" : "fileEditor",
+ );
+ }
+ }
+ e.target.value = "";
+ },
+ [addFiles, navActions, isMultiTool],
+ );
+
+ const shouldHideGoogleDrive =
+ !isGoogleDriveEnabled && config?.hideDisabledToolsGoogleDrive;
+
+ const width = collapsed ? COLLAPSED_WIDTH : EXPANDED_WIDTH;
+
+ return (
+ <div
+ ref={ref}
+ className="file-sidebar"
+ style={{ width, minWidth: width, maxWidth: width }}
+ data-collapsed={collapsed}
+ data-sidebar="file-sidebar"
+ data-tour="quick-access-bar"
+ >
+ <div className="file-sidebar-inner">
+ {/* Header: hamburger + branding */}
+ <div
+ className="file-sidebar-header"
+ onClick={() => onToggleCollapse?.()}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => e.key === "Enter" && onToggleCollapse?.()}
+ aria-label={
+ collapsed
+ ? t("fileSidebar.expand", "Expand sidebar")
+ : t("fileSidebar.collapse", "Collapse sidebar")
+ }
+ >
+ <MenuIcon className="file-sidebar-menu-icon" />
+ {!collapsed && (
+ <Wordmark
+ alt="Stirling PDF"
+ className="file-sidebar-brand-text sidebar-content-fade"
+ />
+ )}
+ </div>
+
+ {/* Search row */}
+ {
+ <div
+ className={`file-sidebar-search-row${searchActive && !collapsed ? " active" : ""}`}
+ onClick={!searchActive ? handleSearchClick : undefined}
+ role={!searchActive ? "button" : undefined}
+ tabIndex={!searchActive ? 0 : undefined}
+ onKeyDown={
+ !searchActive
+ ? (e) => e.key === "Enter" && handleSearchClick()
+ : undefined
+ }
+ >
+ {searchActive && !collapsed ? (
+ <CloseIcon
+ className="file-sidebar-search-icon"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleSearchClose();
+ }}
+ />
+ ) : (
+ <SearchIcon className="file-sidebar-search-icon" />
+ )}
+ {!collapsed &&
+ (searchActive ? (
+ <input
+ ref={searchInputRef}
+ className="file-sidebar-search-input sidebar-content-fade"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder={t(
+ "fileSidebar.searchPlaceholder",
+ "Search files...",
+ )}
+ onClick={(e) => e.stopPropagation()}
+ />
+ ) : (
+ <span className="file-sidebar-search-label sidebar-content-fade">
+ {t("fileSidebar.search", "Search")}
+ </span>
+ ))}
+ </div>
+ }
+
+ {/* Scrollable content */}
+ <div className="file-sidebar-scroll">
+ {/* Open from Computer + Google Drive */}
+ {
+ <>
+ <div
+ className="file-sidebar-action-row"
+ data-testid="files-button"
+ data-tour="files-button"
+ onClick={() => {
+ if (collapsed && onToggleCollapse) onToggleCollapse();
+ openFilesModal();
+ }}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => e.key === "Enter" && openFilesModal()}
+ >
+ <FolderOpenIcon className="file-sidebar-action-icon" />
+ {!collapsed && (
+ <span className="file-sidebar-action-label sidebar-content-fade">
+ {t("fileSidebar.openFromComputer", "Open from computer")}
+ </span>
+ )}
+ </div>
+
+ {!shouldHideGoogleDrive && (
+ <div
+ className={`file-sidebar-cloud-row${!isGoogleDriveEnabled ? " disabled" : ""}`}
+ onClick={handleGoogleDriveClick}
+ role="button"
+ tabIndex={isGoogleDriveEnabled ? 0 : -1}
+ aria-disabled={!isGoogleDriveEnabled}
+ title={
+ !isGoogleDriveEnabled
+ ? t(
+ "fileSidebar.googleDriveDisabled",
+ "Google Drive is not configured",
+ )
+ : t("fileSidebar.googleDrive", "Open from Google Drive")
+ }
+ >
+ <div className="file-sidebar-cloud-icon-wrapper">
+ <GoogleDriveIcon
+ className="file-sidebar-cloud-icon-gray"
+ style={{ color: "var(--text-secondary)" }}
+ />
+ {isGoogleDriveEnabled && (
+ <GoogleDriveIcon
+ colored
+ className="file-sidebar-cloud-icon-color"
+ />
+ )}
+ </div>
+ {!collapsed && (
+ <span className="file-sidebar-action-label sidebar-content-fade">
+ {t("fileSidebar.googleDrive", "Google Drive")}
+ </span>
+ )}
+ </div>
+ )}
+ </>
+ }
+
+ {/* Files section - always visible when expanded */}
+ {!collapsed && (
+ <div className="file-sidebar-files-section sidebar-content-fade">
+ <div className="file-sidebar-section-header">
+ <span className="file-sidebar-section-label">
+ {t("fileSidebar.files", "Files")}
+ </span>
+ <button
+ className="file-sidebar-section-btn file-sidebar-section-btn-external"
+ onClick={() => openFilesModal()}
+ title={t(
+ "fileSidebar.openFileManager",
+ "Open file manager",
+ )}
+ type="button"
+ >
+ <OpenInNewIcon sx={{ fontSize: "1rem" }} />
+ </button>
+ <button
+ className="file-sidebar-section-btn file-sidebar-section-btn-add"
+ onClick={() => nativeFileInputRef.current?.click()}
+ title={t("fileSidebar.addFiles", "Add files")}
+ type="button"
+ >
+ <AddIcon sx={{ fontSize: "1rem" }} />
+ </button>
+ <input
+ ref={nativeFileInputRef}
+ type="file"
+ multiple
+ accept=".pdf"
+ style={{ display: "none" }}
+ onChange={handleNativeFilePick}
+ />
+ </div>
+
+ {!stubsLoaded ? (
+ <div className="file-sidebar-loading">
+ <Loader size="sm" color="var(--text-muted)" />
+ </div>
+ ) : filteredFileStubs.length > 0 ? (
+ <div className="file-sidebar-file-list">
+ {filteredFileStubs.map((stub) => {
+ const workbenchFileId = state.files.ids.find(
+ (id) => (id as string) === (stub.id as string),
+ );
+ const isInWorkbench = !!workbenchFileId;
+ // Both active and viewed-in-viewer are ID-based — never index-based.
+ const isViewedInViewer = !!(
+ viewedWorkbenchId &&
+ viewedWorkbenchId === (stub.id as string)
+ );
+ const isActive = isViewedInViewer;
+ // In-memory thumbnail may be fresher than the IndexedDB stub.
+ // Encrypted files never get a raster thumbnail — use undefined
+ // so the sidebar icon is shown instead of a stale canvas thumbnail.
+ const isEncryptedFile =
+ stub.processedFile?.isEncrypted === true;
+ const thumbnailUrl = isEncryptedFile
+ ? undefined
+ : (workbenchFileId
+ ? state.files.byId[workbenchFileId]?.thumbnailUrl
+ : undefined) || stub.thumbnailUrl;
+ return (
+ <FileItem
+ key={stub.id}
+ fileId={stub.id}
+ name={stub.name}
+ size={stub.size}
+ lastModified={stub.lastModified}
+ isSelected={isInWorkbench}
+ isActive={isActive}
+ isViewedInViewer={isViewedInViewer}
+ thumbnailUrl={thumbnailUrl}
+ onClick={handleFileClick}
+ onEyeClick={handleEyeClick}
+ />
+ );
+ })}
+ </div>
+ ) : (
+ !searchActive && (
+ <div className="file-sidebar-empty">
+ <p className="file-sidebar-empty-text">
+ {t("fileSidebar.noFiles", "No files yet")}
+ </p>
+ <p className="file-sidebar-empty-hint">
+ {t("fileSidebar.dropHint", "Open files to get started")}
+ </p>
+ </div>
+ )
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Bottom bar: user name + settings */}
+ <div
+ className="file-sidebar-bottom-bar"
+ onClick={onOpenSettings}
+ role={onOpenSettings ? "button" : undefined}
+ tabIndex={onOpenSettings ? 0 : undefined}
+ onKeyDown={
+ onOpenSettings
+ ? (e) => e.key === "Enter" && onOpenSettings()
+ : undefined
+ }
+ data-testid={onOpenSettings ? "config-button" : undefined}
+ data-tour={onOpenSettings ? "config-button" : undefined}
+ aria-label={
+ onOpenSettings
+ ? t("fileSidebar.openSettings", "Open settings")
+ : undefined
+ }
+ title={
+ onOpenSettings
+ ? t("fileSidebar.openSettings", "Open settings")
+ : undefined
+ }
+ style={onOpenSettings ? { cursor: "pointer" } : undefined}
+ >
+ <div className="file-sidebar-bottom-avatar" title={displayName}>
+ {displayName.charAt(0).toUpperCase()}
+ </div>
+ {!collapsed && (
+ <span className="file-sidebar-bottom-name sidebar-content-fade">
+ {displayName}
+ </span>
+ )}
+ {onOpenSettings && !collapsed && (
+ <div className="file-sidebar-bottom-settings">
+ <SettingsIcon sx={{ fontSize: "1.1rem" }} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ },
+);
+
+export default FileSidebar;
diff --git a/frontend/src/core/components/shared/FileSidebarFileItem.css b/frontend/src/core/components/shared/FileSidebarFileItem.css
new file mode 100644
index 0000000000..0b64978235
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSidebarFileItem.css
@@ -0,0 +1,283 @@
+/* ---- File list ---- */
+.file-sidebar-file-list {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ padding: 0 8px 0 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+
+.file-sidebar-file-list::-webkit-scrollbar {
+ width: 4px;
+}
+.file-sidebar-file-list::-webkit-scrollbar-track {
+ background: transparent;
+}
+.file-sidebar-file-list::-webkit-scrollbar-thumb {
+ background: rgb(var(--border));
+ border-radius: 2px;
+}
+
+/* ---- File item ---- */
+.file-sidebar-file-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background-color 0.12s ease;
+}
+
+.file-sidebar-file-item:hover:not(.selected) {
+ background-color: rgba(59, 130, 246, 0.06);
+}
+
+.file-sidebar-file-item.selected {
+ background-color: rgba(59, 130, 246, 0.12);
+}
+
+.file-sidebar-file-item.active:not(.selected) {
+ background-color: rgba(59, 130, 246, 0.06);
+}
+
+/* Icon wrapper */
+.file-sidebar-file-icon-wrapper {
+ position: relative;
+ width: 20px;
+ height: 20px;
+ flex-shrink: 0;
+}
+
+.file-sidebar-file-icon-hover-hide {
+ display: block;
+}
+
+.file-sidebar-file-item:hover .file-sidebar-file-icon-hover-hide {
+ display: none;
+}
+
+.file-sidebar-file-checkbox-hover {
+ display: none;
+ width: 20px;
+ height: 20px;
+ border-radius: 5px;
+ border: 1.5px solid var(--border-hover, #52525b);
+}
+
+.file-sidebar-file-item:hover .file-sidebar-file-checkbox-hover {
+ display: block;
+}
+
+.file-sidebar-file-item.selected .file-sidebar-file-checkbox-hover {
+ display: none;
+}
+
+.file-sidebar-file-icon {
+ position: absolute;
+ inset: 0;
+}
+
+/* Checked state */
+.file-sidebar-file-check {
+ width: 20px;
+ height: 20px;
+ border-radius: 5px;
+ background-color: #3b82f6;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+}
+
+.file-sidebar-check-svg {
+ color: white;
+ flex-shrink: 0;
+}
+
+/* File info */
+.file-sidebar-file-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.file-sidebar-file-name {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-primary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.file-sidebar-file-item.selected .file-sidebar-file-name {
+ color: #3b82f6;
+}
+
+.file-sidebar-file-meta {
+ display: block;
+ font-size: 11px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+/* ---- Eye button (open in viewer) ---- */
+.file-sidebar-eye-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: 24px;
+ height: 24px;
+ border: none;
+ background: transparent;
+ border-radius: 4px;
+ cursor: pointer;
+ color: var(--text-muted);
+ padding: 0;
+ opacity: 0;
+ transition:
+ opacity 0.12s ease,
+ color 0.12s ease;
+}
+
+/* Show eye on hover (for any non-viewed file) */
+.file-sidebar-file-item:hover .file-sidebar-eye-btn {
+ opacity: 1;
+}
+
+/* Pin the viewed item when scrolled out of view in either direction */
+.file-sidebar-file-item.viewed {
+ position: sticky;
+ top: 0;
+ bottom: 0;
+ z-index: 2;
+ /* solid base + green tint overlay so content behind doesn't bleed through */
+ background-color: var(--bg-toolbar);
+ background-image: linear-gradient(
+ rgba(34, 197, 94, 0.1),
+ rgba(34, 197, 94, 0.1)
+ );
+}
+
+.file-sidebar-file-item.viewed .file-sidebar-file-name {
+ color: #22c55e;
+}
+
+.file-sidebar-file-item.viewed .file-sidebar-file-check {
+ background-color: #22c55e;
+}
+
+/* viewed takes precedence over selected */
+.file-sidebar-file-item.viewed.selected {
+ background-color: var(--bg-toolbar);
+ background-image: linear-gradient(
+ rgba(34, 197, 94, 0.1),
+ rgba(34, 197, 94, 0.1)
+ );
+}
+
+/* Always show eye for the currently viewed file */
+.file-sidebar-file-item.viewed .file-sidebar-eye-btn {
+ opacity: 1;
+ color: #22c55e;
+}
+
+.file-sidebar-eye-btn:hover {
+ color: var(--text-primary);
+}
+
+/* Eye open: shown by default */
+.file-sidebar-eye-open {
+ display: block !important;
+}
+.file-sidebar-eye-closed {
+ display: none !important;
+}
+
+/* On hover over a viewed item: swap to eye-closed */
+.file-sidebar-file-item.viewed:hover .file-sidebar-eye-open {
+ display: none !important;
+}
+.file-sidebar-file-item.viewed:hover .file-sidebar-eye-closed {
+ display: block !important;
+}
+
+/* ---- Date group headers ---- */
+.file-sidebar-date-group-header {
+ font-size: 11px;
+ font-weight: 500;
+ color: var(--text-muted);
+ padding: 0 10px 2px 10px;
+ margin-top: 8px;
+ user-select: none;
+}
+
+.file-sidebar-date-group-header:first-child {
+ margin-top: 0;
+}
+
+/* ---- Loading state ---- */
+.file-sidebar-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px 0;
+ opacity: 0.5;
+}
+
+/* ---- Empty state ---- */
+.file-sidebar-empty {
+ padding: 12px 16px 24px 16px;
+ text-align: center;
+}
+
+.file-sidebar-empty-text {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin: 0 0 2px 0;
+}
+
+.file-sidebar-empty-hint {
+ font-size: 11px;
+ color: var(--text-muted);
+ opacity: 0.7;
+ margin: 0;
+}
+
+/* ---- Thumbnail tooltip (hover preview) ---- */
+.file-sidebar-thumb-tooltip {
+ position: fixed;
+ z-index: 9999;
+ transform: translateY(-50%);
+ background: var(--bg-surface, #fff);
+ border: 1px solid var(--border-subtle);
+ border-radius: 8px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
+ padding: 4px;
+ width: 150px;
+ pointer-events: none;
+ animation: file-sidebar-thumb-in 0.12s ease;
+}
+
+.file-sidebar-thumb-img {
+ width: 100%;
+ height: auto;
+ display: block;
+ border-radius: 4px;
+}
+
+@keyframes file-sidebar-thumb-in {
+ from {
+ opacity: 0;
+ transform: translateY(-50%) scale(0.94);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(-50%) scale(1);
+ }
+}
diff --git a/frontend/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/src/core/components/shared/FileSidebarFileItem.tsx
new file mode 100644
index 0000000000..b0138ef2b0
--- /dev/null
+++ b/frontend/src/core/components/shared/FileSidebarFileItem.tsx
@@ -0,0 +1,297 @@
+import { useState, useCallback, useRef, useEffect } from "react";
+import { createPortal } from "react-dom";
+import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
+import VisibilityOffOutlinedIcon from "@mui/icons-material/VisibilityOffOutlined";
+import type { FileId } from "@app/types/file";
+import { FileDocIcon } from "@app/components/shared/FileDocIcon";
+import { getFileDocVariant } from "@app/components/shared/filePreview/getFileTypeIcon";
+import { useIndexedDB } from "@app/contexts/IndexedDBContext";
+import { useFileManagement } from "@app/contexts/FileContext";
+import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
+import { IMAGE_EXTENSIONS } from "@app/utils/fileUtils";
+import "@app/components/shared/FileSidebarFileItem.css";
+
+const THUMBNAIL_SIZE_LIMIT = 100 * 1024 * 1024; // 100MB
+
+/** Generate + persist a thumbnail for a sidebar file that doesn't have one yet. */
+function useLazyThumbnail(
+ fileId: FileId,
+ size: number,
+ thumbnailUrl?: string,
+): string | undefined {
+ const [thumb, setThumb] = useState<string | undefined>(thumbnailUrl);
+ const attempted = useRef(false);
+ const indexedDB = useIndexedDB();
+ const { updateStirlingFileStub } = useFileManagement();
+
+ // Sync prop changes (e.g. thumbnail arrives after TTL bump)
+ useEffect(() => {
+ if (thumbnailUrl) setThumb(thumbnailUrl);
+ }, [thumbnailUrl]);
+
+ useEffect(() => {
+ if (thumbnailUrl || attempted.current || size >= THUMBNAIL_SIZE_LIMIT)
+ return;
+ attempted.current = true;
+ let cancelled = false;
+
+ (async () => {
+ try {
+ const file = await indexedDB.loadFile(fileId);
+ if (!file || cancelled) return;
+ const thumbnail = await generateThumbnailForFile(file);
+ if (cancelled || !thumbnail) return;
+ setThumb(thumbnail);
+ void indexedDB.updateThumbnail(fileId, thumbnail);
+ updateStirlingFileStub(fileId, { thumbnailUrl: thumbnail });
+ } catch {
+ // non-critical
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [fileId, size, thumbnailUrl, indexedDB, updateStirlingFileStub]);
+
+ return thumb;
+}
+
+export function getFileExtension(name: string): string {
+ const parts = name.split(".");
+ return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
+}
+
+export type DateGroup =
+ | "today"
+ | "yesterday"
+ | "thisWeek"
+ | "thisMonth"
+ | "older";
+
+export const DATE_GROUP_ORDER: DateGroup[] = [
+ "today",
+ "yesterday",
+ "thisWeek",
+ "thisMonth",
+ "older",
+];
+
+export function getDateGroup(lastModified: number | undefined): DateGroup {
+ if (!lastModified) return "older";
+ const now = new Date();
+ const today = new Date(
+ now.getFullYear(),
+ now.getMonth(),
+ now.getDate(),
+ ).getTime();
+ const d = new Date(lastModified);
+ const fileDay = new Date(
+ d.getFullYear(),
+ d.getMonth(),
+ d.getDate(),
+ ).getTime();
+ const daysAgo = (today - fileDay) / 86400000;
+ if (daysAgo < 1) return "today";
+ if (daysAgo < 2) return "yesterday";
+ if (daysAgo < 7) return "thisWeek";
+ if (daysAgo < 30) return "thisMonth";
+ return "older";
+}
+
+export function formatFileDate(lastModifiedTs: number): string {
+ const lastModified = lastModifiedTs ? new Date(lastModifiedTs) : new Date();
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const yesterday = new Date(today);
+ yesterday.setDate(yesterday.getDate() - 1);
+ const fileDay = new Date(
+ lastModified.getFullYear(),
+ lastModified.getMonth(),
+ lastModified.getDate(),
+ );
+
+ if (fileDay.getTime() === today.getTime()) {
+ return lastModified
+ .toLocaleTimeString("en-US", {
+ hour: "numeric",
+ minute: "2-digit",
+ hour12: true,
+ })
+ .toLowerCase();
+ }
+ if (fileDay.getTime() === yesterday.getTime()) {
+ return "Yesterday";
+ }
+ const weekAgo = new Date(today);
+ weekAgo.setDate(weekAgo.getDate() - 7);
+ if (fileDay >= weekAgo) {
+ return lastModified.toLocaleDateString("en-US", { weekday: "long" });
+ }
+ return lastModified.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+function CheckIcon({
+ className,
+ style,
+}: {
+ className?: string;
+ style?: React.CSSProperties;
+}) {
+ return (
+ <svg
+ className={className}
+ style={style}
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="3"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="20 6 9 17 4 12" />
+ </svg>
+ );
+}
+
+function getSidebarFileIcon(ext: string): React.ReactElement {
+ const cls = "file-sidebar-file-icon file-sidebar-file-icon-hover-hide";
+ return <FileDocIcon className={cls} variant={getFileDocVariant(ext)} />;
+}
+
+export interface FileItemProps {
+ fileId: FileId;
+ name: string;
+ size?: number;
+ lastModified?: number;
+ isSelected: boolean;
+ isActive: boolean;
+ isViewedInViewer: boolean;
+ thumbnailUrl?: string;
+ onClick: (fileId: FileId) => void;
+ onEyeClick: (fileId: FileId, e: React.MouseEvent) => void;
+}
+
+export function FileItem({
+ fileId,
+ name,
+ size,
+ lastModified,
+ isSelected,
+ isActive,
+ isViewedInViewer,
+ thumbnailUrl,
+ onClick,
+ onEyeClick,
+}: FileItemProps) {
+ const ext = getFileExtension(name);
+ const dateLabel = lastModified ? formatFileDate(lastModified) : "";
+ const typeLabel = ext ? ext.toUpperCase() : "File";
+
+ // Only use raster thumbnails for PDFs and images — everything else uses scalable SVG icons
+ const useRasterThumb = ext === "pdf" || IMAGE_EXTENSIONS.has(ext);
+ const resolvedThumbnail = useLazyThumbnail(
+ fileId,
+ size ?? 0,
+ useRasterThumb ? thumbnailUrl : undefined,
+ );
+
+ const itemRef = useRef<HTMLDivElement>(null);
+ const [hoverRect, setHoverRect] = useState<DOMRect | null>(null);
+
+ const handleMouseEnter = useCallback(() => {
+ setHoverRect(itemRef.current?.getBoundingClientRect() ?? null);
+ }, []);
+
+ const handleMouseLeave = useCallback(() => setHoverRect(null), []);
+
+ // Reactive: tooltip appears as soon as both hover rect and thumbnail are ready
+ const thumbPos =
+ hoverRect && resolvedThumbnail
+ ? {
+ top: hoverRect.top + hoverRect.height / 2,
+ left: hoverRect.right + 10,
+ }
+ : null;
+
+ return (
+ <>
+ <div
+ ref={itemRef}
+ className={`file-sidebar-file-item${isSelected ? " selected" : ""}${isActive ? " active" : ""}${isViewedInViewer ? " viewed" : ""}`}
+ onClick={() => onClick(fileId)}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => e.key === "Enter" && onClick(fileId)}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
+ <div className="file-sidebar-file-icon-wrapper">
+ {isSelected ? (
+ <div className="file-sidebar-file-check">
+ <CheckIcon className="file-sidebar-check-svg" />
+ </div>
+ ) : (
+ <>
+ <div className="file-sidebar-file-checkbox-hover" />
+ {getSidebarFileIcon(ext)}
+ </>
+ )}
+ </div>
+ <div className="file-sidebar-file-info">
+ <span
+ className={`file-sidebar-file-name${isSelected ? " selected" : ""}`}
+ >
+ {name}
+ </span>
+ <span className="file-sidebar-file-meta">
+ {dateLabel}
+ {dateLabel && typeLabel ? " · " : ""}
+ {typeLabel}
+ </span>
+ </div>
+ <button
+ className="file-sidebar-eye-btn"
+ onClick={(e) => {
+ e.stopPropagation();
+ onEyeClick(fileId, e);
+ }}
+ tabIndex={-1}
+ type="button"
+ aria-label={isViewedInViewer ? "Close viewer" : "Open in viewer"}
+ >
+ <VisibilityOutlinedIcon
+ className="file-sidebar-eye-open"
+ sx={{ fontSize: "1.1rem" }}
+ />
+ <VisibilityOffOutlinedIcon
+ className="file-sidebar-eye-closed"
+ sx={{ fontSize: "1.1rem" }}
+ />
+ </button>
+ </div>
+
+ {useRasterThumb &&
+ thumbPos &&
+ resolvedThumbnail &&
+ createPortal(
+ <div
+ className="file-sidebar-thumb-tooltip"
+ style={{ top: thumbPos.top, left: thumbPos.left }}
+ >
+ <img
+ src={resolvedThumbnail}
+ alt=""
+ className="file-sidebar-thumb-img"
+ />
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/core/components/shared/HoverActionMenu.tsx b/frontend/src/core/components/shared/HoverActionMenu.tsx
index c43225854d..f4cfb247a1 100644
--- a/frontend/src/core/components/shared/HoverActionMenu.tsx
+++ b/frontend/src/core/components/shared/HoverActionMenu.tsx
@@ -11,6 +11,7 @@ export interface HoverAction {
disabled?: boolean;
color?: string;
hidden?: boolean;
+ dataTour?: string;
}
interface HoverActionMenuProps {
@@ -18,6 +19,7 @@ interface HoverActionMenuProps {
actions: HoverAction[];
position?: "inside" | "outside";
className?: string;
+ visibility?: "state" | "cssHover";
}
const HoverActionMenu: React.FC<HoverActionMenuProps> = ({
@@ -25,6 +27,7 @@ const HoverActionMenu: React.FC<HoverActionMenuProps> = ({
actions,
position = "inside",
className = "",
+ visibility = "state",
}) => {
const visibleActions = actions.filter((action) => !action.hidden);
@@ -32,10 +35,23 @@ const HoverActionMenu: React.FC<HoverActionMenuProps> = ({
return null;
}
+ const style: React.CSSProperties = { zIndex: Z_INDEX_HOVER_ACTION_MENU };
+ if (visibility === "state") {
+ style.opacity = show ? 1 : 0;
+ style.pointerEvents = show ? "auto" : "none";
+ } else if (show) {
+ // Force visible (e.g. mobile) even when CSS-hover mode is active.
+ style.opacity = 1;
+ style.pointerEvents = "auto";
+ }
+
return (
<div
className={`${styles.hoverMenu} ${position === "outside" ? styles.outside : styles.inside} ${className}`}
- style={{ opacity: show ? 1 : 0, zIndex: Z_INDEX_HOVER_ACTION_MENU }}
+ style={style}
+ data-hover-action-menu="true"
+ data-hover-action-menu-mode={visibility}
+ data-force-visible={show ? "true" : "false"}
onMouseDown={(e) => e.stopPropagation()}
onMouseUp={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
@@ -48,7 +64,8 @@ const HoverActionMenu: React.FC<HoverActionMenuProps> = ({
disabled={action.disabled}
onClick={action.onClick}
c={action.color}
- style={{ color: action.color || "var(--right-rail-icon)" }}
+ style={{ color: action.color || "var(--text-secondary)" }}
+ data-tour={action.dataTour}
>
{action.icon}
</ActionIcon>
diff --git a/frontend/src/core/components/shared/InfoBanner.tsx b/frontend/src/core/components/shared/InfoBanner.tsx
index a9fde9ae42..50a1cba225 100644
--- a/frontend/src/core/components/shared/InfoBanner.tsx
+++ b/frontend/src/core/components/shared/InfoBanner.tsx
@@ -50,6 +50,7 @@ interface InfoBannerProps {
buttonVariant?: "light" | "filled" | "white" | "outline" | "subtle";
minHeight?: number | string;
closeIconColor?: string;
+ compact?: boolean;
}
/**
@@ -75,6 +76,7 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
buttonVariant = "light",
minHeight = 56,
closeIconColor,
+ compact = false,
}) => {
if (!show) {
return null;
@@ -85,13 +87,21 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
onDismiss?.();
};
+ const iconSize = compact ? "1rem" : "1.2rem";
+ const textSize = compact ? "xs" : "sm";
+ const buttonSize = compact ? "xs" : "xs";
+
return (
<Paper
- p="sm"
+ p={compact ? "xs" : "sm"}
radius={0}
style={{
background: background ?? toneStyle.background,
- borderBottom: `1px solid ${borderColor ?? toneStyle.border}`,
+ border: "none",
+ borderBottom:
+ borderColor === "transparent"
+ ? "none"
+ : `1px solid ${borderColor ?? toneStyle.border}`,
minHeight,
display: "flex",
alignItems: "center",
@@ -105,22 +115,22 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
style={{ width: "100%" }}
>
<Group
- gap="sm"
+ gap={compact ? "xs" : "sm"}
align="center"
wrap="nowrap"
style={{ flex: 1, minWidth: 0 }}
>
<LocalIcon
icon={icon}
- width="1.2rem"
- height="1.2rem"
+ width={iconSize}
+ height={iconSize}
style={{ color: iconColor ?? toneStyle.icon, flexShrink: 0 }}
/>
- <Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
+ <Stack gap={compact ? 1 : 2} style={{ flex: 1, minWidth: 0 }}>
{title && (
<Text
fw={600}
- size="sm"
+ size={textSize}
style={{ color: textColor ?? toneStyle.text }}
>
{title}
@@ -128,9 +138,9 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
)}
<Text
fw={title ? 400 : 500}
- size="sm"
+ size={textSize}
style={{ color: textColor ?? toneStyle.text }}
- lineClamp={2}
+ lineClamp={compact ? 1 : 2}
>
{message}
</Text>
@@ -141,11 +151,15 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
<Button
variant={buttonVariant}
color={buttonColor ?? toneStyle.buttonColor}
- size="xs"
+ size={buttonSize}
onClick={onButtonClick}
loading={loading}
leftSection={
- <LocalIcon icon={buttonIcon} width="0.9rem" height="0.9rem" />
+ <LocalIcon
+ icon={buttonIcon}
+ width={compact ? "0.75rem" : "0.9rem"}
+ height={compact ? "0.75rem" : "0.9rem"}
+ />
}
>
{buttonText}
@@ -160,7 +174,11 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
aria-label="Dismiss"
style={closeIconColor ? { color: closeIconColor } : undefined}
>
- <LocalIcon icon="close-rounded" width="1rem" height="1rem" />
+ <LocalIcon
+ icon="close-rounded"
+ width={compact ? "0.85rem" : "1rem"}
+ height={compact ? "0.85rem" : "1rem"}
+ />
</ActionIcon>
)}
</Group>
diff --git a/frontend/src/core/components/shared/LandingPage.css b/frontend/src/core/components/shared/LandingPage.css
index e818217600..233b15cfee 100644
--- a/frontend/src/core/components/shared/LandingPage.css
+++ b/frontend/src/core/components/shared/LandingPage.css
@@ -5,14 +5,11 @@
/* ── Hero text ───────────────────────────────────────────── */
.landing-title {
- margin: 0;
- margin-top: 1.75rem;
- margin-bottom: 0.5rem;
- text-align: center;
- font-size: 2.125rem;
- font-weight: 700;
- letter-spacing: -0.02em;
- color: var(--text-primary);
+ display: block;
+ margin: 1.75rem auto 0.5rem;
+ height: 3rem;
+ width: auto;
+ max-width: 100%;
}
.landing-subtitle {
diff --git a/frontend/src/core/components/shared/LandingPage.tsx b/frontend/src/core/components/shared/LandingPage.tsx
index e52eb98b56..1f9f117f3e 100644
--- a/frontend/src/core/components/shared/LandingPage.tsx
+++ b/frontend/src/core/components/shared/LandingPage.tsx
@@ -8,6 +8,7 @@ import MobileUploadModal from "@app/components/shared/MobileUploadModal";
import { openFilesFromDisk } from "@app/services/openFilesFromDisk";
import { LandingDocumentStack } from "@app/components/shared/LandingDocumentStack";
import { LandingActions } from "@app/components/shared/LandingActions";
+import { Wordmark } from "@app/components/shared/Wordmark";
import "@app/components/shared/LandingPage.css";
const LandingPage = () => {
@@ -79,9 +80,10 @@ const LandingPage = () => {
>
<LandingDocumentStack />
- <h1 className="landing-title">
- {t("landing.heroTitle", "Stirling PDF")}
- </h1>
+ <Wordmark
+ alt={t("landing.heroTitle", "Stirling PDF")}
+ className="landing-title"
+ />
<p className="landing-subtitle">
{t(
"landing.heroSubtitle",
diff --git a/frontend/src/core/components/shared/LanguageSelector.tsx b/frontend/src/core/components/shared/LanguageSelector.tsx
index e0896a21eb..1319aad13f 100644
--- a/frontend/src/core/components/shared/LanguageSelector.tsx
+++ b/frontend/src/core/components/shared/LanguageSelector.tsx
@@ -91,10 +91,10 @@ const LanguageItem: React.FC<LanguageItemProps> = ({
? "light-dark(var(--mantine-color-blue-1), var(--mantine-color-blue-8))"
: "transparent",
color: disabled
- ? "light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3))"
+ ? "var(--text-muted)"
: isSelected
- ? "light-dark(var(--mantine-color-blue-9), var(--mantine-color-white))"
- : "light-dark(var(--mantine-color-gray-7), var(--mantine-color-white))",
+ ? "light-dark(var(--mantine-color-blue-9), var(--mantine-color-blue-3))"
+ : "var(--text-primary)",
transition: "all 0.12s cubic-bezier(0.25, 0.46, 0.45, 0.94)",
cursor: disabled ? "not-allowed" : "pointer",
"&:hover": !disabled
@@ -274,11 +274,11 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({
<ActionIcon
variant="subtle"
radius="md"
- className="right-rail-icon"
+ data-testid="language-selector-button"
title={!opened && tooltip ? tooltip : undefined}
styles={{
root: {
- color: "var(--right-rail-icon)",
+ color: "var(--text-secondary)",
"&:hover": {
backgroundColor:
"light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5))",
@@ -292,14 +292,14 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({
<Button
variant="subtle"
size="sm"
+ data-testid="language-selector-button"
leftSection={
<LocalIcon icon="language" width="1.5rem" height="1.5rem" />
}
styles={{
root: {
border: "none",
- color:
- "light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-1))",
+ color: "var(--text-primary)",
transition:
"background-color 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",
"&:hover": {
diff --git a/frontend/src/core/components/shared/MultiSelectControls.tsx b/frontend/src/core/components/shared/MultiSelectControls.tsx
index 7a1cb80d10..447662e9dd 100644
--- a/frontend/src/core/components/shared/MultiSelectControls.tsx
+++ b/frontend/src/core/components/shared/MultiSelectControls.tsx
@@ -33,11 +33,11 @@ const MultiSelectControls = ({
>
<Group justify="space-between">
<Text size="sm">
- {selectedCount} {t("fileManager.filesSelected", "files selected")}
+ {selectedCount} {t("fileManager.filesSelected", "files")}
</Text>
<Group>
<Button size="xs" variant="light" onClick={onClearSelection}>
- {t("fileManager.clearSelection", "Clear Selection")}
+ {t("fileManager.clearSelection", "Clear files")}
</Button>
{onAddToUpload && (
diff --git a/frontend/src/core/components/shared/PageEditorFileDropdown.tsx b/frontend/src/core/components/shared/PageEditorFileDropdown.tsx
index 4cbd84b157..fbe44c35c6 100644
--- a/frontend/src/core/components/shared/PageEditorFileDropdown.tsx
+++ b/frontend/src/core/components/shared/PageEditorFileDropdown.tsx
@@ -197,7 +197,7 @@ export const PageEditorFileDropdown: React.FC<PageEditorFileDropdownProps> = ({
<Menu.Dropdown
className="ph-no-capture"
style={{
- backgroundColor: "var(--right-rail-bg)",
+ backgroundColor: "var(--bg-file-manager)",
border: "1px solid var(--border-subtle)",
borderRadius: "8px",
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
diff --git a/frontend/src/core/components/shared/RightRail.tsx b/frontend/src/core/components/shared/RightRail.tsx
deleted file mode 100644
index 95d4694a76..0000000000
--- a/frontend/src/core/components/shared/RightRail.tsx
+++ /dev/null
@@ -1,375 +0,0 @@
-import React, { useCallback, useMemo } from "react";
-import { ActionIcon, Divider } from "@mantine/core";
-import "@app/components/shared/rightRail/RightRail.css";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { useRightRail } from "@app/contexts/RightRailContext";
-import {
- useFileState,
- useFileSelection,
- useFileActions,
-} from "@app/contexts/FileContext";
-import { isStirlingFile } from "@app/types/fileContext";
-import { useNavigationState } from "@app/contexts/NavigationContext";
-import { useTranslation } from "react-i18next";
-import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
-
-import LanguageSelector from "@app/components/shared/LanguageSelector";
-import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
-import { Tooltip } from "@app/components/shared/Tooltip";
-import { ViewerContext } from "@app/contexts/ViewerContext";
-import LocalIcon from "@app/components/shared/LocalIcon";
-import { RightRailFooterExtensions } from "@app/components/rightRail/RightRailFooterExtensions";
-import DarkModeIcon from "@mui/icons-material/DarkMode";
-import LightModeIcon from "@mui/icons-material/LightMode";
-
-import { useSidebarContext } from "@app/contexts/SidebarContext";
-import {
- RightRailButtonConfig,
- RightRailRenderContext,
- RightRailSection,
-} from "@app/types/rightRail";
-import { useRightRailTooltipSide } from "@app/hooks/useRightRailTooltipSide";
-import { downloadFile } from "@app/services/downloadService";
-
-const SECTION_ORDER: RightRailSection[] = ["top", "middle", "bottom"];
-
-function renderWithTooltip(
- node: React.ReactNode,
- tooltip: React.ReactNode | undefined,
- position: "left" | "right",
- offset: number,
-) {
- if (!tooltip) return node;
-
- const portalTarget =
- typeof document !== "undefined" ? document.body : undefined;
-
- return (
- <Tooltip
- content={tooltip}
- position={position}
- offset={offset}
- arrow
- portalTarget={portalTarget}
- >
- <div className="right-rail-tooltip-wrapper">{node}</div>
- </Tooltip>
- );
-}
-
-export default function RightRail() {
- const { sidebarRefs } = useSidebarContext();
- const { position: tooltipPosition, offset: tooltipOffset } =
- useRightRailTooltipSide(sidebarRefs);
- const { t } = useTranslation();
- const terminology = useFileActionTerminology();
- const icons = useFileActionIcons();
- const viewerContext = React.useContext(ViewerContext);
- const { toggleTheme, themeMode } = useRainbowThemeContext();
- const { buttons, actions, allButtonsDisabled } = useRightRail();
-
- const { pageEditorFunctions, toolPanelMode, leftPanelView } =
- useToolWorkflow();
- const disableForFullscreen =
- toolPanelMode === "fullscreen" && leftPanelView === "toolPicker";
-
- const { workbench: currentView } = useNavigationState();
-
- const { selectors } = useFileState();
- const { selectedFiles, selectedFileIds } = useFileSelection();
- const { actions: fileActions } = useFileActions();
- const activeFiles = selectors.getFiles();
- const pageEditorTotalPages = pageEditorFunctions?.totalPages ?? 0;
- const pageEditorSelectedCount =
- pageEditorFunctions?.selectedPageIds?.length ?? 0;
-
- const totalItems = useMemo(() => {
- if (currentView === "pageEditor") return pageEditorTotalPages;
- return activeFiles.length;
- }, [currentView, pageEditorTotalPages, activeFiles.length]);
-
- const selectedCount = useMemo(() => {
- if (currentView === "pageEditor") {
- return pageEditorSelectedCount;
- }
- return selectedFileIds.length;
- }, [currentView, pageEditorSelectedCount, selectedFileIds.length]);
-
- const sectionsWithButtons = useMemo(() => {
- return SECTION_ORDER.map((section) => {
- const sectionButtons = buttons.filter(
- (btn) => (btn.section ?? "top") === section && (btn.visible ?? true),
- );
- return { section, buttons: sectionButtons };
- }).filter((entry) => entry.buttons.length > 0);
- }, [buttons]);
-
- const renderButton = useCallback(
- (btn: RightRailButtonConfig) => {
- const action = actions[btn.id];
- const disabled = Boolean(
- btn.disabled || allButtonsDisabled || disableForFullscreen,
- );
- const isActive = Boolean(btn.active);
-
- const triggerAction = () => {
- if (!disabled) action?.();
- };
-
- if (btn.render) {
- const context: RightRailRenderContext = {
- id: btn.id,
- disabled,
- allButtonsDisabled,
- action,
- triggerAction,
- active: isActive,
- };
- return btn.render(context) ?? null;
- }
-
- if (!btn.icon) return null;
-
- const ariaLabel =
- btn.ariaLabel ||
- (typeof btn.tooltip === "string" ? (btn.tooltip as string) : undefined);
- const className = ["right-rail-icon", btn.className]
- .filter(Boolean)
- .join(" ");
- const buttonNode = (
- <ActionIcon
- variant={isActive ? "filled" : "subtle"}
- color={isActive ? "blue" : undefined}
- radius="md"
- className={className}
- onClick={triggerAction}
- disabled={disabled}
- aria-label={ariaLabel}
- aria-pressed={isActive ? true : undefined}
- data-active={isActive ? "true" : "false"}
- >
- {btn.icon}
- </ActionIcon>
- );
-
- return renderWithTooltip(
- buttonNode,
- btn.tooltip,
- tooltipPosition,
- tooltipOffset,
- );
- },
- [
- actions,
- allButtonsDisabled,
- disableForFullscreen,
- tooltipPosition,
- tooltipOffset,
- ],
- );
-
- const handleExportAll = useCallback(
- async (forceNewFile = false) => {
- if (currentView === "viewer") {
- const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
- if (!buffer) return;
- const fileToExport =
- selectedFiles.length > 0 ? selectedFiles[0] : activeFiles[0];
- if (!fileToExport) return;
- const stub = isStirlingFile(fileToExport)
- ? selectors.getStirlingFileStub(fileToExport.fileId)
- : undefined;
- try {
- const result = await downloadFile({
- data: new Blob([buffer], { type: "application/pdf" }),
- filename: fileToExport.name,
- localPath: forceNewFile ? undefined : stub?.localFilePath,
- });
- if (!forceNewFile && !result.cancelled && stub && result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch (error) {
- console.error("[RightRail] Failed to export viewer file:", error);
- }
- return;
- }
-
- if (currentView === "pageEditor") {
- pageEditorFunctions?.onExportAll?.();
- return;
- }
-
- const filesToExport =
- selectedFiles.length > 0 ? selectedFiles : activeFiles;
-
- if (filesToExport.length > 0) {
- for (const file of filesToExport) {
- const stub = isStirlingFile(file)
- ? selectors.getStirlingFileStub(file.fileId)
- : undefined;
- try {
- const result = await downloadFile({
- data: file,
- filename: file.name,
- localPath: forceNewFile ? undefined : stub?.localFilePath,
- });
- if (result.cancelled) continue;
- if (!forceNewFile && stub && result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch (error) {
- console.error(
- "[RightRail] Failed to export file:",
- file.name,
- error,
- );
- }
- }
- }
- },
- [
- currentView,
- selectedFiles,
- activeFiles,
- pageEditorFunctions,
- viewerContext,
- selectors,
- fileActions,
- ],
- );
-
- const downloadTooltip = useMemo(() => {
- if (currentView === "pageEditor") {
- return t("rightRail.exportAll", "Export PDF");
- }
- if (currentView === "viewer") {
- return terminology.download;
- }
- if (selectedCount > 0) {
- return terminology.downloadSelected;
- }
- return terminology.downloadAll;
- }, [currentView, selectedCount, t, terminology]);
-
- return (
- <div
- ref={sidebarRefs.rightRailRef}
- className="right-rail"
- data-sidebar="right-rail"
- >
- <div className="right-rail-inner">
- {sectionsWithButtons.map(({ section, buttons: sectionButtons }) => (
- <React.Fragment key={section}>
- <div className="right-rail-section" data-tour="right-rail-controls">
- {sectionButtons.map((btn, index) => {
- const content = renderButton(btn);
- if (!content) return null;
- return (
- <div
- key={btn.id}
- className="right-rail-button-wrapper"
- style={{ animationDelay: `${index * 50}ms` }}
- >
- {content}
- </div>
- );
- })}
- </div>
- <Divider className="right-rail-divider" />
- </React.Fragment>
- ))}
- <div
- style={{
- display: "flex",
- flexDirection: "column",
- alignItems: "center",
- gap: "1rem",
- }}
- data-tour="right-rail-settings"
- >
- {renderWithTooltip(
- <ActionIcon
- variant="subtle"
- radius="md"
- className="right-rail-icon"
- onClick={toggleTheme}
- >
- {themeMode === "dark" ? (
- <LightModeIcon sx={{ fontSize: "1.5rem" }} />
- ) : (
- <DarkModeIcon sx={{ fontSize: "1.5rem" }} />
- )}
- </ActionIcon>,
- t("rightRail.toggleTheme", "Toggle Theme"),
- tooltipPosition,
- tooltipOffset,
- )}
-
- <LanguageSelector
- position="left-start"
- offset={6}
- compact
- tooltip={t("rightRail.language", "Language")}
- />
-
- {renderWithTooltip(
- <ActionIcon
- variant="subtle"
- radius="md"
- className="right-rail-icon"
- onClick={() => handleExportAll()}
- disabled={
- disableForFullscreen ||
- (currentView !== "viewer" &&
- (totalItems === 0 || allButtonsDisabled))
- }
- >
- <LocalIcon
- icon={icons.downloadIconName}
- width="1.5rem"
- height="1.5rem"
- />
- </ActionIcon>,
- downloadTooltip,
- tooltipPosition,
- tooltipOffset,
- )}
- {icons.saveAsIconName &&
- renderWithTooltip(
- <ActionIcon
- variant="subtle"
- radius="md"
- className="right-rail-icon"
- onClick={() => handleExportAll(true)}
- disabled={
- disableForFullscreen ||
- (currentView !== "viewer" &&
- (totalItems === 0 || allButtonsDisabled))
- }
- >
- <LocalIcon
- icon={icons.saveAsIconName}
- width="1.5rem"
- height="1.5rem"
- />
- </ActionIcon>,
- t("rightRail.saveAs", "Save As"),
- tooltipPosition,
- tooltipOffset,
- )}
- </div>
-
- <div className="right-rail-spacer" />
-
- <RightRailFooterExtensions className="right-rail-footer" />
- </div>
- </div>
- );
-}
diff --git a/frontend/src/core/components/shared/TextInput.tsx b/frontend/src/core/components/shared/TextInput.tsx
index 12725f44e4..e134710529 100644
--- a/frontend/src/core/components/shared/TextInput.tsx
+++ b/frontend/src/core/components/shared/TextInput.tsx
@@ -36,6 +36,8 @@ export interface TextInputProps {
"aria-label"?: string;
/** Focus event handler */
onFocus?: () => void;
+ /** Allow the icon to receive pointer events (e.g. when icon is a clickable button) */
+ iconClickable?: boolean;
}
export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
@@ -56,6 +58,7 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
readOnly = false,
"aria-label": ariaLabel,
onFocus,
+ iconClickable = false,
...props
},
ref,
@@ -76,7 +79,10 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
{icon && (
<span
className={styles.icon}
- style={{ color: "var(--search-text-and-icon-color)" }}
+ style={{
+ pointerEvents: iconClickable ? "auto" : "none",
+ left: "12px",
+ }}
>
{icon}
</span>
@@ -96,8 +102,6 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
aria-label={ariaLabel}
onFocus={onFocus}
style={{
- backgroundColor: "var(--input-bg)",
- color: "var(--search-text-and-icon-color)",
paddingRight: shouldShowClearButton ? "40px" : "12px",
paddingLeft: icon ? "40px" : "12px",
}}
@@ -108,7 +112,6 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
type="button"
className={styles.clearButton}
onClick={handleClear}
- style={{ color: "var(--search-text-and-icon-color)" }}
aria-label="Clear input"
>
<LocalIcon icon="close-rounded" width="1.25rem" height="1.25rem" />
diff --git a/frontend/src/core/components/shared/ViewerInlineControls.tsx b/frontend/src/core/components/shared/ViewerInlineControls.tsx
new file mode 100644
index 0000000000..96a9d2f06c
--- /dev/null
+++ b/frontend/src/core/components/shared/ViewerInlineControls.tsx
@@ -0,0 +1,81 @@
+import React, { useState, useEffect } from "react";
+import { ActionIcon, Slider } from "@mantine/core";
+import { useViewer } from "@app/contexts/ViewerContext";
+import { useNavigationState } from "@app/contexts/NavigationContext";
+import ZoomInIcon from "@mui/icons-material/ZoomIn";
+import ZoomOutIcon from "@mui/icons-material/ZoomOut";
+
+/**
+ * Compact zoom controls rendered inline in the WorkbenchBar when the current workbench is "viewer".
+ */
+export function ViewerInlineControls() {
+ const { workbench } = useNavigationState();
+ const viewer = useViewer();
+
+ const [zoomPercent, setZoomPercent] = useState(100);
+
+ useEffect(() => {
+ const zoomState = viewer.getZoomState();
+ setZoomPercent(zoomState.zoomPercent || 100);
+
+ const unregister = viewer.registerImmediateZoomUpdate((pct) => {
+ setZoomPercent(pct);
+ });
+ return () => unregister?.();
+ }, [viewer.registerImmediateZoomUpdate]);
+
+ if (workbench !== "viewer") return null;
+
+ const sliderValue = Math.min(Math.max(zoomPercent, 20), 500);
+
+ return (
+ <div className="viewer-inline-controls">
+ {/* Divider */}
+ <div className="workbench-bar-divider" />
+
+ {/* Zoom controls */}
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={() => viewer.zoomActions.zoomOut()}
+ aria-label="Zoom out"
+ >
+ <ZoomOutIcon sx={{ fontSize: "1rem" }} />
+ </ActionIcon>
+
+ <div className="viewer-inline-controls__slider-wrap">
+ <Slider
+ value={sliderValue}
+ min={20}
+ max={500}
+ step={5}
+ onChange={(val) => {
+ viewer.zoomActions.setZoomLevel?.(val / 100);
+ }}
+ size="xs"
+ styles={{
+ root: { width: "6rem" },
+ thumb: { width: 14, height: 14 },
+ track: { height: 3 },
+ }}
+ label={null}
+ />
+ </div>
+
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={() => viewer.zoomActions.zoomIn()}
+ aria-label="Zoom in"
+ >
+ <ZoomInIcon sx={{ fontSize: "1rem" }} />
+ </ActionIcon>
+
+ <span className="viewer-inline-controls__zoom-pct">
+ {Math.round(zoomPercent)}%
+ </span>
+ </div>
+ );
+}
diff --git a/frontend/src/core/components/shared/WorkbenchBar.css b/frontend/src/core/components/shared/WorkbenchBar.css
new file mode 100644
index 0000000000..ced97dcff6
--- /dev/null
+++ b/frontend/src/core/components/shared/WorkbenchBar.css
@@ -0,0 +1,187 @@
+/* ========== WORKBENCH BAR ========== */
+/* Horizontal toolbar at the top of the workbench area. */
+
+.workbench-bar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ align-content: flex-start;
+ min-height: 48px;
+ padding: 0 8px;
+ background-color: var(--bg-toolbar);
+ border-bottom: 1px solid var(--border-subtle);
+ flex-shrink: 0;
+ z-index: 50;
+}
+
+/* ---- View switcher (left) ---- */
+.workbench-bar-views {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ flex-shrink: 0;
+ order: 1;
+ height: 48px;
+ z-index: 0;
+}
+
+.workbench-bar-view-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 10px;
+ border: none;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--text-secondary);
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition:
+ background-color 0.15s ease,
+ color 0.15s ease;
+ white-space: nowrap;
+}
+
+.workbench-bar-view-btn:hover {
+ background-color: var(--bg-hover);
+ color: var(--text-primary);
+}
+
+.workbench-bar-view-btn.active {
+ background-color: var(--mantine-color-blue-light, rgba(59, 130, 246, 0.12));
+ color: var(--mantine-color-blue-6, #3b82f6);
+}
+
+.workbench-bar-view-btn svg {
+ font-size: 16px !important;
+ width: 16px;
+ height: 16px;
+}
+
+.workbench-bar-view-label {
+ line-height: 1;
+}
+
+/* ---- Center: tool buttons ---- */
+
+/* Single-row: center sits between views and globals */
+.workbench-bar-center {
+ order: 2;
+ flex: 1 1 auto;
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 2px;
+ height: 48px;
+ overflow: hidden;
+}
+
+/* Two-row: center drops below views+globals */
+.workbench-bar[data-wrapped="true"] .workbench-bar-center {
+ order: 3;
+ flex: 0 0 100%;
+ height: auto;
+ overflow: visible;
+ padding: 4px 0;
+ border-top: 1px solid var(--border-subtle);
+}
+
+/* ---- Right: global buttons (theme / language / download) ---- */
+.workbench-bar-globals {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ flex-shrink: 0;
+ order: 3;
+ height: 48px;
+ margin-left: auto;
+}
+
+/* In two-row mode globals moves to row 1 right side */
+.workbench-bar[data-wrapped="true"] .workbench-bar-globals {
+ order: 2;
+ margin-left: auto;
+}
+
+/* Shared action icon style — applies to both center and global buttons */
+.workbench-bar-action-icon {
+ color: var(--text-secondary) !important;
+ width: 28px !important;
+ height: 28px !important;
+ background: transparent !important;
+}
+
+.workbench-bar-action-icon svg,
+.workbench-bar-action-icon img {
+ color: inherit !important;
+ fill: currentColor;
+}
+
+.workbench-bar-action-icon:hover {
+ color: var(--text-primary) !important;
+ background-color: var(--bg-hover) !important;
+}
+
+.workbench-bar-action-icon[data-variant="filled"] {
+ background: var(--mantine-color-blue-6, #3b82f6) !important;
+ color: #fff !important;
+}
+
+.workbench-bar-action-icon[data-variant="filled"]:hover {
+ background: var(--mantine-color-blue-7, #2563eb) !important;
+ color: #fff !important;
+}
+
+.workbench-bar-action-wrapper {
+ display: flex;
+ align-items: center;
+}
+
+.workbench-bar-tooltip-wrapper {
+ display: inline-flex;
+ align-items: center;
+}
+
+.workbench-bar-divider {
+ width: 1px;
+ height: 16px;
+ background-color: var(--border-subtle);
+ margin: 0 4px;
+}
+
+/* Extra breathing room around the export/close separator */
+.workbench-bar-globals-sep {
+ margin: 0 8px;
+}
+
+/* ---- Inline viewer controls (page nav + zoom) ---- */
+.viewer-inline-controls {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.viewer-inline-controls__page {
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ min-width: 3rem;
+ text-align: center;
+ white-space: nowrap;
+}
+
+.viewer-inline-controls__slider-wrap {
+ display: flex;
+ align-items: center;
+ padding: 0 4px;
+}
+
+.viewer-inline-controls__zoom-pct {
+ font-size: 12px;
+ color: var(--text-muted);
+ min-width: 2.5rem;
+ text-align: right;
+ white-space: nowrap;
+}
diff --git a/frontend/src/core/components/shared/WorkbenchBar.tsx b/frontend/src/core/components/shared/WorkbenchBar.tsx
new file mode 100644
index 0000000000..b50e8ae47e
--- /dev/null
+++ b/frontend/src/core/components/shared/WorkbenchBar.tsx
@@ -0,0 +1,490 @@
+import React, { useCallback, useEffect, useMemo, useRef } from "react";
+import { ActionIcon } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
+import {
+ useFileState,
+ useFileSelection,
+ useFileActions,
+} from "@app/contexts/FileContext";
+import { isStirlingFile } from "@app/types/fileContext";
+import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
+import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import { useNavigationState } from "@app/contexts/NavigationContext";
+import { ViewerContext, useViewer } from "@app/contexts/ViewerContext";
+import { WorkbenchType, isBaseWorkbench } from "@app/types/workbench";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import LocalIcon from "@app/components/shared/LocalIcon";
+import { downloadFile } from "@app/services/downloadService";
+import {
+ WorkbenchBarButtonConfig,
+ WorkbenchBarRenderContext,
+ WorkbenchBarSection,
+} from "@app/types/workbenchBar";
+import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
+import FolderIcon from "@mui/icons-material/Folder";
+import CloseIcon from "@mui/icons-material/Close";
+import PrintIcon from "@mui/icons-material/Print";
+import "@app/components/shared/WorkbenchBar.css";
+
+const SECTION_ORDER: WorkbenchBarSection[] = ["top", "middle", "bottom"];
+
+interface ViewOption {
+ value: WorkbenchType;
+ label: string;
+ icon: React.ReactNode;
+}
+
+interface WorkbenchBarProps {
+ currentView: WorkbenchType;
+ setCurrentView: (view: WorkbenchType) => void;
+ hasFiles: boolean;
+}
+
+function renderWithTooltip(
+ node: React.ReactNode,
+ tooltip: React.ReactNode | undefined,
+) {
+ if (!tooltip) return node;
+ return (
+ <Tooltip
+ content={tooltip}
+ position="bottom"
+ offset={6}
+ arrow
+ portalTarget={typeof document !== "undefined" ? document.body : undefined}
+ >
+ <div className="workbench-bar-tooltip-wrapper">{node}</div>
+ </Tooltip>
+ );
+}
+
+export default function WorkbenchBar({
+ currentView,
+ setCurrentView,
+ hasFiles,
+}: WorkbenchBarProps) {
+ const { t } = useTranslation();
+ const { buttons, actions, allButtonsDisabled } = useWorkbenchBar();
+ const {
+ pageEditorFunctions,
+ toolPanelMode,
+ leftPanelView,
+ customWorkbenchViews,
+ } = useToolWorkflow();
+ const { selectedTool } = useNavigationState();
+ const isCustomView = !isBaseWorkbench(currentView);
+ const disableForFullscreen =
+ toolPanelMode === "fullscreen" && leftPanelView === "toolPicker";
+ const terminology = useFileActionTerminology();
+ const icons = useFileActionIcons();
+ const viewerContext = React.useContext(ViewerContext);
+
+ const { selectors } = useFileState();
+ const { selectedFiles, selectedFileIds } = useFileSelection();
+ const { actions: fileActions } = useFileActions();
+ const activeFiles = selectors.getFiles();
+ const { activeFileId, setActiveFileId } = useViewer();
+ const pageEditorTotalPages = pageEditorFunctions?.totalPages ?? 0;
+ const pageEditorSelectedCount =
+ pageEditorFunctions?.selectedPageIds?.length ?? 0;
+
+ const totalItems = useMemo(() => {
+ if (currentView === "pageEditor") return pageEditorTotalPages;
+ return activeFiles.length;
+ }, [currentView, pageEditorTotalPages, activeFiles.length]);
+
+ const selectedCount = useMemo(() => {
+ if (currentView === "pageEditor") return pageEditorSelectedCount;
+ return selectedFileIds.length;
+ }, [currentView, pageEditorSelectedCount, selectedFileIds.length]);
+
+ const sectionsWithButtons = useMemo(() => {
+ return SECTION_ORDER.map((section) => {
+ const sectionButtons = buttons.filter(
+ (btn) => (btn.section ?? "top") === section && (btn.visible ?? true),
+ );
+ return { section, buttons: sectionButtons };
+ }).filter((entry) => entry.buttons.length > 0);
+ }, [buttons]);
+
+ const handleExportAll = useCallback(
+ async (forceNewFile = false) => {
+ if (currentView === "viewer") {
+ const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
+ if (!buffer) return;
+ const fileToExport =
+ selectedFiles.length > 0 ? selectedFiles[0] : activeFiles[0];
+ if (!fileToExport) return;
+ const stub = isStirlingFile(fileToExport)
+ ? selectors.getStirlingFileStub(fileToExport.fileId)
+ : undefined;
+ try {
+ const result = await downloadFile({
+ data: new Blob([buffer], { type: "application/pdf" }),
+ filename: fileToExport.name,
+ localPath: forceNewFile ? undefined : stub?.localFilePath,
+ });
+ if (!forceNewFile && !result.cancelled && stub && result.savedPath) {
+ fileActions.updateStirlingFileStub(stub.id, {
+ localFilePath: stub.localFilePath ?? result.savedPath,
+ isDirty: false,
+ });
+ }
+ } catch (error) {
+ console.error("[WorkbenchBar] Failed to export viewer file:", error);
+ }
+ return;
+ }
+
+ if (currentView === "pageEditor") {
+ pageEditorFunctions?.onExportAll?.();
+ return;
+ }
+
+ const filesToExport =
+ selectedFiles.length > 0 ? selectedFiles : activeFiles;
+ for (const file of filesToExport) {
+ const stub = isStirlingFile(file)
+ ? selectors.getStirlingFileStub(file.fileId)
+ : undefined;
+ try {
+ const result = await downloadFile({
+ data: file,
+ filename: file.name,
+ localPath: forceNewFile ? undefined : stub?.localFilePath,
+ });
+ if (result.cancelled) continue;
+ if (!forceNewFile && stub && result.savedPath) {
+ fileActions.updateStirlingFileStub(stub.id, {
+ localFilePath: stub.localFilePath ?? result.savedPath,
+ isDirty: false,
+ });
+ }
+ } catch (error) {
+ console.error(
+ "[WorkbenchBar] Failed to export file:",
+ file.name,
+ error,
+ );
+ }
+ }
+ },
+ [
+ currentView,
+ selectedFiles,
+ activeFiles,
+ pageEditorFunctions,
+ viewerContext,
+ selectors,
+ fileActions,
+ ],
+ );
+
+ const handlePrint = useCallback(() => {
+ viewerContext?.printActions?.print?.();
+ }, [viewerContext]);
+
+ const handleClose = useCallback(async () => {
+ if (currentView === "fileEditor") {
+ await fileActions.clearAllFiles();
+ } else if (currentView === "viewer") {
+ const file =
+ (activeFileId
+ ? activeFiles.find(
+ (f) => isStirlingFile(f) && f.fileId === activeFileId,
+ )
+ : null) ?? activeFiles[0];
+ const countBeforeRemove = activeFiles.length;
+ if (file && isStirlingFile(file)) {
+ // Pick the next file to show before removing, so the sidebar stays in sync.
+ const remaining = activeFiles.filter(
+ (f) => isStirlingFile(f) && f.fileId !== file.fileId,
+ );
+ const nextFile = remaining.find(isStirlingFile) ?? null;
+ await fileActions.removeFiles([file.fileId], false);
+ if (countBeforeRemove <= 1) {
+ setCurrentView("fileEditor");
+ } else if (nextFile) {
+ setActiveFileId(nextFile.fileId);
+ }
+ } else if (countBeforeRemove <= 1) {
+ setCurrentView("fileEditor");
+ }
+ } else if (currentView === "pageEditor") {
+ pageEditorFunctions?.closePdf?.();
+ }
+ }, [
+ currentView,
+ fileActions,
+ activeFiles,
+ activeFileId,
+ setActiveFileId,
+ pageEditorFunctions,
+ setCurrentView,
+ ]);
+
+ const downloadTooltip = useMemo(() => {
+ if (currentView === "pageEditor")
+ return t("workbenchBar.exportAll", "Export PDF");
+ if (currentView === "viewer") return terminology.download;
+ if (selectedCount > 0) return terminology.downloadSelected;
+ return terminology.downloadAll;
+ }, [currentView, selectedCount, t, terminology]);
+
+ const renderButton = useCallback(
+ (btn: WorkbenchBarButtonConfig) => {
+ const action = actions[btn.id];
+ const disabled = Boolean(
+ btn.disabled || allButtonsDisabled || disableForFullscreen,
+ );
+ const isActive = Boolean(btn.active);
+
+ const triggerAction = () => {
+ if (!disabled) action?.();
+ };
+
+ if (btn.render) {
+ const context: WorkbenchBarRenderContext = {
+ id: btn.id,
+ disabled,
+ allButtonsDisabled,
+ action,
+ triggerAction,
+ active: isActive,
+ };
+ return btn.render(context) ?? null;
+ }
+
+ if (!btn.icon) return null;
+
+ const ariaLabel =
+ btn.ariaLabel ||
+ (typeof btn.tooltip === "string" ? (btn.tooltip as string) : undefined);
+ const buttonNode = (
+ <ActionIcon
+ variant={isActive ? "filled" : "subtle"}
+ color={isActive ? "blue" : undefined}
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={triggerAction}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ aria-pressed={isActive ? true : undefined}
+ >
+ {btn.icon}
+ </ActionIcon>
+ );
+ return renderWithTooltip(buttonNode, btn.tooltip);
+ },
+ [actions, allButtonsDisabled, disableForFullscreen],
+ );
+
+ // View options
+ const viewOptions: ViewOption[] = [
+ {
+ value: "viewer",
+ label: t("workbenchBar.viewer", "Viewer"),
+ icon: <InsertDriveFileIcon fontSize="small" />,
+ },
+ {
+ value: "fileEditor",
+ label: t("workbenchBar.activeFiles", "Active Files"),
+ icon: <FolderIcon fontSize="small" />,
+ },
+ ...(selectedTool === "multiTool"
+ ? [
+ {
+ value: "pageEditor" as WorkbenchType,
+ label: t("workbenchBar.multiTool", "Multi-Tool"),
+ icon: (
+ <LocalIcon
+ icon="dashboard-customize-outline-rounded"
+ width="1rem"
+ height="1rem"
+ />
+ ),
+ },
+ ]
+ : []),
+ ...customWorkbenchViews
+ .filter((v) => v.data != null)
+ .map((v) => ({
+ value: v.workbenchId,
+ label: v.label,
+ icon: v.icon ?? <InsertDriveFileIcon fontSize="small" />,
+ })),
+ ];
+
+ const barRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const bar = barRef.current;
+ if (!bar) return;
+
+ const measure = () => {
+ const viewsEl = bar.querySelector<HTMLElement>(".workbench-bar-views");
+ const globalsEl = bar.querySelector<HTMLElement>(
+ ".workbench-bar-globals",
+ );
+ const centerEl = bar.querySelector<HTMLElement>(".workbench-bar-center");
+
+ const viewsWidth = viewsEl?.offsetWidth ?? 0;
+ const globalsWidth = globalsEl?.offsetWidth ?? 0;
+ const centerChildren = centerEl
+ ? (Array.from(centerEl.children) as HTMLElement[])
+ : [];
+ const centerWidth =
+ centerChildren.reduce((sum, el) => sum + el.offsetWidth, 0) +
+ Math.max(0, centerChildren.length - 1) * 2; // gap: 2px
+
+ const needed = viewsWidth + centerWidth + globalsWidth + 24; // 24px bar padding
+ bar.dataset.wrapped = String(needed > bar.clientWidth);
+ };
+
+ const ro = new ResizeObserver(measure);
+ ro.observe(bar);
+ measure();
+ return () => ro.disconnect();
+ }, []);
+
+ return (
+ <div
+ ref={barRef}
+ className="workbench-bar"
+ data-wrapped="true"
+ data-tour="workbench-bar"
+ >
+ {/* Left: View switcher */}
+ <div className="workbench-bar-views" data-tour="view-switcher">
+ {hasFiles &&
+ viewOptions.map((opt) => (
+ <button
+ key={opt.value}
+ className={`workbench-bar-view-btn${currentView === opt.value ? " active" : ""}`}
+ onClick={() => setCurrentView(opt.value)}
+ aria-pressed={currentView === opt.value}
+ type="button"
+ >
+ {opt.icon}
+ <span className="workbench-bar-view-label">{opt.label}</span>
+ </button>
+ ))}
+ </div>
+
+ {/* Tool buttons — second row, only rendered when buttons exist */}
+ {sectionsWithButtons.length > 0 && (
+ <div className="workbench-bar-center">
+ {sectionsWithButtons.map(
+ ({ section, buttons: sectionButtons }, idx) => (
+ <React.Fragment key={section}>
+ {idx > 0 && <div className="workbench-bar-divider" />}
+ {sectionButtons.map((btn) => {
+ const content = renderButton(btn);
+ if (!content) return null;
+ return (
+ <div key={btn.id} className="workbench-bar-action-wrapper">
+ {content}
+ </div>
+ );
+ })}
+ </React.Fragment>
+ ),
+ )}
+ </div>
+ )}
+
+ {/* Right: Global buttons — export group left, close anchored right */}
+ <div className="workbench-bar-globals">
+ {/* Print */}
+ {currentView === "viewer" &&
+ renderWithTooltip(
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={handlePrint}
+ disabled={
+ totalItems === 0 || allButtonsDisabled || disableForFullscreen
+ }
+ aria-label={t("workbenchBar.print", "Print PDF")}
+ >
+ <PrintIcon sx={{ fontSize: "1rem" }} />
+ </ActionIcon>,
+ t("workbenchBar.print", "Print PDF"),
+ )}
+
+ {/* Download */}
+ {renderWithTooltip(
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={() => handleExportAll()}
+ disabled={
+ disableForFullscreen || totalItems === 0 || allButtonsDisabled
+ }
+ >
+ <LocalIcon
+ icon={icons.downloadIconName}
+ width="1rem"
+ height="1rem"
+ />
+ </ActionIcon>,
+ downloadTooltip,
+ )}
+
+ {/* Save As */}
+ {icons.saveAsIconName &&
+ renderWithTooltip(
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={() => handleExportAll(true)}
+ disabled={
+ disableForFullscreen || totalItems === 0 || allButtonsDisabled
+ }
+ >
+ <LocalIcon
+ icon={icons.saveAsIconName}
+ width="1rem"
+ height="1rem"
+ />
+ </ActionIcon>,
+ t("workbenchBar.saveAs", "Save As"),
+ )}
+
+ {/* Separator: export group | close */}
+ {!isCustomView && (
+ <div className="workbench-bar-divider workbench-bar-globals-sep" />
+ )}
+
+ {/* Close (context-aware: close all / close viewer file / close page editor) */}
+ {!isCustomView &&
+ renderWithTooltip(
+ <ActionIcon
+ variant="subtle"
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={handleClose}
+ disabled={
+ totalItems === 0 || allButtonsDisabled || disableForFullscreen
+ }
+ aria-label={
+ currentView === "fileEditor"
+ ? t("workbenchBar.closeAll", "Close All")
+ : t("workbenchBar.closePdf", "Close PDF")
+ }
+ >
+ <CloseIcon sx={{ fontSize: "1rem" }} />
+ </ActionIcon>,
+ currentView === "fileEditor"
+ ? t("workbenchBar.closeAll", "Close All")
+ : t("workbenchBar.closePdf", "Close PDF"),
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/core/components/shared/config/configNavSections.tsx b/frontend/src/core/components/shared/config/configNavSections.tsx
index d9b9f56d83..68ed7285dd 100644
--- a/frontend/src/core/components/shared/config/configNavSections.tsx
+++ b/frontend/src/core/components/shared/config/configNavSections.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { NavKey } from "@app/components/shared/config/types";
import HotkeysSection from "@app/components/shared/config/configSections/HotkeysSection";
import GeneralSection from "@app/components/shared/config/configSections/GeneralSection";
+import HelpSection from "@app/components/shared/config/configSections/HelpSection";
export interface ConfigNavItem {
key: NavKey;
@@ -34,6 +35,7 @@ export const useConfigNavSections = (
_isAdmin: boolean = false,
_runningEE: boolean = false,
_loginEnabled: boolean = false,
+ onRequestClose: () => void = () => {},
): ConfigNavSection[] => {
const { t } = useTranslation();
@@ -55,6 +57,19 @@ export const useConfigNavSections = (
},
],
},
+ {
+ title: t("settings.help.title", "Help"),
+ items: [
+ {
+ key: "help",
+ label: t("settings.help.label", "Tours"),
+ icon: "help-rounded",
+ component: (
+ <HelpSection isAdmin={_isAdmin} onRequestClose={onRequestClose} />
+ ),
+ },
+ ],
+ },
];
return sections;
diff --git a/frontend/src/core/components/shared/config/configSections/GeneralSection.tsx b/frontend/src/core/components/shared/config/configSections/GeneralSection.tsx
index 34d7fcbe56..f1bfdbdca2 100644
--- a/frontend/src/core/components/shared/config/configSections/GeneralSection.tsx
+++ b/frontend/src/core/components/shared/config/configSections/GeneralSection.tsx
@@ -19,6 +19,8 @@ import {
import { useTranslation } from "react-i18next";
import { usePreferences } from "@app/contexts/PreferencesContext";
import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
+import LanguageSelector from "@app/components/shared/LanguageSelector";
import type { ToolPanelMode } from "@app/constants/toolPanel";
import type {
StartupView,
@@ -47,6 +49,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
const { t } = useTranslation();
const { preferences, updatePreference } = usePreferences();
const { config } = useAppConfig();
+ const { toggleTheme, themeMode } = useRainbowThemeContext();
const [fileLimitInput, setFileLimitInput] = useState<number | string>(
preferences.autoUnzipFileLimit,
);
@@ -355,6 +358,67 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
</Paper>
)}
+ {/* Appearance */}
+ <Paper withBorder p="md" radius="md">
+ <Stack gap="md">
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ }}
+ >
+ <div>
+ <Text fw={500} size="sm">
+ {t("settings.general.theme", "Theme")}
+ </Text>
+ <Text size="xs" c="dimmed" mt={4}>
+ {t(
+ "settings.general.themeDescription",
+ "Switch between light and dark mode",
+ )}
+ </Text>
+ </div>
+ <SegmentedControl
+ value={themeMode === "rainbow" ? "dark" : themeMode}
+ onChange={(val) => {
+ if ((themeMode === "dark") !== (val === "dark")) toggleTheme();
+ }}
+ data={[
+ {
+ label: t("settings.general.themeLight", "Light"),
+ value: "light",
+ },
+ {
+ label: t("settings.general.themeDark", "Dark"),
+ value: "dark",
+ },
+ ]}
+ />
+ </div>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ }}
+ >
+ <div>
+ <Text fw={500} size="sm">
+ {t("settings.general.language", "Language")}
+ </Text>
+ <Text size="xs" c="dimmed" mt={4}>
+ {t(
+ "settings.general.languageDescription",
+ "Choose the display language",
+ )}
+ </Text>
+ </div>
+ <LanguageSelector position="bottom-end" offset={6} />
+ </div>
+ </Stack>
+ </Paper>
+
<Paper withBorder p="md" radius="md">
<Stack gap="md">
<div
@@ -412,7 +476,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
<Text size="xs" c="dimmed" mt={4}>
{t(
"settings.general.defaultStartupViewDescription",
- "Choose which tab is active in the left column when the app starts",
+ "Choose which view is active when the app starts",
)}
</Text>
</div>
diff --git a/frontend/src/core/components/shared/config/configSections/HelpSection.tsx b/frontend/src/core/components/shared/config/configSections/HelpSection.tsx
new file mode 100644
index 0000000000..89299fe3d0
--- /dev/null
+++ b/frontend/src/core/components/shared/config/configSections/HelpSection.tsx
@@ -0,0 +1,86 @@
+import React from "react";
+import { Button, Group, Paper, Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import LocalIcon from "@app/components/shared/LocalIcon";
+import { requestStartTour } from "@app/constants/events";
+
+interface HelpSectionProps {
+ isAdmin: boolean;
+ onRequestClose: () => void;
+}
+
+const HelpSection: React.FC<HelpSectionProps> = ({
+ isAdmin,
+ onRequestClose,
+}) => {
+ const { t } = useTranslation();
+
+ const startTour = (tourType: "tools" | "admin") => {
+ onRequestClose();
+ setTimeout(() => requestStartTour(tourType), 300);
+ };
+
+ return (
+ <Stack gap="lg">
+ <Paper withBorder p="md" radius="md">
+ <Stack gap="md">
+ <Group justify="space-between" align="center">
+ <div>
+ <Text fw={600} size="sm">
+ {t("settings.help.toolsTour.title", "Tools Tour")}
+ </Text>
+ <Text size="xs" c="dimmed" mt={4}>
+ {t(
+ "settings.help.toolsTour.description",
+ "Walk through uploading files, picking a tool, and reviewing results.",
+ )}
+ </Text>
+ </div>
+ <Button
+ variant="default"
+ size="sm"
+ leftSection={
+ <LocalIcon
+ icon="build-outline-rounded"
+ width="1rem"
+ height="1rem"
+ />
+ }
+ onClick={() => startTour("tools")}
+ >
+ {t("settings.help.toolsTour.start", "Start")}
+ </Button>
+ </Group>
+
+ {isAdmin && (
+ <Group justify="space-between" align="center">
+ <div>
+ <Text fw={600} size="sm">
+ {t("settings.help.adminTour.title", "Admin Tour")}
+ </Text>
+ <Text size="xs" c="dimmed" mt={4}>
+ {t(
+ "settings.help.adminTour.description",
+ "Explore team management, system settings, and enterprise features.",
+ )}
+ </Text>
+ </div>
+ <Button
+ variant="default"
+ size="sm"
+ leftSection={
+ <LocalIcon icon="person-rounded" width="1rem" height="1rem" />
+ }
+ onClick={() => startTour("admin")}
+ >
+ {t("settings.help.adminTour.start", "Start")}
+ </Button>
+ </Group>
+ )}
+ </Stack>
+ </Paper>
+ </Stack>
+ );
+};
+
+export default HelpSection;
diff --git a/frontend/src/core/components/shared/config/types.ts b/frontend/src/core/components/shared/config/types.ts
index 6a22ed3112..110c7801ee 100644
--- a/frontend/src/core/components/shared/config/types.ts
+++ b/frontend/src/core/components/shared/config/types.ts
@@ -30,6 +30,7 @@ export const VALID_NAV_KEYS = [
"adminUsage",
"adminEndpoints",
"adminStorageSharing",
+ "help",
] as const;
// Derive the type from the array
diff --git a/frontend/src/core/components/shared/filePreview/DocumentThumbnail.tsx b/frontend/src/core/components/shared/filePreview/DocumentThumbnail.tsx
index e0b61d6a40..9b5ce16eaf 100644
--- a/frontend/src/core/components/shared/filePreview/DocumentThumbnail.tsx
+++ b/frontend/src/core/components/shared/filePreview/DocumentThumbnail.tsx
@@ -1,12 +1,19 @@
import React from "react";
-import { Box, Center, Image } from "@mantine/core";
+import { Box, Center, Loader, Stack, Text } from "@mantine/core";
+import LockIcon from "@mui/icons-material/Lock";
import { getFileTypeIcon } from "@app/components/shared/filePreview/getFileTypeIcon";
import { StirlingFileStub } from "@app/types/fileContext";
import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { detectFileExtension } from "@app/utils/fileUtils";
export interface DocumentThumbnailProps {
file: File | StirlingFileStub | null;
thumbnail?: string | null;
+ isEncrypted?: boolean;
+ isLoading?: boolean;
+ iconSize?: string | number;
+ imgClassName?: string;
+ onImageError?: React.ReactEventHandler<HTMLImageElement>;
style?: React.CSSProperties;
onClick?: () => void;
children?: React.ReactNode;
@@ -15,14 +22,19 @@ export interface DocumentThumbnailProps {
const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
file,
thumbnail,
+ isEncrypted = false,
+ isLoading = false,
+ iconSize = "4rem",
+ imgClassName,
+ onImageError,
style = {},
onClick,
children,
}) => {
if (!file) return null;
- const containerStyle = {
- position: "relative" as const,
+ const containerStyle: React.CSSProperties = {
+ position: "relative",
cursor: onClick ? "pointer" : "default",
transition: "opacity 0.2s ease",
width: "100%",
@@ -33,20 +45,29 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
...style,
};
- if (thumbnail) {
+ if (thumbnail && !isEncrypted) {
return (
<Box style={containerStyle} onClick={onClick}>
<PrivateContent>
- <Image
+ <img
src={thumbnail}
alt={`Preview of ${file.name}`}
- fit="contain"
- style={{
- maxWidth: "100%",
- maxHeight: "100%",
- width: "auto",
- height: "auto",
- }}
+ className={imgClassName}
+ style={
+ imgClassName
+ ? undefined
+ : {
+ maxWidth: "100%",
+ maxHeight: "100%",
+ width: "auto",
+ height: "auto",
+ objectFit: "contain",
+ }
+ }
+ draggable={false}
+ loading="lazy"
+ decoding="async"
+ onError={onImageError}
/>
</PrivateContent>
{children}
@@ -54,17 +75,93 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
);
}
+ if (isEncrypted) {
+ return (
+ <Box style={containerStyle} onClick={onClick}>
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ width: "calc(100% - 8px)",
+ height: "calc(100% - 8px)",
+ gap: "0.5rem",
+ border: "2px dashed var(--mantine-color-red-5)",
+ borderRadius: "10px",
+ }}
+ >
+ <LockIcon
+ style={{ fontSize: iconSize, color: "var(--mantine-color-red-6)" }}
+ />
+ <span
+ style={{
+ fontSize: "0.65rem",
+ fontWeight: 700,
+ letterSpacing: "0.08em",
+ textTransform: "uppercase",
+ color: "var(--mantine-color-red-6)",
+ background: "rgba(220,38,38,0.1)",
+ padding: "2px 8px",
+ borderRadius: "6px",
+ }}
+ >
+ Locked
+ </span>
+ </div>
+ {children}
+ </Box>
+ );
+ }
+
+ if (isLoading) {
+ return (
+ <Box style={containerStyle} onClick={onClick}>
+ <Stack
+ align="center"
+ justify="center"
+ gap="xs"
+ style={{ height: "100%" }}
+ >
+ <Loader size="sm" />
+ <Text size="xs" c="dimmed">
+ Loading thumbnail...
+ </Text>
+ </Stack>
+ {children}
+ </Box>
+ );
+ }
+
+ const ext = detectFileExtension(file.name ?? "").toUpperCase();
+
return (
<Box style={containerStyle} onClick={onClick}>
<Center
style={{
width: "100%",
height: "100%",
- backgroundColor: "var(--mantine-color-gray-1)",
- borderRadius: "0.25rem",
+ flexDirection: "column",
+ gap: "0.75rem",
}}
>
- <PrivateContent>{getFileTypeIcon(file)}</PrivateContent>
+ <PrivateContent>{getFileTypeIcon(file, iconSize)}</PrivateContent>
+ {ext && (
+ <span
+ style={{
+ fontSize: "0.7rem",
+ fontWeight: 700,
+ letterSpacing: "0.1em",
+ textTransform: "uppercase",
+ color: "var(--text-secondary)",
+ background: "rgb(var(--border))",
+ padding: "3px 10px",
+ borderRadius: "6px",
+ }}
+ >
+ {ext}
+ </span>
+ )}
</Center>
{children}
</Box>
diff --git a/frontend/src/core/components/shared/filePreview/getFileTypeIcon.tsx b/frontend/src/core/components/shared/filePreview/getFileTypeIcon.tsx
index 2666f06606..6be3d35163 100644
--- a/frontend/src/core/components/shared/filePreview/getFileTypeIcon.tsx
+++ b/frontend/src/core/components/shared/filePreview/getFileTypeIcon.tsx
@@ -1,17 +1,84 @@
import React from "react";
-import JavascriptIcon from "@mui/icons-material/Javascript";
-import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
-import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
+import { FileDocIcon } from "@app/components/shared/FileDocIcon";
+import type { FileDocVariant } from "@app/components/shared/FileDocIcon";
import type { StirlingFileStub } from "@app/types/fileContext";
import { detectFileExtension } from "@app/utils/fileUtils";
+export const SPREADSHEET_EXTS = new Set(["csv", "xls", "xlsx", "ods"]);
+export const DOC_EXTS = new Set([
+ "md",
+ "markdown",
+ "txt",
+ "doc",
+ "docx",
+ "odt",
+ "rtf",
+]);
+export const IMAGE_EXTS = new Set([
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "webp",
+ "svg",
+ "bmp",
+ "tiff",
+ "tif",
+]);
+export const ARCHIVE_EXTS = new Set([
+ "zip",
+ "tar",
+ "gz",
+ "rar",
+ "7z",
+ "cbz",
+ "cbr",
+]);
+export const CODE_EXTS = new Set([
+ "js",
+ "ts",
+ "jsx",
+ "tsx",
+ "html",
+ "css",
+ "json",
+ "xml",
+ "yaml",
+ "yml",
+]);
+
type FileLike = File | StirlingFileStub;
-/**
- * Returns an appropriate file type icon for the provided file.
- * - Uses the real file type and extension to decide the icon.
- * - No any-casts; accepts File or StirlingFileStub.
- */
+export function getFileDocVariant(ext: string, mime = ""): FileDocVariant {
+ if (ext === "pdf" || mime === "application/pdf") return "pdf";
+ if (
+ SPREADSHEET_EXTS.has(ext) ||
+ mime.includes("spreadsheet") ||
+ mime === "text/csv"
+ )
+ return "spreadsheet";
+ if (
+ DOC_EXTS.has(ext) ||
+ mime === "text/markdown" ||
+ mime === "text/plain" ||
+ mime.includes("word") ||
+ mime.includes("opendocument.text")
+ )
+ return "doc";
+ if (IMAGE_EXTS.has(ext) || mime.startsWith("image/")) return "image";
+ if (ARCHIVE_EXTS.has(ext) || mime.includes("zip") || mime.includes("archive"))
+ return "archive";
+ if (
+ CODE_EXTS.has(ext) ||
+ mime.includes("javascript") ||
+ mime.includes("json") ||
+ mime.includes("xml") ||
+ mime === "text/html"
+ )
+ return "code";
+ return "generic";
+}
+
export function getFileTypeIcon(
file: FileLike,
size: number | string = "2rem",
@@ -19,29 +86,10 @@ export function getFileTypeIcon(
const name = (file?.name ?? "").toLowerCase();
const mime = (file?.type ?? "").toLowerCase();
const ext = detectFileExtension(name);
-
- // JavaScript
- if (ext === "js" || mime.includes("javascript")) {
- return (
- <JavascriptIcon
- style={{ fontSize: size, color: "var(--mantine-color-gray-6)" }}
- />
- );
- }
-
- // PDF
- if (ext === "pdf" || mime === "application/pdf") {
- return (
- <PictureAsPdfIcon
- style={{ fontSize: size, color: "var(--mantine-color-gray-6)" }}
- />
- );
- }
-
- // Fallback generic
return (
- <InsertDriveFileIcon
- style={{ fontSize: size, color: "var(--mantine-color-gray-6)" }}
+ <FileDocIcon
+ variant={getFileDocVariant(ext, mime)}
+ style={{ width: size, height: "auto" }}
/>
);
}
diff --git a/frontend/src/core/components/shared/rightRail/RightRail.README.md b/frontend/src/core/components/shared/rightRail/RightRail.README.md
deleted file mode 100644
index 1c804daaab..0000000000
--- a/frontend/src/core/components/shared/rightRail/RightRail.README.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# RightRail Component
-
-A dynamic vertical toolbar on the right side of the application that supports both static buttons (Undo/Redo, Save, Print, Share) and dynamic buttons registered by tools.
-
-## Structure
-
-- **Top Section**: Dynamic buttons from tools (empty when none)
-- **Middle Section**: Grid, Cut, Undo, Redo
-- **Bottom Section**: Save, Print, Share
-
-## Usage
-
-### For Tools (Recommended)
-
-```tsx
-import { useRightRailButtons } from '../hooks/useRightRailButtons';
-import PlayArrowIcon from '@mui/icons-material/PlayArrow';
-
-function MyTool() {
- const handleAction = useCallback(() => {
- // Your action here
- }, []);
-
- useRightRailButtons([
- {
- id: 'my-action',
- icon: <PlayArrowIcon />,
- tooltip: 'Execute Action',
- onClick: handleAction,
- },
- ]);
-
- return <div>My Tool</div>;
-}
-```
-
-### Multiple Buttons
-
-```tsx
-useRightRailButtons([
- {
- id: 'primary',
- icon: <StarIcon />,
- tooltip: 'Primary Action',
- order: 1,
- onClick: handlePrimary,
- },
- {
- id: 'secondary',
- icon: <SettingsIcon />,
- tooltip: 'Secondary Action',
- order: 2,
- onClick: handleSecondary,
- },
-]);
-```
-
-### Conditional Buttons
-
-```tsx
-useRightRailButtons([
- // Always show
- {
- id: 'process',
- icon: <PlayArrowIcon />,
- tooltip: 'Process',
- disabled: isProcessing,
- onClick: handleProcess,
- },
- // Only show when condition met
- ...(hasResults ? [{
- id: 'export',
- icon: <DownloadIcon />,
- tooltip: 'Export',
- onClick: handleExport,
- }] : []),
-]);
-```
-
-## API
-
-### Button Config
-
-```typescript
-interface RightRailButtonWithAction {
- id: string; // Unique identifier
- icon?: React.ReactNode; // Icon component (omit when using render)
- tooltip?: React.ReactNode; // Hover tooltip / description
- active?: boolean; // Optional active state for highlight
- section?: 'top' | 'middle' | 'bottom'; // Section (default: 'top')
- order?: number; // Sort order (default: 0)
- disabled?: boolean; // Disabled state (default: false)
- visible?: boolean; // Visibility (default: true)
- render?: (ctx: RightRailRenderContext) => React.ReactNode; // Custom renderer
- onClick?: () => void; // Click handler (optional if using render)
-}
-
-interface RightRailRenderContext {
- id: string;
- disabled: boolean;
- allButtonsDisabled: boolean;
- action?: () => void;
- triggerAction: () => void;
- active: boolean;
-}
-```
-
-### Custom Rendering (Popovers, Multi-button Blocks)
-
-```tsx
-useRightRailButtons([
- {
- id: 'viewer-search',
- tooltip: t('rightRail.search', 'Search PDF'),
- render: ({ disabled }) => (
- <Tooltip content={t('rightRail.search', 'Search PDF')}>
- <Popover position="left">
- <Popover.Target>
- <ActionIcon disabled={disabled}>
- <SearchIcon />
- </ActionIcon>
- </Popover.Target>
- <Popover.Dropdown>
- <SearchInterface />
- </Popover.Dropdown>
- </Popover>
- </Tooltip>
- ),
- },
-]);
-```
-
-## Built-in Features
-
-- **Undo/Redo**: Automatically integrates with Page Editor
-- **Theme Support**: Light/dark mode with CSS variables
-- **Auto Cleanup**: Buttons unregister when tool unmounts
-
-## Best Practices
-
-- Use descriptive IDs: `'compress-optimize'`, `'ocr-process'`
-- Choose appropriate Material-UI icons
-- Keep tooltips concise: `'Compress PDF'`, `'Process with OCR'`
-- Use `useCallback` for click handlers to prevent re-registration
-- Reach for `render` when you need popovers or multi-control groups inside the rail
diff --git a/frontend/src/core/components/shared/rightRail/RightRail.css b/frontend/src/core/components/shared/rightRail/RightRail.css
deleted file mode 100644
index f8fd76b35d..0000000000
--- a/frontend/src/core/components/shared/rightRail/RightRail.css
+++ /dev/null
@@ -1,170 +0,0 @@
-.right-rail {
- background-color: var(--right-rail-bg);
- width: 3.5rem;
- min-width: 3.5rem;
- max-width: 3.5rem;
- position: relative;
- z-index: 10;
- display: flex;
- flex-direction: column;
- height: 100vh;
- border-left: 1px solid var(--border-subtle);
-}
-
-.right-rail-inner {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.75rem;
- padding: 1rem 0.5rem;
- width: 100%;
- height: 100%;
- flex: 1;
-}
-
-.right-rail-section {
- background-color: var(--right-rail-foreground);
- border-radius: 12px;
- padding: 0.5rem;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.75rem;
-}
-
-.right-rail-button-wrapper {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.75rem;
- width: 100%;
- animation: rightRailButtonReveal 200ms ease forwards;
- transform-origin: top center;
- opacity: 0;
-}
-
-.right-rail-tooltip-wrapper {
- display: inline-flex;
- width: 100%;
- justify-content: center;
-}
-
-@keyframes rightRailButtonReveal {
- 0% {
- opacity: 0;
- transform: scaleY(0.6) translateY(-6px);
- }
- 100% {
- opacity: 1;
- transform: scaleY(1) translateY(0);
- }
-}
-
-.right-rail-divider {
- width: 2.75rem;
- border: none;
- border-top: 1px solid var(--tool-subcategory-rule-color);
- margin: 0.25rem 0;
-}
-
-.right-rail-icon {
- color: var(--right-rail-icon);
-}
-
-.right-rail-icon[data-active="true"] {
- color: #fff;
-}
-
-.right-rail-icon[aria-disabled="true"],
-.right-rail-icon[disabled] {
- color: var(--right-rail-icon-disabled) !important;
- background-color: transparent !important;
-}
-
-/* When all buttons are disabled via context */
-.right-rail--all-disabled .right-rail-icon {
- color: var(--right-rail-icon-disabled) !important;
- background-color: transparent !important;
- pointer-events: none !important;
-}
-
-.right-rail-spacer {
- flex: 1;
-}
-
-/* Animated grow-down slot for buttons (mirrors current-tool-slot behavior) */
-.right-rail-slot {
- overflow: hidden;
- max-height: 0;
- opacity: 0;
- transition:
- max-height 450ms ease-out,
- opacity 300ms ease-out;
-}
-
-.right-rail-enter {
- animation: rightRailGrowDown 450ms ease-out;
-}
-
-.right-rail-exit {
- animation: rightRailShrinkUp 450ms ease-out;
-}
-
-.right-rail-slot.visible {
- max-height: 40rem; /* increased to fit additional controls + divider */
- opacity: 1;
-}
-
-@keyframes rightRailGrowDown {
- 0% {
- max-height: 0;
- opacity: 0;
- }
- 100% {
- max-height: 40rem;
- opacity: 1;
- }
-}
-
-@keyframes rightRailShrinkUp {
- 0% {
- max-height: 40rem;
- opacity: 1;
- }
- 100% {
- max-height: 0;
- opacity: 0;
- }
-}
-
-/* Remove bottom margin from close icon */
-.right-rail-slot .right-rail-icon {
- margin-bottom: 0;
-}
-
-/* Inline appear/disappear animation for page-number selector button */
-.right-rail-fade {
- transition-property: opacity, transform, max-height, visibility;
- transition-duration: 220ms, 220ms, 220ms, 0s;
- transition-timing-function: ease, ease, ease, linear;
- transition-delay: 0s, 0s, 0s, 0s;
- transform-origin: top center;
- overflow: hidden;
-}
-
-.right-rail-fade.enter {
- opacity: 1;
- transform: scale(1);
- max-height: 3rem;
- visibility: visible;
-}
-
-.right-rail-fade.exit {
- opacity: 0;
- transform: scale(0.85);
- max-height: 0;
- visibility: hidden;
- /* delay visibility change so opacity/max-height can finish */
- transition-delay: 0s, 0s, 0s, 220ms;
- pointer-events: none;
-}
diff --git a/frontend/src/core/components/shared/signing/CreateSessionPanel.tsx b/frontend/src/core/components/shared/signing/CreateSessionPanel.tsx
index 671de36b72..dfbb1c0f74 100644
--- a/frontend/src/core/components/shared/signing/CreateSessionPanel.tsx
+++ b/frontend/src/core/components/shared/signing/CreateSessionPanel.tsx
@@ -43,11 +43,11 @@ const CreateSessionPanel = ({
<>
<div className="quick-access-popout__section">
<div className="quick-access-popout__label">
- {t("quickAccess.selectedFile", "Selected file")}
+ {t("quickAccess.selectedFile", "File")}
</div>
<div className="quick-access-popout__row-title">
{selectedFiles[0]?.name ||
- t("quickAccess.noFile", "No file selected")}
+ t("quickAccess.noFile", "No file loaded")}
</div>
</div>
diff --git a/frontend/src/core/components/shared/textInput/TextInput.module.css b/frontend/src/core/components/shared/textInput/TextInput.module.css
index 7ccf300635..72fa8abb7b 100644
--- a/frontend/src/core/components/shared/textInput/TextInput.module.css
+++ b/frontend/src/core/components/shared/textInput/TextInput.module.css
@@ -15,6 +15,7 @@
display: flex;
align-items: center;
justify-content: center;
+ color: var(--search-text-and-icon-color);
}
.input {
@@ -26,6 +27,8 @@
outline: none;
box-shadow: none;
transition: box-shadow 0.2s ease;
+ background-color: var(--input-bg);
+ color: var(--search-text-and-icon-color);
}
.input::placeholder {
@@ -62,6 +65,7 @@
justify-content: center;
font-size: 16px;
transition: background-color 0.2s ease;
+ color: var(--search-text-and-icon-color);
}
.clearButton:hover {
diff --git a/frontend/src/core/components/tools/FullscreenToolSurface.tsx b/frontend/src/core/components/tools/FullscreenToolSurface.tsx
index 99683f3923..264f00c35c 100644
--- a/frontend/src/core/components/tools/FullscreenToolSurface.tsx
+++ b/frontend/src/core/components/tools/FullscreenToolSurface.tsx
@@ -1,6 +1,5 @@
-import { useState, useRef } from "react";
-import { ActionIcon, ScrollArea, Switch } from "@mantine/core";
-import DoubleArrowIcon from "@mui/icons-material/DoubleArrow";
+import { useRef } from "react";
+import { ScrollArea, Switch } from "@mantine/core";
import { useTranslation } from "react-i18next";
import ToolSearch from "@app/components/tools/toolPicker/ToolSearch";
import FullscreenToolList from "@app/components/tools/FullscreenToolList";
@@ -9,10 +8,8 @@ import { ToolId } from "@app/types/toolId";
import { useFocusTrap } from "@app/hooks/useFocusTrap";
import { LogoIcon } from "@app/components/shared/LogoIcon";
import { Wordmark } from "@app/components/shared/Wordmark";
-import { Tooltip } from "@app/components/shared/Tooltip";
import "@app/components/tools/ToolPanel.css";
import { ToolPanelGeometry } from "@app/hooks/tools/useToolPanelGeometry";
-import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
interface FullscreenToolSurfaceProps {
searchQuery: string;
@@ -28,7 +25,6 @@ interface FullscreenToolSurfaceProps {
onSelect: (id: ToolId) => void;
onToggleDescriptions: () => void;
onExitFullscreenMode: () => void;
- toggleLabel: string;
geometry: ToolPanelGeometry | null;
}
@@ -42,47 +38,17 @@ const FullscreenToolSurface = ({
onSearchChange,
onSelect,
onToggleDescriptions,
- onExitFullscreenMode,
- toggleLabel,
+ onExitFullscreenMode: _onExitFullscreenMode,
geometry,
}: FullscreenToolSurfaceProps) => {
const { t } = useTranslation();
- const [isExiting, setIsExiting] = useState(false);
const surfaceRef = useRef<HTMLDivElement>(null);
- const isRTL =
- typeof document !== "undefined" && document.documentElement.dir === "rtl";
// Enable focus trap when surface is active
- useFocusTrap(surfaceRef, !isExiting);
+ useFocusTrap(surfaceRef, true);
const brandAltText = t("home.mobile.brandAlt", "Stirling PDF logo");
- const handleExit = () => {
- const prefersReducedMotion = window.matchMedia(
- "(prefers-reduced-motion: reduce)",
- ).matches;
-
- if (prefersReducedMotion) {
- onExitFullscreenMode();
- return;
- }
-
- setIsExiting(true);
- const el = surfaceRef.current;
- if (!el) {
- onExitFullscreenMode();
- return;
- }
- // Rely on CSS animation end rather than duplicating timing in JS
- el.addEventListener(
- "animationend",
- () => {
- onExitFullscreenMode();
- },
- { once: true },
- );
- };
-
const style = geometry
? {
left: `${geometry.left}px`,
@@ -103,10 +69,7 @@ const FullscreenToolSurface = ({
)}
data-tour="tool-panel"
>
- <div
- ref={surfaceRef}
- className={`tool-panel__fullscreen-surface-inner ${isExiting ? "tool-panel__fullscreen-surface-inner--exiting" : ""}`}
- >
+ <div ref={surfaceRef} className="tool-panel__fullscreen-surface-inner">
<header className="tool-panel__fullscreen-header">
<div className="tool-panel__fullscreen-brand">
<LogoIcon className="tool-panel__fullscreen-brand-icon" />
@@ -115,29 +78,6 @@ const FullscreenToolSurface = ({
className="tool-panel__fullscreen-brand-text"
/>
</div>
- <div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
- <Tooltip
- content={toggleLabel}
- position="bottom"
- arrow={true}
- openOnFocus={false}
- containerStyle={{ zIndex: Z_INDEX_OVER_FULLSCREEN_SURFACE }}
- >
- <ActionIcon
- variant="subtle"
- radius="xl"
- size="md"
- onClick={handleExit}
- aria-label={toggleLabel}
- style={{ color: "var(--right-rail-icon)" }}
- >
- <DoubleArrowIcon
- fontSize="small"
- style={{ transform: isRTL ? undefined : "rotate(180deg)" }}
- />
- </ActionIcon>
- </Tooltip>
- </div>
</header>
<div className="tool-panel__fullscreen-controls">
diff --git a/frontend/src/core/components/tools/ToolPanel.css b/frontend/src/core/components/tools/ToolPanel.css
index dd5c3c15e1..0e52f93abd 100644
--- a/frontend/src/core/components/tools/ToolPanel.css
+++ b/frontend/src/core/components/tools/ToolPanel.css
@@ -1,3 +1,14 @@
+/* ---- Viewer mode mini-toolbar (top of ToolPanel) ---- */
+.tool-panel-viewer-bar {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 4px 8px;
+ border-bottom: 1px solid var(--border-subtle);
+ background-color: var(--bg-toolbar);
+ flex-shrink: 0;
+}
+
/* CSS Custom Properties for Fullscreen Mode */
.tool-panel__fullscreen-surface-inner {
--fullscreen-bg-surface-1: color-mix(
@@ -109,16 +120,8 @@
var(--text-primary) 20%,
var(--border-subtle)
);
- --fullscreen-text-icon: color-mix(
- in srgb,
- var(--text-primary) 90%,
- var(--text-muted)
- );
- --fullscreen-text-icon-compact: color-mix(
- in srgb,
- var(--text-primary) 88%,
- var(--text-muted)
- );
+ --fullscreen-text-icon: var(--text-primary);
+ --fullscreen-text-icon-compact: var(--text-primary);
}
.tool-panel {
@@ -128,6 +131,49 @@
max-width 0.3s ease;
}
+.tool-panel__collapsed-strip {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: flex-start;
+ padding-top: 10px;
+ gap: 8px;
+ height: 100%;
+ width: 100%;
+}
+
+.tool-panel__expand-btn {
+ flex-shrink: 0;
+ color: var(--text-secondary) !important;
+ border-color: var(--border-subtle) !important;
+}
+
+.tool-panel__expand-btn svg {
+ color: var(--text-secondary) !important;
+}
+
+.tool-panel__expand-btn:hover {
+ color: var(--text-primary) !important;
+ border-color: var(--border) !important;
+}
+
+.tool-panel__collapsed-search-btn {
+ flex-shrink: 0;
+ color: var(--text-secondary) !important;
+}
+
+.tool-panel__collapsed-search-btn svg {
+ color: var(--text-secondary) !important;
+}
+
+.tool-panel__collapsed-search-btn:hover {
+ color: var(--text-primary) !important;
+}
+
+.tool-panel__back-btn {
+ flex-shrink: 0;
+}
+
.tool-panel--fullscreen-active {
overflow: visible !important;
}
@@ -136,7 +182,9 @@
display: flex;
align-items: center;
gap: 0.75rem;
- padding: 0.75rem 1rem;
+ height: 48px;
+ padding: 0 0.5rem;
+ box-sizing: border-box;
}
.tool-panel__search-row .search-input-container {
@@ -469,6 +517,8 @@
.tool-panel__fullscreen-name {
color: var(--text-primary);
+ font-size: 13px !important;
+ font-weight: 500 !important;
}
.tool-panel__fullscreen-description {
@@ -604,7 +654,7 @@
@keyframes tool-panel-fullscreen-slide-in {
from {
- transform: translateX(-6%) scaleX(0.85);
+ transform: translateX(6%) scaleX(0.85);
opacity: 0;
}
to {
@@ -619,14 +669,14 @@
opacity: 1;
}
to {
- transform: translateX(-6%) scaleX(0.85);
+ transform: translateX(6%) scaleX(0.85);
opacity: 0;
}
}
@keyframes tool-panel-fullscreen-slide-in-rtl {
from {
- transform: translateX(6%) scaleX(0.85);
+ transform: translateX(-6%) scaleX(0.85);
opacity: 0;
}
to {
@@ -641,7 +691,7 @@
opacity: 1;
}
to {
- transform: translateX(6%) scaleX(0.85);
+ transform: translateX(-6%) scaleX(0.85);
opacity: 0;
}
}
diff --git a/frontend/src/core/components/tools/ToolPanel.tsx b/frontend/src/core/components/tools/ToolPanel.tsx
index 8be8d84c45..ab31a4e8f6 100644
--- a/frontend/src/core/components/tools/ToolPanel.tsx
+++ b/frontend/src/core/components/tools/ToolPanel.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { usePreferences } from "@app/contexts/PreferencesContext";
@@ -8,15 +8,18 @@ import ToolRenderer from "@app/components/tools/ToolRenderer";
import ToolSearch from "@app/components/tools/toolPicker/ToolSearch";
import { useSidebarContext } from "@app/contexts/SidebarContext";
import rainbowStyles from "@app/styles/rainbow.module.css";
-import { ActionIcon, ScrollArea } from "@mantine/core";
+import { ActionIcon, Button, ScrollArea } from "@mantine/core";
import { ToolId } from "@app/types/toolId";
import { useIsMobile } from "@app/hooks/useIsMobile";
-import DoubleArrowIcon from "@mui/icons-material/DoubleArrow";
import { useTranslation } from "react-i18next";
import FullscreenToolSurface from "@app/components/tools/FullscreenToolSurface";
+import { ToolPanelViewerBar } from "@app/components/tools/ToolPanelViewerBar";
import { useToolPanelGeometry } from "@app/hooks/tools/useToolPanelGeometry";
-import { useRightRail } from "@app/contexts/RightRailContext";
-import { Tooltip } from "@app/components/shared/Tooltip";
+import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
+import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import ArrowBackIcon from "@mui/icons-material/ArrowBack";
+import SearchIcon from "@mui/icons-material/Search";
import "@app/components/tools/ToolPanel.css";
// No props needed - component uses context
@@ -25,7 +28,7 @@ export default function ToolPanel() {
const { t } = useTranslation();
const { isRainbowMode } = useRainbowThemeContext();
const { sidebarRefs } = useSidebarContext();
- const { toolPanelRef, quickAccessRef, rightRailRef } = sidebarRefs;
+ const { toolPanelRef, quickAccessRef } = sidebarRefs;
const isMobile = useIsMobile();
const {
@@ -37,14 +40,18 @@ export default function ToolPanel() {
setSearchQuery,
selectedToolKey,
handleToolSelect,
+ handleBackToTools,
setPreviewFile,
toolPanelMode,
setToolPanelMode,
setLeftPanelView,
+ setReaderMode,
+ setSidebarsVisible,
+ sidebarsVisible,
readerMode,
} = useToolWorkflow();
- const { setAllRightRailButtonsDisabled } = useRightRail();
+ const { setAllButtonsDisabled } = useWorkbenchBar();
const { preferences, updatePreference } = usePreferences();
const isFullscreenMode = toolPanelMode === "fullscreen";
@@ -54,41 +61,54 @@ export default function ToolPanel() {
leftPanelView === "toolPicker" &&
!isMobile &&
toolPickerVisible;
- const isRTL =
- typeof document !== "undefined" && document.documentElement.dir === "rtl";
- // Disable right rail buttons when fullscreen mode is active
+ // Disable workbench bar buttons when fullscreen mode is active
useEffect(() => {
- setAllRightRailButtonsDisabled(fullscreenExpanded);
- }, [fullscreenExpanded, setAllRightRailButtonsDisabled]);
+ setAllButtonsDisabled(fullscreenExpanded);
+ }, [fullscreenExpanded, setAllButtonsDisabled]);
const fullscreenGeometry = useToolPanelGeometry({
enabled: fullscreenExpanded,
toolPanelRef,
quickAccessRef,
- rightRailRef,
});
- const toggleLabel = isFullscreenMode
- ? t("toolPanel.toggle.sidebar", "Switch to sidebar mode")
- : t("toolPanel.toggle.fullscreen", "Switch to fullscreen mode");
+ const handleExpand = () => {
+ if (readerMode) setReaderMode(false);
+ if (leftPanelView === "hidden") setLeftPanelView("toolPicker");
+ if (!sidebarsVisible) setSidebarsVisible(true);
+ };
- const handleModeToggle = () => {
- const nextMode = isFullscreenMode ? "sidebar" : "fullscreen";
- setToolPanelMode(nextMode);
+ const handleCollapse = () => {
+ setLeftPanelView("hidden");
+ };
- if (nextMode === "fullscreen" && leftPanelView !== "toolPicker") {
- setLeftPanelView("toolPicker");
- }
+ const [focusSearch, setFocusSearch] = useState(false);
+ const focusSearchOnNextOpen = useRef(false);
+
+ const handleExpandAndSearch = () => {
+ focusSearchOnNextOpen.current = true;
+ handleExpand();
};
+ // Once the panel becomes visible, consume the focus-search request
+ useEffect(() => {
+ if (isPanelVisible && focusSearchOnNextOpen.current) {
+ focusSearchOnNextOpen.current = false;
+ setFocusSearch(true);
+ // Reset after one render so autoFocus doesn't re-fire on subsequent renders
+ const id = setTimeout(() => setFocusSearch(false), 100);
+ return () => clearTimeout(id);
+ }
+ }, [isPanelVisible]);
+
const computedWidth = () => {
if (isMobile) {
return "100%";
}
if (!isPanelVisible) {
- return "0";
+ return "3.5rem";
}
return "18.5rem";
@@ -109,7 +129,7 @@ export default function ToolPanel() {
ref={toolPanelRef}
data-sidebar="tool-panel"
data-tour={fullscreenExpanded ? undefined : "tool-panel"}
- className={`tool-panel flex flex-col ${fullscreenExpanded ? "tool-panel--fullscreen-active" : "overflow-hidden"} bg-[var(--bg-toolbar)] border-r border-[var(--border-subtle)] transition-all duration-300 ease-out ${
+ className={`tool-panel flex flex-col ${fullscreenExpanded ? "tool-panel--fullscreen-active" : "overflow-hidden"} bg-[var(--bg-toolbar)] border-l border-[var(--border-subtle)] transition-all duration-300 ease-out ${
isRainbowMode ? rainbowStyles.rainbowPaper : ""
} ${isMobile ? "h-full border-r-0" : "h-screen"} ${fullscreenExpanded ? "tool-panel--fullscreen" : ""}`}
style={{
@@ -117,21 +137,52 @@ export default function ToolPanel() {
padding: "0",
}}
>
- {!fullscreenExpanded && (
+ {!fullscreenExpanded && !isPanelVisible && !isMobile && (
+ <div className="tool-panel__collapsed-strip">
+ <ActionIcon
+ variant="outline"
+ color="gray.4"
+ radius="xl"
+ size="md"
+ className="tool-panel__expand-btn"
+ onClick={handleExpand}
+ aria-label={t("toolPanel.expand", "Expand panel")}
+ >
+ <ChevronLeftIcon sx={{ fontSize: "1.1rem" }} />
+ </ActionIcon>
+ <ActionIcon
+ variant="subtle"
+ color="gray"
+ radius="md"
+ size="md"
+ className="tool-panel__collapsed-search-btn"
+ onClick={handleExpandAndSearch}
+ aria-label={t("toolPanel.search", "Search tools")}
+ style={{ marginTop: "8px" }}
+ >
+ <SearchIcon sx={{ fontSize: "1.25rem" }} />
+ </ActionIcon>
+ </div>
+ )}
+
+ {!fullscreenExpanded && isPanelVisible && (
<div
style={{
- opacity: isMobile || isPanelVisible ? 1 : 0,
+ opacity: 1,
transition: "opacity 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)",
height: "100%",
display: "flex",
flexDirection: "column",
}}
>
+ {/* Viewer mode tools — annotate, redact, form fill */}
+ <ToolPanelViewerBar />
+
<div
className="tool-panel__search-row"
style={{
- backgroundColor: "var(--tool-panel-search-bg)",
- borderBottom: "1px solid var(--tool-panel-search-border-bottom)",
+ backgroundColor: "transparent",
+ borderBottom: "1px solid var(--border-subtle)",
}}
>
<ToolSearch
@@ -139,29 +190,19 @@ export default function ToolPanel() {
onChange={setSearchQuery}
toolRegistry={toolRegistry}
mode="filter"
+ autoFocus={focusSearch}
/>
- {!isMobile && leftPanelView === "toolPicker" && (
- <Tooltip
- content={toggleLabel}
- position="bottom"
- arrow={true}
- openOnFocus={false}
- >
- <ActionIcon
- variant="subtle"
- radius="xl"
- style={{ color: "var(--right-rail-icon)" }}
- onClick={handleModeToggle}
- aria-label={toggleLabel}
- className="tool-panel__mode-toggle"
- >
- <DoubleArrowIcon
- fontSize="small"
- style={{ transform: isRTL ? "scaleX(-1)" : undefined }}
- />
- </ActionIcon>
- </Tooltip>
- )}
+ <ActionIcon
+ variant="outline"
+ radius="xl"
+ size="md"
+ onClick={handleCollapse}
+ aria-label={t("toolPanel.collapse", "Collapse panel")}
+ className="tool-panel__expand-btn"
+ style={{ flexShrink: 0 }}
+ >
+ <ChevronRightIcon sx={{ fontSize: "1.1rem" }} />
+ </ActionIcon>
</div>
{searchQuery.trim().length > 0 ? (
@@ -185,6 +226,26 @@ export default function ToolPanel() {
</div>
) : (
<div className="flex-1 flex flex-col overflow-hidden">
+ <div
+ style={{
+ borderBottom: "1px solid var(--border-subtle)",
+ flexShrink: 0,
+ }}
+ >
+ <Button
+ variant="light"
+ color="blue"
+ size="sm"
+ fullWidth
+ radius={0}
+ leftSection={<ArrowBackIcon sx={{ fontSize: "0.9rem" }} />}
+ onClick={handleBackToTools}
+ aria-label={t("toolPanel.backToTools", "Back to tools")}
+ styles={{ root: { justifyContent: "flex-start" } }}
+ >
+ {t("toolPanel.backToTools", "Back to tools")}
+ </Button>
+ </div>
<div className="flex-1 min-h-0 overflow-hidden">
<ScrollArea h="100%">
{selectedToolKey ? (
@@ -224,7 +285,6 @@ export default function ToolPanel() {
)
}
onExitFullscreenMode={() => setToolPanelMode("sidebar")}
- toggleLabel={toggleLabel}
geometry={fullscreenGeometry}
/>
)}
diff --git a/frontend/src/core/components/tools/ToolPanelViewerBar.tsx b/frontend/src/core/components/tools/ToolPanelViewerBar.tsx
new file mode 100644
index 0000000000..5e01b4f711
--- /dev/null
+++ b/frontend/src/core/components/tools/ToolPanelViewerBar.tsx
@@ -0,0 +1,99 @@
+import React, { useCallback } from "react";
+import { ActionIcon } from "@mantine/core";
+import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
+import { useNavigationState } from "@app/contexts/NavigationContext";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import type {
+ WorkbenchBarButtonConfig,
+ WorkbenchBarRenderContext,
+} from "@app/types/workbenchBar";
+
+/**
+ * Mini toolbar rendered at the top of the ToolPanel when in viewer mode.
+ * Shows "tool-panel" section buttons — viewer mode tools like annotate, redact, form fill.
+ */
+export function ToolPanelViewerBar() {
+ const { workbench } = useNavigationState();
+ const { buttons, actions, allButtonsDisabled } = useWorkbenchBar();
+
+ const toolPanelButtons = buttons
+ .filter((btn) => btn.section === "tool-panel" && (btn.visible ?? true))
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+
+ const renderButton = useCallback(
+ (btn: WorkbenchBarButtonConfig) => {
+ const action = actions[btn.id];
+ const disabled = Boolean(btn.disabled || allButtonsDisabled);
+ const isActive = Boolean(btn.active);
+
+ const triggerAction = () => {
+ if (!disabled) action?.();
+ };
+
+ if (btn.render) {
+ const context: WorkbenchBarRenderContext = {
+ id: btn.id,
+ disabled,
+ allButtonsDisabled,
+ action,
+ triggerAction,
+ active: isActive,
+ };
+ return btn.render(context) ?? null;
+ }
+
+ if (!btn.icon) return null;
+
+ const ariaLabel =
+ btn.ariaLabel ||
+ (typeof btn.tooltip === "string" ? btn.tooltip : undefined);
+ const buttonNode = (
+ <ActionIcon
+ variant={isActive ? "filled" : "subtle"}
+ color={isActive ? "blue" : undefined}
+ radius="md"
+ className="workbench-bar-action-icon"
+ onClick={triggerAction}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ aria-pressed={isActive || undefined}
+ >
+ {btn.icon}
+ </ActionIcon>
+ );
+
+ if (!btn.tooltip) return buttonNode;
+ return (
+ <Tooltip
+ content={btn.tooltip}
+ position="bottom"
+ offset={6}
+ arrow
+ portalTarget={document.body}
+ >
+ <div style={{ display: "inline-flex" }}>{buttonNode}</div>
+ </Tooltip>
+ );
+ },
+ [actions, allButtonsDisabled],
+ );
+
+ if (workbench !== "viewer" || toolPanelButtons.length === 0) return null;
+
+ return (
+ <div className="tool-panel-viewer-bar">
+ {toolPanelButtons.map((btn) => {
+ const content = renderButton(btn);
+ if (!content) return null;
+ return (
+ <div
+ key={btn.id}
+ style={{ display: "inline-flex", alignItems: "center" }}
+ >
+ {content}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/core/components/tools/ToolPicker.tsx b/frontend/src/core/components/tools/ToolPicker.tsx
index 02ba7625a1..f60475493a 100644
--- a/frontend/src/core/components/tools/ToolPicker.tsx
+++ b/frontend/src/core/components/tools/ToolPicker.tsx
@@ -65,12 +65,12 @@ const ToolPicker = ({
isSearching ? filteredTools : emptyFilteredTools;
const { searchGroups } = useToolSections(effectiveFilteredForSearch);
const headerTextStyle: React.CSSProperties = {
- fontSize: "0.75rem",
- fontWeight: 500,
- padding: "0.5rem 0 0.25rem 0.5rem",
- textTransform: "none",
- color: "var(--text-secondary, rgba(0, 0, 0, 0.6))",
- opacity: 0.7,
+ fontSize: "0.68rem",
+ fontWeight: 600,
+ padding: "1rem 0 0.35rem 0.5rem",
+ textTransform: "uppercase",
+ letterSpacing: "0.06em",
+ color: "var(--text-muted)",
};
const toTitleCase = (s: string) =>
s.replace(
diff --git a/frontend/src/core/components/tools/automate/AutomationRun.tsx b/frontend/src/core/components/tools/automate/AutomationRun.tsx
index d988f1a4a8..3e3a4c0756 100644
--- a/frontend/src/core/components/tools/automate/AutomationRun.tsx
+++ b/frontend/src/core/components/tools/automate/AutomationRun.tsx
@@ -11,7 +11,7 @@ import {
} from "@mantine/core";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import CheckIcon from "@mui/icons-material/Check";
-import { useFileSelection } from "@app/contexts/FileContext";
+import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
import { AutomationConfig, ExecutionStep } from "@app/types/automation";
import { EXECUTION_STATUS } from "@app/constants/automation";
@@ -29,7 +29,7 @@ export default function AutomationRun({
automateOperation,
}: AutomationRunProps) {
const { t } = useTranslation();
- const { selectedFiles } = useFileSelection();
+ const selectedFiles = useViewScopedFiles();
const { regularTools } = useToolRegistry();
const toolRegistry = regularTools;
const cleanup = useResourceCleanup();
diff --git a/frontend/src/core/components/tools/compare/CompareDocumentPane.tsx b/frontend/src/core/components/tools/compare/CompareDocumentPane.tsx
index cbb33539a1..d3a13a6fdc 100644
--- a/frontend/src/core/components/tools/compare/CompareDocumentPane.tsx
+++ b/frontend/src/core/components/tools/compare/CompareDocumentPane.tsx
@@ -13,6 +13,9 @@ import {
} from "@app/components/tools/compare/compare";
import CompareNavigationDropdown from "@app/components/tools/compare/CompareNavigationDropdown";
import { useIsMobile } from "@app/hooks/useIsMobile";
+import { truncateCenter } from "@app/utils/textUtils";
+
+const COMPARE_PANE_TITLE_MAX_LEN = 48;
// utilities moved to compare.ts
@@ -107,9 +110,14 @@ const CompareDocumentPane = ({
return (
<div className="compare-pane">
<div className="compare-header">
- <Group justify="space-between" align="center">
- <Text fw={600} size="lg">
- {title}
+ <Group justify="space-between" align="center" wrap="nowrap">
+ <Text
+ fw={600}
+ size="lg"
+ style={{ minWidth: 0, flex: 1 }}
+ title={title || undefined}
+ >
+ {title ? truncateCenter(title, COMPARE_PANE_TITLE_MAX_LEN) : title}
</Text>
<Group justify="flex-end" align="center" gap="sm" wrap="nowrap">
{(changes.length > 0 || Boolean(dropdownPlaceholder)) && (
diff --git a/frontend/src/core/components/tools/compare/CompareWorkbenchView.tsx b/frontend/src/core/components/tools/compare/CompareWorkbenchView.tsx
index 5d2842cd67..2034dcaf7c 100644
--- a/frontend/src/core/components/tools/compare/CompareWorkbenchView.tsx
+++ b/frontend/src/core/components/tools/compare/CompareWorkbenchView.tsx
@@ -14,14 +14,14 @@ import {
import { CompareResultData, CompareWorkbenchData } from "@app/types/compare";
import ComparePixelWorkbenchView from "@app/components/tools/compare/ComparePixelWorkbenchView";
import { useFileContext } from "@app/contexts/file/fileHooks";
-import { useRightRailButtons } from "@app/hooks/useRightRailButtons";
+import { useWorkbenchBarButtons } from "@app/hooks/useWorkbenchBarButtons";
import CompareDocumentPane from "@app/components/tools/compare/CompareDocumentPane";
import { useComparePagePreviews } from "@app/components/tools/compare/hooks/useComparePagePreviews";
import { useComparePanZoom } from "@app/components/tools/compare/hooks/useComparePanZoom";
import { useCompareHighlights } from "@app/components/tools/compare/hooks/useCompareHighlights";
import { useCompareChangeNavigation } from "@app/components/tools/compare/hooks/useCompareChangeNavigation";
import "@app/components/tools/compare/compareView.css";
-import { useCompareRightRailButtons } from "@app/components/tools/compare/hooks/useCompareRightRailButtons";
+import { useCompareWorkbenchBarButtons } from "@app/components/tools/compare/hooks/useCompareWorkbenchBarButtons";
import {
alert,
updateToast,
@@ -209,7 +209,7 @@ const CompareTextWorkbenchView = ({ data }: CompareTextWorkbenchViewProps) => {
})
);
- const rightRailButtons = useCompareRightRailButtons({
+ const workbenchBarButtons = useCompareWorkbenchBarButtons({
layout,
toggleLayout,
isPanMode,
@@ -230,7 +230,7 @@ const CompareTextWorkbenchView = ({ data }: CompareTextWorkbenchViewProps) => {
comparisonScrollRef,
});
- useRightRailButtons(rightRailButtons);
+ useWorkbenchBarButtons(workbenchBarButtons);
// Rendering progress toast for very large PDFs
const LARGE_PAGE_THRESHOLD = 400; // show banner when one or both exceed threshold
diff --git a/frontend/src/core/components/tools/compare/compareView.css b/frontend/src/core/components/tools/compare/compareView.css
index c4c4278f08..d65c5fa866 100644
--- a/frontend/src/core/components/tools/compare/compareView.css
+++ b/frontend/src/core/components/tools/compare/compareView.css
@@ -23,10 +23,9 @@
flex-direction: column;
gap: 1.5rem;
padding: 1rem;
- padding-top: 3rem;
height: 100%;
min-height: 0;
- /* Allow the custom workbench to shrink within flex parents (prevents pushing right rail off-screen) */
+ /* Allow the custom workbench to shrink within flex parents */
min-width: 0;
}
@@ -522,6 +521,124 @@
}
}
+/* Compare tool — file selection step (Original / Edited + swap column) */
+.compare-step-selection {
+ width: 100%;
+}
+
+.compare-step-selection__clear-row {
+ display: flex;
+ justify-content: flex-end;
+ width: 100%;
+}
+
+/* Thumbnails + swap only — swap top aligns with first thumbnail, not “Original PDF” heading */
+.compare-step-selection__thumbs-row {
+ display: flex;
+ flex-direction: row;
+ align-items: stretch;
+ gap: 0.75rem;
+ width: 100%;
+ min-width: 0;
+}
+
+.compare-step-selection__thumbs-col {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+/* Full-height light bar to the right of both cards (reference UI) */
+.compare-step-selection__swap {
+ flex-shrink: 0;
+ width: 36px;
+ min-width: 36px;
+ align-self: stretch;
+ margin: 0;
+ padding: 0.5rem 0.2rem;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.35rem;
+ border-radius: var(--radius-md);
+ border: 1px solid
+ color-mix(in srgb, var(--mantine-color-blue-4) 28%, var(--border-default));
+ background: color-mix(
+ in srgb,
+ var(--mantine-color-blue-0) 92%,
+ var(--mantine-color-body)
+ );
+ color: var(--mantine-color-blue-filled);
+ cursor: pointer;
+ font: inherit;
+ transition:
+ background 0.12s ease,
+ border-color 0.12s ease;
+}
+
+.compare-step-selection__swap:hover:not(:disabled) {
+ background: color-mix(
+ in srgb,
+ var(--mantine-color-blue-1) 75%,
+ var(--mantine-color-body)
+ );
+ border-color: color-mix(
+ in srgb,
+ var(--mantine-color-blue-5) 35%,
+ var(--border-default)
+ );
+}
+
+.compare-step-selection__swap:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.compare-step-selection__swap-icon {
+ font-size: 1.35rem !important;
+ color: var(--mantine-color-blue-filled);
+}
+
+.compare-step-selection__swap-label {
+ font-size: 0.7rem;
+ font-weight: 600;
+ line-height: 1.15;
+ text-align: center;
+ color: var(--mantine-color-blue-filled);
+ writing-mode: horizontal-tb;
+}
+
+[data-mantine-color-scheme="”dark”"] .compare-step-selection__swap {
+ background: color-mix(
+ in srgb,
+ var(--mantine-color-blue-9) 22%,
+ var(--mantine-color-dark-6)
+ );
+ border-color: color-mix(
+ in srgb,
+ var(--mantine-color-blue-4) 40%,
+ var(--border-default)
+ );
+ color: var(--mantine-color-blue-3);
+}
+
+[data-mantine-color-scheme="”dark”"]
+ .compare-step-selection__swap:hover:not(:disabled) {
+ background: color-mix(
+ in srgb,
+ var(--mantine-color-blue-9) 32%,
+ var(--mantine-color-dark-6)
+ );
+}
+
+[data-mantine-color-scheme="”dark”"] .compare-step-selection__swap-icon,
+[data-mantine-color-scheme="”dark”"] .compare-step-selection__swap-label {
+ color: var(--mantine-color-blue-3);
+}
+
/* Pixel compare mode */
.compare-pixel-workbench {
padding: 16px 24px 32px;
diff --git a/frontend/src/core/components/tools/compare/hooks/useCompareRightRailButtons.tsx b/frontend/src/core/components/tools/compare/hooks/useCompareWorkbenchBarButtons.tsx
similarity index 93%
rename from frontend/src/core/components/tools/compare/hooks/useCompareRightRailButtons.tsx
rename to frontend/src/core/components/tools/compare/hooks/useCompareWorkbenchBarButtons.tsx
index 273535a05f..3ddbbbf3da 100644
--- a/frontend/src/core/components/tools/compare/hooks/useCompareRightRailButtons.tsx
+++ b/frontend/src/core/components/tools/compare/hooks/useCompareWorkbenchBarButtons.tsx
@@ -4,12 +4,12 @@ import { useTranslation } from "react-i18next";
import LocalIcon from "@app/components/shared/LocalIcon";
import { alert } from "@app/components/toast";
import type { ToastLocation } from "@app/components/toast/types";
-import type { RightRailButtonWithAction } from "@app/hooks/useRightRailButtons";
+import type { WorkbenchBarButtonWithAction } from "@app/hooks/useWorkbenchBarButtons";
import { useIsMobile } from "@app/hooks/useIsMobile";
type Pane = "base" | "comparison";
-export interface UseCompareRightRailButtonsOptions {
+export interface UseCompareWorkbenchBarButtonsOptions {
layout: "side-by-side" | "stacked";
toggleLayout: () => void;
isPanMode: boolean;
@@ -30,7 +30,7 @@ export interface UseCompareRightRailButtonsOptions {
comparisonScrollRef?: React.RefObject<HTMLDivElement | null>;
}
-export const useCompareRightRailButtons = ({
+export const useCompareWorkbenchBarButtons = ({
layout,
toggleLayout,
isPanMode,
@@ -49,11 +49,11 @@ export const useCompareRightRailButtons = ({
zoomLimits,
baseScrollRef,
comparisonScrollRef,
-}: UseCompareRightRailButtonsOptions): RightRailButtonWithAction[] => {
+}: UseCompareWorkbenchBarButtonsOptions): WorkbenchBarButtonWithAction[] => {
const { t, i18n } = useTranslation();
const isMobile = useIsMobile();
- return useMemo<RightRailButtonWithAction[]>(
+ return useMemo<WorkbenchBarButtonWithAction[]>(
() => [
{
id: "compare-toggle-layout",
@@ -212,6 +212,6 @@ export const useCompareRightRailButtons = ({
);
};
-export type UseCompareRightRailButtonsReturn = ReturnType<
- typeof useCompareRightRailButtons
+export type UseCompareWorkbenchBarButtonsReturn = ReturnType<
+ typeof useCompareWorkbenchBarButtons
>;
diff --git a/frontend/src/core/components/tools/crop/CropSettings.tsx b/frontend/src/core/components/tools/crop/CropSettings.tsx
index 8525d44c42..65b0e8f0fe 100644
--- a/frontend/src/core/components/tools/crop/CropSettings.tsx
+++ b/frontend/src/core/components/tools/crop/CropSettings.tsx
@@ -12,7 +12,7 @@ import {
import { useTranslation } from "react-i18next";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import { CropParametersHook } from "@app/hooks/tools/crop/useCropParameters";
-import { useSelectedFiles } from "@app/contexts/file/fileHooks";
+import { useAllFiles } from "@app/contexts/FileContext";
import CropAreaSelector from "@app/components/tools/crop/CropAreaSelector";
import CropCoordinateInputs from "@app/components/tools/crop/CropCoordinateInputs";
import { DEFAULT_CROP_AREA } from "@app/constants/cropConstants";
@@ -34,17 +34,17 @@ const CONTAINER_SIZE = 250; // Fit within actual pane width
const CropSettings = ({ parameters, disabled = false }: CropSettingsProps) => {
const { t } = useTranslation();
- const { selectedFiles, selectedFileStubs } = useSelectedFiles();
+ const { files, fileStubs } = useAllFiles();
- // Get the first selected file for preview
+ // Get the first file for preview
const selectedStub = useMemo(() => {
- return selectedFileStubs.length > 0 ? selectedFileStubs[0] : null;
- }, [selectedFileStubs]);
+ return fileStubs.length > 0 ? fileStubs[0] : null;
+ }, [fileStubs]);
- // Get the first selected file for PDF processing
+ // Get the first file for PDF processing
const selectedFile = useMemo(() => {
- return selectedFiles.length > 0 ? selectedFiles[0] : null;
- }, [selectedFiles]);
+ return files.length > 0 ? files[0] : null;
+ }, [files]);
// Get thumbnail for the selected file
const [thumbnail, setThumbnail] = useState<string | null>(null);
diff --git a/frontend/src/core/components/tools/fullscreen/CompactToolItem.tsx b/frontend/src/core/components/tools/fullscreen/CompactToolItem.tsx
index 858e1fd572..a6f4d257b3 100644
--- a/frontend/src/core/components/tools/fullscreen/CompactToolItem.tsx
+++ b/frontend/src/core/components/tools/fullscreen/CompactToolItem.tsx
@@ -76,9 +76,7 @@ const CompactToolItem: React.FC<CompactToolItemProps> = ({
) : null}
<span className="tool-panel__fullscreen-list-body">
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
- <Text fw={600} size="sm" className="tool-panel__fullscreen-name">
- {tool.name}
- </Text>
+ <Text className="tool-panel__fullscreen-name">{tool.name}</Text>
{tool.versionStatus === "alpha" && (
<Badge size="xs" variant="light" color="orange">
{t("toolPanel.alpha", "Alpha")}
diff --git a/frontend/src/core/components/tools/fullscreen/DetailedToolItem.tsx b/frontend/src/core/components/tools/fullscreen/DetailedToolItem.tsx
index 61372fad05..32fa181a16 100644
--- a/frontend/src/core/components/tools/fullscreen/DetailedToolItem.tsx
+++ b/frontend/src/core/components/tools/fullscreen/DetailedToolItem.tsx
@@ -78,9 +78,7 @@ const DetailedToolItem: React.FC<DetailedToolItemProps> = ({
) : null}
<span className="tool-panel__fullscreen-body">
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
- <Text fw={600} size="sm" className="tool-panel__fullscreen-name">
- {tool.name}
- </Text>
+ <Text className="tool-panel__fullscreen-name">{tool.name}</Text>
{tool.versionStatus === "alpha" && (
<Badge size="xs" variant="light" color="orange">
{/* we can add more translations for different badges in future, like beta, etc. */}
diff --git a/frontend/src/core/components/tools/rotate/RotateSettings.tsx b/frontend/src/core/components/tools/rotate/RotateSettings.tsx
index 134bf97b4e..cae25c5a65 100644
--- a/frontend/src/core/components/tools/rotate/RotateSettings.tsx
+++ b/frontend/src/core/components/tools/rotate/RotateSettings.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import { RotateParametersHook } from "@app/hooks/tools/rotate/useRotateParameters";
-import { useSelectedFiles } from "@app/contexts/file/fileHooks";
+import { useAllFiles } from "@app/contexts/FileContext";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
interface RotateSettingsProps {
@@ -17,12 +17,12 @@ const RotateSettings = ({
disabled = false,
}: RotateSettingsProps) => {
const { t } = useTranslation();
- const { selectedFileStubs } = useSelectedFiles();
+ const { fileStubs } = useAllFiles();
- // Get the first selected file for preview
+ // Get the first file for preview
const selectedStub = useMemo(() => {
- return selectedFileStubs.length > 0 ? selectedFileStubs[0] : null;
- }, [selectedFileStubs]);
+ return fileStubs.length > 0 ? fileStubs[0] : null;
+ }, [fileStubs]);
// Get thumbnail for the selected file
const [thumbnail, setThumbnail] = useState<string | null>(null);
diff --git a/frontend/src/core/components/tools/shared/FileStatusIndicator.tsx b/frontend/src/core/components/tools/shared/FileStatusIndicator.tsx
index 90c24253fe..08a0d0ed91 100644
--- a/frontend/src/core/components/tools/shared/FileStatusIndicator.tsx
+++ b/frontend/src/core/components/tools/shared/FileStatusIndicator.tsx
@@ -59,17 +59,12 @@ const FileStatusIndicator = ({
const getPlaceholder = () => {
if (minFiles === undefined || minFiles === 1) {
- return t(
- "files.selectFromWorkbench",
- "Select files from the workbench or ",
- );
+ return t("files.selectFromWorkbench", "Add files to the workbench or ");
} else {
return t(
"files.selectMultipleFromWorkbench",
- "Select at least {{count}} files from the workbench or ",
- {
- count: minFiles,
- },
+ "Add at least {{count}} files to the workbench or ",
+ { count: minFiles },
);
}
};
@@ -171,14 +166,12 @@ const FileStatusIndicator = ({
✓{" "}
{selectedFiles.length === 1 ? (
<PrivateContent>
- {t("fileSelected", "Selected: {{filename}}", {
+ {t("fileSelected", "{{filename}}", {
filename: selectedFiles[0]?.name,
})}
</PrivateContent>
) : (
- t("filesSelected", "{{count}} files selected", {
- count: selectedFiles.length,
- })
+ t("filesSelected", "{{count}} files", { count: selectedFiles.length })
)}
</Text>
);
diff --git a/frontend/src/core/components/tools/shared/OperationButton.tsx b/frontend/src/core/components/tools/shared/OperationButton.tsx
index e6db1478e7..3993953eab 100644
--- a/frontend/src/core/components/tools/shared/OperationButton.tsx
+++ b/frontend/src/core/components/tools/shared/OperationButton.tsx
@@ -58,6 +58,10 @@ const OperationButton = ({
"tool.endpointUnavailable",
"This tool is unavailable on your server.",
),
+ filesLoading: t(
+ "tool.filesLoading",
+ "Files are still loading, please wait.",
+ ),
noFiles: t("tool.noFiles", "Add a file to get started."),
invalidParams: t("tool.invalidParams", "Fill in the required settings."),
viewerMode: t(
diff --git a/frontend/src/core/components/tools/shared/ReviewToolStep.tsx b/frontend/src/core/components/tools/shared/ReviewToolStep.tsx
index 70bb9408d2..82e936678e 100644
--- a/frontend/src/core/components/tools/shared/ReviewToolStep.tsx
+++ b/frontend/src/core/components/tools/shared/ReviewToolStep.tsx
@@ -120,6 +120,7 @@ function ReviewStepContent<TParams = unknown>({
{onUndo && (
<Tooltip
+ position="left"
content={t(
"undoOperationTooltip",
"Click to undo the last operation and restore the original files",
diff --git a/frontend/src/core/components/tools/shared/ScopedOperationButton.tsx b/frontend/src/core/components/tools/shared/ScopedOperationButton.tsx
index 512dc2f956..1761c91e4b 100644
--- a/frontend/src/core/components/tools/shared/ScopedOperationButton.tsx
+++ b/frontend/src/core/components/tools/shared/ScopedOperationButton.tsx
@@ -1,4 +1,4 @@
-import { Text } from "@mantine/core";
+import { Text, Box, Button } from "@mantine/core";
import { useTranslation } from "react-i18next";
import OperationButton, {
OperationButtonProps,
@@ -18,8 +18,7 @@ export interface ScopedOperationButtonProps extends OperationButtonProps {
*
* - Viewer mode (multiple files loaded): appends "(this file)" to button text and
* shows a note naming the exact file that will be processed.
- * - File-editor mode with N>1 selected files: appends "(N files)" to button text.
- * - File-editor mode with 0 selected files: shows a hint to select files.
+ * - N>1 files loaded: appends "(N files)" to button text.
* - All other cases: no change to button text or layout.
*/
export function ScopedOperationButton({
@@ -30,7 +29,14 @@ export function ScopedOperationButton({
const { t } = useTranslation();
const { workbench } = useNavigationState();
const { activeFileIndex } = useViewer();
- const { files: allFiles } = useAllFiles();
+ const { files: allFiles, fileIds } = useAllFiles();
+
+ // Disable until all files are hydrated — running early would silently skip unloaded files.
+ const isFilesHydrating = fileIds.length > allFiles.length;
+ const effectiveDisabledReason =
+ isFilesHydrating && props.disabledReason !== "endpointUnavailable"
+ ? "filesLoading"
+ : props.disabledReason;
const isViewerMode = workbench === "viewer";
const isFileEditorMode = workbench === "fileEditor";
@@ -56,6 +62,11 @@ export function ScopedOperationButton({
? allFiles[activeFileIndex]?.name
: null;
+ const pendingCount = fileIds.length - allFiles.length;
+ const isBulkLoading = pendingCount > 1;
+ const loadProgress = isBulkLoading
+ ? (allFiles.length / fileIds.length) * 100
+ : 0;
const showSelectFilesHint =
!disableScopeHints &&
isFileEditorMode &&
@@ -64,7 +75,54 @@ export function ScopedOperationButton({
return (
<>
- <OperationButton {...props} submitText={scopedText} />
+ {isFilesHydrating ? (
+ <Box mx="md" mt="md">
+ <Button
+ fullWidth
+ disabled
+ loading={!isBulkLoading}
+ variant={props.variant ?? "filled"}
+ color={props.color ?? "blue"}
+ style={{
+ position: "relative",
+ overflow: "hidden",
+ minHeight: "2.5rem",
+ pointerEvents: "none",
+ }}
+ >
+ {isBulkLoading && (
+ <>
+ <Box
+ style={{
+ position: "absolute",
+ inset: 0,
+ width: `${loadProgress}%`,
+ backgroundColor: "rgba(255,255,255,0.15)",
+ transition: "width 0.3s ease",
+ borderRadius: "inherit",
+ }}
+ />
+ <Text size="sm" style={{ position: "relative" }}>
+ {t(
+ "tool.filesLoadingProgress",
+ "{{loaded}} / {{total}} files loading...",
+ {
+ loaded: allFiles.length,
+ total: fileIds.length,
+ },
+ )}
+ </Text>
+ </>
+ )}
+ </Button>
+ </Box>
+ ) : (
+ <OperationButton
+ {...props}
+ submitText={scopedText}
+ disabledReason={effectiveDisabledReason}
+ />
+ )}
{viewerFileName && (
<Text size="xs" c="dimmed" ta="center" mx="md" mt={2}>
{t("tool.singleFileScope", "Only applying to: {{fileName}}", {
diff --git a/frontend/src/core/components/tools/showJS/ShowJSView.css b/frontend/src/core/components/tools/showJS/ShowJSView.css
index 3121c2e29a..301589a930 100644
--- a/frontend/src/core/components/tools/showJS/ShowJSView.css
+++ b/frontend/src/core/components/tools/showJS/ShowJSView.css
@@ -92,7 +92,7 @@
border: 1px solid var(--mantine-color-gray-4);
border-radius: 8px;
overflow: hidden;
- background: var(--right-rail-bg);
+ background: var(--bg-file-manager);
}
.showjs-toolbar {
diff --git a/frontend/src/core/components/tools/toolPicker/ToolButton.tsx b/frontend/src/core/components/tools/toolPicker/ToolButton.tsx
index 1983163360..d4021d794a 100644
--- a/frontend/src/core/components/tools/toolPicker/ToolButton.tsx
+++ b/frontend/src/core/components/tools/toolPicker/ToolButton.tsx
@@ -201,13 +201,17 @@ const ToolButton: React.FC<ToolButtonProps> = ({
handleUnlessSpecialClick(e, () => handleClick(id));
};
+ const selectedStyles = isSelected
+ ? { backgroundColor: "#EAEAEA", color: "var(--tools-text-and-icon-color)" }
+ : {};
+
const buttonElement = navProps ? (
// For internal tools with URLs, render Button as an anchor for proper link behavior
<Button
component="a"
href={navProps.href}
onClick={navProps.onClick}
- variant={isSelected ? "filled" : "subtle"}
+ variant="subtle"
size="sm"
radius="md"
fullWidth
@@ -219,6 +223,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
borderRadius: 0,
color: "var(--tools-text-and-icon-color)",
overflow: "visible",
+ ...selectedStyles,
},
label: { overflow: "visible" },
}}
@@ -233,7 +238,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
target="_blank"
rel="noopener noreferrer"
onClick={handleExternalClick}
- variant={isSelected ? "filled" : "subtle"}
+ variant="subtle"
size="sm"
radius="md"
fullWidth
@@ -245,6 +250,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
borderRadius: 0,
color: "var(--tools-text-and-icon-color)",
overflow: "visible",
+ ...selectedStyles,
},
label: { overflow: "visible" },
}}
@@ -254,7 +260,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
) : (
// For unavailable tools, use regular button
<Button
- variant={isSelected ? "filled" : "subtle"}
+ variant="subtle"
onClick={() => handleClick(id)}
size="sm"
radius="md"
@@ -269,6 +275,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
color: "var(--tools-text-and-icon-color)",
cursor: visuallyUnavailable ? "not-allowed" : undefined,
overflow: "visible",
+ ...selectedStyles,
},
label: { overflow: "visible" },
}}
@@ -292,7 +299,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({
{star}
<Tooltip
content={tooltipContent}
- position="right"
+ position="left"
arrow={true}
delay={500}
>
diff --git a/frontend/src/core/components/tools/toolPicker/ToolPicker.css b/frontend/src/core/components/tools/toolPicker/ToolPicker.css
index a7b73bee54..54551d8105 100644
--- a/frontend/src/core/components/tools/toolPicker/ToolPicker.css
+++ b/frontend/src/core/components/tools/toolPicker/ToolPicker.css
@@ -57,13 +57,16 @@
/* Compact tool buttons */
.tool-button {
- font-size: 0.875rem; /* default 1rem - 0.125rem? We'll apply exact -0.25rem via calc below */
- padding-top: 0.375rem;
- padding-bottom: 0.375rem;
+ font-size: 0.875rem;
+ padding-top: 0.5rem;
+ padding-bottom: 0.5rem;
+ padding-left: 0.5rem;
}
.tool-button .mantine-Button-label {
- font-size: 0.85rem;
+ font-size: 0.84rem;
+ font-weight: 500;
+ line-height: 1.2;
}
.tool-button-icon {
diff --git a/frontend/src/core/components/tools/toolPicker/ToolSearch.tsx b/frontend/src/core/components/tools/toolPicker/ToolSearch.tsx
index b2a2c01e91..ae136c4333 100644
--- a/frontend/src/core/components/tools/toolPicker/ToolSearch.tsx
+++ b/frontend/src/core/components/tools/toolPicker/ToolSearch.tsx
@@ -17,6 +17,7 @@ interface ToolSearchProps {
selectedToolKey?: string | null;
placeholder?: string;
hideIcon?: boolean;
+ iconOverride?: React.ReactNode;
onFocus?: () => void;
autoFocus?: boolean;
}
@@ -30,6 +31,7 @@ const ToolSearch = ({
selectedToolKey,
placeholder,
hideIcon = false,
+ iconOverride,
onFocus,
autoFocus = false,
}: ToolSearchProps) => {
@@ -96,10 +98,12 @@ const ToolSearch = ({
placeholder || t("toolPicker.searchPlaceholder", "Search tools...")
}
icon={
- hideIcon ? undefined : (
- <LocalIcon icon="search-rounded" width="1.5rem" height="1.5rem" />
- )
+ iconOverride ??
+ (hideIcon ? undefined : (
+ <LocalIcon icon="search-rounded" width="1.25rem" height="1.25rem" />
+ ))
}
+ iconClickable={!!iconOverride}
autoComplete="off"
onFocus={onFocus}
/>
diff --git a/frontend/src/core/components/viewer/CommentsSidebar.tsx b/frontend/src/core/components/viewer/CommentsSidebar.tsx
index fef8adb8db..ffd39517ad 100644
--- a/frontend/src/core/components/viewer/CommentsSidebar.tsx
+++ b/frontend/src/core/components/viewer/CommentsSidebar.tsx
@@ -538,7 +538,7 @@ export function CommentsSidebar({
top: 0,
bottom: 0,
width: SIDEBAR_WIDTH,
- backgroundColor: "var(--right-rail-bg)",
+ backgroundColor: "var(--bg-file-manager)",
borderLeft: "1px solid var(--border-subtle)",
zIndex: 998,
display: "flex",
diff --git a/frontend/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/src/core/components/viewer/EmbedPdfViewer.tsx
index 81e421abdf..889cc2aeaa 100644
--- a/frontend/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -5,6 +5,7 @@ import React, {
useRef,
useState,
} from "react";
+import { useTranslation } from "react-i18next";
import { Box, Center, Text, ActionIcon, Button, Stack } from "@mantine/core";
import CloseIcon from "@mui/icons-material/Close";
import LockIcon from "@mui/icons-material/Lock";
@@ -27,7 +28,7 @@ import { useRedaction } from "@app/contexts/RedactionContext";
import type { RedactionPendingTrackerAPI } from "@app/components/viewer/RedactionPendingTracker";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import { isStirlingFile, getFormFillFileId } from "@app/types/fileContext";
-import { useViewerRightRailButtons } from "@app/components/viewer/useViewerRightRailButtons";
+import { useViewerWorkbenchBarButtons } from "@app/components/viewer/useViewerWorkbenchBarButtons";
import { StampPlacementOverlay } from "@app/components/viewer/StampPlacementOverlay";
import {
RulerOverlay,
@@ -138,8 +139,6 @@ export interface EmbedPdfViewerProps {
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
- activeFileIndex?: number;
- setActiveFileIndex?: (index: number) => void;
}
const EmbedPdfViewerContent = ({
@@ -147,9 +146,8 @@ const EmbedPdfViewerContent = ({
setSidebarsVisible: _setSidebarsVisible,
onClose,
previewFile,
- activeFileIndex: externalActiveFileIndex,
- setActiveFileIndex: externalSetActiveFileIndex,
}: EmbedPdfViewerProps) => {
+ const { t } = useTranslation();
const viewerRef = React.useRef<HTMLDivElement>(null);
const pdfContainerRef = useRef<HTMLDivElement>(null);
const [isViewerHovered, setIsViewerHovered] = React.useState(false);
@@ -178,6 +176,9 @@ const EmbedPdfViewerContent = ({
applyChanges: viewerApplyChanges,
pdfRenderMode,
cyclePdfRenderMode,
+ setActiveFileIndex: _setActiveFileIndex,
+ activeFileId,
+ setActiveFileId,
} = useViewer();
const scrollState = getScrollState();
@@ -327,63 +328,25 @@ const EmbedPdfViewerContent = ({
isInAnnotationTool && isPlacementMode && signatureConfig,
);
- // Track which file tab is active
- const [internalActiveFileIndex, setInternalActiveFileIndex] = useState(0);
- const activeFileIndex = externalActiveFileIndex ?? internalActiveFileIndex;
- const setActiveFileIndex =
- externalSetActiveFileIndex ?? setInternalActiveFileIndex;
-
- // activeFileId (from ViewerContext) is the stable source of truth.
- // We derive activeFileIndex from it so reorders after tool operations don't lose the viewed file.
- const { activeFileId, setActiveFileId } = useViewer();
-
- // Stable string key representing the current file list order.
- // Using a joined ID string avoids depending on the activeFiles array reference,
- // which is a new object every render and would cause an infinite effect loop.
- const fileIdsKey = activeFiles.map((f) => f.fileId).join(",");
-
- // When the file list actually changes, re-derive activeFileIndex from the stable activeFileId.
- useEffect(() => {
- if (!activeFileId || activeFiles.length === 0) return;
- const newIndex = activeFiles.findIndex((f) => f.fileId === activeFileId);
- if (newIndex !== -1 && newIndex !== activeFileIndex) {
- setActiveFileIndex(newIndex);
- }
- }, [fileIdsKey, activeFileId]); // stable primitives — no infinite loop
-
- // When the user manually switches file tabs, keep activeFileId in sync.
- // Skips the initial mount to avoid overwriting an activeFileId set by handleViewFile.
- const activeFileIndexMountedRef = useRef(false);
- useEffect(() => {
- if (!activeFileIndexMountedRef.current) {
- activeFileIndexMountedRef.current = true;
- return;
- }
- const fileId = activeFilesRef.current[activeFileIndex]?.fileId;
- if (fileId && fileId !== activeFileId) {
- setActiveFileId(fileId);
- }
- }, [activeFileIndex]);
-
- // Reset active tab if it's out of bounds (safety net)
- useEffect(() => {
- if (activeFileIndex >= activeFiles.length && activeFiles.length > 0) {
- setActiveFileIndex(0);
- }
- }, [activeFiles.length, activeFileIndex]);
-
- // Determine which file to display
+ // Determine which file to display — use activeFileId (stable) not activeFileIndex (shifts on removal)
const currentFile = React.useMemo(() => {
if (previewFile) {
return previewFile;
} else if (activeFiles.length > 0) {
- return activeFiles[activeFileIndex] || activeFiles[0];
+ const byId = activeFileId
+ ? activeFiles.find(
+ (f) => isStirlingFile(f) && f.fileId === activeFileId,
+ )
+ : null;
+ return byId || activeFiles[0];
}
return null;
- }, [previewFile, activeFiles, activeFileIndex]);
+ }, [previewFile, activeFiles, activeFileId]);
- // Get file with URL for rendering
- const fileWithUrl = useFileWithUrl(currentFile);
+ // Stable id — avoids blob URL churn when FileContext recreates file objects each render.
+ const currentFileStableId =
+ currentFile && isStirlingFile(currentFile) ? currentFile.fileId : null;
+ const fileWithUrl = useFileWithUrl(currentFile, currentFileStableId);
// Determine the effective file to display
const effectiveFile = React.useMemo(() => {
@@ -703,7 +666,7 @@ const EmbedPdfViewerContent = ({
// Step 3: Create StirlingFiles and stubs for version history
// Only consume the current file, not all active files
- const currentFileId = activeFiles[activeFileIndex]?.fileId;
+ const currentFileId = currentFileStableId;
if (!currentFileId) throw new Error("Current file ID not found");
const parentStub = selectors.getStirlingFileStub(currentFileId);
@@ -739,7 +702,6 @@ const EmbedPdfViewerContent = ({
}, [
currentFile,
activeFiles,
- activeFileIndex,
exportActions,
actions,
selectors,
@@ -773,7 +735,7 @@ const EmbedPdfViewerContent = ({
});
// Get current file info for creating the updated version
- const currentFileId = activeFiles[activeFileIndex]?.fileId;
+ const currentFileId = currentFileStableId;
if (!currentFileId) throw new Error("Current file ID not found");
const parentStub = selectors.getStirlingFileStub(currentFileId);
@@ -811,7 +773,6 @@ const EmbedPdfViewerContent = ({
[
currentFile,
activeFiles,
- activeFileIndex,
actions,
selectors,
activeFileIds.length,
@@ -847,7 +808,7 @@ const EmbedPdfViewerContent = ({
type: "application/pdf",
});
- const currentFileId = activeFiles[activeFileIndex]?.fileId;
+ const currentFileId = currentFileStableId;
if (!currentFileId) throw new Error("Current file ID not found");
const parentStub = selectors.getStirlingFileStub(currentFileId);
@@ -877,7 +838,6 @@ const EmbedPdfViewerContent = ({
[
currentFile,
activeFiles,
- activeFileIndex,
actions,
selectors,
activeFileIds.length,
@@ -916,7 +876,7 @@ const EmbedPdfViewerContent = ({
const file = new File([blob], filename, { type: "application/pdf" });
// Create StirlingFiles and stubs for version history
- const currentFileId = activeFiles[activeFileIndex]?.fileId;
+ const currentFileId = currentFileStableId;
if (!currentFileId) throw new Error("Current file ID not found");
const parentStub = selectors.getStirlingFileStub(currentFileId);
@@ -949,7 +909,6 @@ const EmbedPdfViewerContent = ({
redactionsApplied,
currentFile,
activeFiles,
- activeFileIndex,
activeFileIds.length,
exportActions,
actions,
@@ -1123,8 +1082,8 @@ const EmbedPdfViewerContent = ({
};
}, [effectiveFile]);
- // Register viewer right-rail buttons
- useViewerRightRailButtons(isRulerActive, setIsRulerActive);
+ // Register workbench bar buttons for the viewer
+ useViewerWorkbenchBarButtons(isRulerActive, setIsRulerActive);
// Auto-fetch form fields when a PDF is loaded in the viewer.
// In normal viewer mode, this uses PDFium WASM (frontend-only).
@@ -1157,7 +1116,11 @@ const EmbedPdfViewerContent = ({
// the effect re-fires before the async fetch completes.
}
- if (currentFile && (fileChanged || providerChanged)) {
+ if (
+ currentFile &&
+ !isCurrentFileEncrypted &&
+ (fileChanged || providerChanged)
+ ) {
console.log("[FormFill] Fetching form fields for:", currentFileId);
fetchFormFields(currentFile, currentFileId ?? undefined);
}
@@ -1219,7 +1182,12 @@ const EmbedPdfViewerContent = ({
<Center style={{ flex: 1 }}>
<Stack align="center" gap="md">
<LockIcon style={{ fontSize: 48, opacity: 0.5 }} />
- <Text fw={500}>This PDF is password-protected</Text>
+ <Text fw={500}>
+ {t(
+ "encryptedPdfUnlock.viewerLocked",
+ "This PDF is password-protected",
+ )}
+ </Text>
<Button
variant="filled"
onClick={() => {
@@ -1228,7 +1196,7 @@ const EmbedPdfViewerContent = ({
}
}}
>
- Unlock
+ {t("encryptedPdfUnlock.viewerUnlock", "Unlock")}
</Button>
</Stack>
</Center>
@@ -1329,7 +1297,7 @@ const EmbedPdfViewerContent = ({
<ThumbnailSidebar
visible={isThumbnailSidebarVisible}
onToggle={toggleThumbnailSidebar}
- activeFileIndex={activeFileIndex}
+ activeFileId={activeFileId}
/>
<BookmarkSidebar
visible={isBookmarkSidebarVisible}
diff --git a/frontend/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/src/core/components/viewer/LocalEmbedPDF.tsx
index d3625762bb..11f9decee8 100644
--- a/frontend/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -162,7 +162,10 @@ export function LocalEmbedPDF({
});
}, [config?.enableLogin]);
- // Convert File to URL if needed
+ // Stable key — avoids recreating the blob URL (and crashing ViewportPlugin) when
+ // FileContext produces new File object references for the same file content.
+ const fileStableKey =
+ fileId ?? (file ? `${(file as File).name}-${file.size}` : null);
useEffect(() => {
if (file) {
const objectUrl = URL.createObjectURL(file);
@@ -171,7 +174,17 @@ export function LocalEmbedPDF({
} else if (url) {
setPdfUrl(url);
}
- }, [file, url]);
+ // When file is present, use the stable key to avoid blob URL churn from FileContext
+ // re-renders. When only url is provided, depend on url directly so changes are picked up.
+ }, [file ? fileStableKey : url]);
+
+ // Keyed by fileStableKey to avoid recomputing on every FileContext re-render.
+ const exportFileName = useMemo(() => {
+ if (fileName) return fileName;
+ if (file && "name" in file) return (file as File).name;
+ if (url) return url.split("/").pop()?.split("?")[0] || "document.pdf";
+ return "document.pdf";
+ }, [fileStableKey, fileName, url]);
// Create plugins configuration
const plugins = useMemo(() => {
@@ -183,17 +196,6 @@ export function LocalEmbedPDF({
);
const viewportGap = rootFontSize * 3.5;
- // Determine export filename - use provided fileName, or extract from file/url
- let exportFileName = "document.pdf";
- if (fileName) {
- exportFileName = fileName;
- } else if (file && "name" in file) {
- exportFileName = file.name;
- } else if (url) {
- const urlPath = url.split("/").pop() || "document.pdf";
- exportFileName = urlPath.split("?")[0]; // Remove query params
- }
-
return [
createPluginRegistration(DocumentManagerPluginPackage, {
initialDocuments: [
@@ -290,7 +292,7 @@ export function LocalEmbedPDF({
// Register print plugin for printing PDFs
createPluginRegistration(PrintPluginPackage),
];
- }, [pdfUrl, enableAnnotations, fileName, file, url]);
+ }, [pdfUrl, enableAnnotations, exportFileName]);
// Initialize the engine with the React hook - use local WASM for offline support
const { engine, isLoading, error } = usePdfiumEngine({
diff --git a/frontend/src/core/components/viewer/NonPdfViewer.tsx b/frontend/src/core/components/viewer/NonPdfViewer.tsx
index ec24efe562..1b54fa1680 100644
--- a/frontend/src/core/components/viewer/NonPdfViewer.tsx
+++ b/frontend/src/core/components/viewer/NonPdfViewer.tsx
@@ -4,6 +4,7 @@ import ArticleIcon from "@mui/icons-material/Article";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useFileState } from "@app/contexts/FileContext";
+import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import {
detectFileExtension,
@@ -12,7 +13,6 @@ import {
import { CONVERSION_MATRIX } from "@app/constants/convertConstants";
import { NonPdfBanner } from "@app/components/viewer/nonpdf/NonPdfBanner";
-import { getFileTypeMeta } from "@app/components/viewer/nonpdf/types";
import { ImageViewer } from "@app/components/viewer/nonpdf/ImageViewer";
import { CsvViewer } from "@app/components/viewer/nonpdf/CsvViewer";
import { JsonViewer } from "@app/components/viewer/nonpdf/JsonViewer";
@@ -24,8 +24,6 @@ export interface ViewerProps {
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
- activeFileIndex?: number;
- setActiveFileIndex?: (index: number) => void;
}
export interface NonPdfViewerProps extends ViewerProps {
@@ -34,10 +32,6 @@ export interface NonPdfViewerProps extends ViewerProps {
export function NonPdfViewer({ file }: NonPdfViewerProps) {
const fileType = useMemo(() => detectNonPdfFileType(file), [file]);
- const meta = useMemo(
- () => getFileTypeMeta(fileType, file.name),
- [fileType, file.name],
- );
const { handleToolSelect, toolAvailability } = useToolWorkflow();
@@ -112,7 +106,6 @@ export function NonPdfViewer({ file }: NonPdfViewerProps) {
}}
>
<NonPdfBanner
- meta={meta}
onConvertToPdf={isConvertAvailable ? handleConvertToPdf : undefined}
/>
<Box
@@ -134,7 +127,7 @@ export function NonPdfViewer({ file }: NonPdfViewerProps) {
export function NonPdfViewerWrapper(props: ViewerProps) {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
- const activeFileIndex = props.activeFileIndex ?? 0;
+ const { activeFileIndex } = useViewer();
const file =
props.previewFile ?? activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
@@ -143,7 +136,7 @@ export function NonPdfViewerWrapper(props: ViewerProps) {
return (
<Center style={{ flex: 1 }}>
<Text c="dimmed" size="sm">
- No file selected
+ No file loaded
</Text>
</Center>
);
diff --git a/frontend/src/core/components/viewer/PdfViewerToolbar.tsx b/frontend/src/core/components/viewer/PdfViewerToolbar.tsx
index 7ce3b99180..ea71bb826b 100644
--- a/frontend/src/core/components/viewer/PdfViewerToolbar.tsx
+++ b/frontend/src/core/components/viewer/PdfViewerToolbar.tsx
@@ -1,5 +1,12 @@
import { useState, useEffect } from "react";
-import { Button, Paper, Group, NumberInput } from "@mantine/core";
+import {
+ ActionIcon,
+ Button,
+ Paper,
+ Group,
+ NumberInput,
+ Slider,
+} from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useViewer } from "@app/contexts/ViewerContext";
import { Tooltip } from "@app/components/shared/Tooltip";
@@ -12,6 +19,8 @@ import ViewWeekIcon from "@mui/icons-material/ViewWeek";
import DarkModeIcon from "@mui/icons-material/DarkMode";
import WbSunnyIcon from "@mui/icons-material/WbSunny";
import WbTwilightIcon from "@mui/icons-material/WbTwilight";
+import ZoomInIcon from "@mui/icons-material/ZoomIn";
+import ZoomOutIcon from "@mui/icons-material/ZoomOut";
interface PdfViewerToolbarProps {
// Page navigation props (placeholders for now)
@@ -291,31 +300,48 @@ export function PdfViewerToolbar({
{/* Zoom Controls */}
<Group gap={4} align="center" style={{ marginLeft: 16 }}>
- <Button
+ <ActionIcon
variant="subtle"
color="blue"
- size="md"
- radius="xl"
+ radius="md"
onClick={handleZoomOut}
- style={{ minWidth: "2rem", padding: 0 }}
- title={t("viewer.zoomOut", "Zoom out")}
+ aria-label={t("viewer.zoomOut", "Zoom out")}
>
- −
- </Button>
- <span style={{ minWidth: "2.5rem", textAlign: "center" }}>
- {displayZoomPercent}%
- </span>
- <Button
+ <ZoomOutIcon fontSize="small" />
+ </ActionIcon>
+ <Slider
+ value={Math.min(Math.max(displayZoomPercent, 20), 500)}
+ min={20}
+ max={500}
+ step={5}
+ onChange={(val) => zoomActions.setZoomLevel?.(val / 100)}
+ size="xs"
+ styles={{
+ root: { width: "6rem" },
+ thumb: { width: 14, height: 14 },
+ track: { height: 3 },
+ }}
+ label={null}
+ />
+ <ActionIcon
variant="subtle"
color="blue"
- size="md"
- radius="xl"
+ radius="md"
onClick={handleZoomIn}
- style={{ minWidth: "2rem", padding: 0 }}
- title={t("viewer.zoomIn", "Zoom in")}
+ aria-label={t("viewer.zoomIn", "Zoom in")}
>
- +
- </Button>
+ <ZoomInIcon fontSize="small" />
+ </ActionIcon>
+ <span
+ style={{
+ minWidth: "2.5rem",
+ textAlign: "center",
+ fontSize: 12,
+ color: "var(--text-muted)",
+ }}
+ >
+ {displayZoomPercent}%
+ </span>
</Group>
</Paper>
);
diff --git a/frontend/src/core/components/viewer/ThumbnailSidebar.tsx b/frontend/src/core/components/viewer/ThumbnailSidebar.tsx
index 1876cf5812..06a3043363 100644
--- a/frontend/src/core/components/viewer/ThumbnailSidebar.tsx
+++ b/frontend/src/core/components/viewer/ThumbnailSidebar.tsx
@@ -6,13 +6,13 @@ import { PrivateContent } from "@app/components/shared/PrivateContent";
interface ThumbnailSidebarProps {
visible: boolean;
onToggle: () => void;
- activeFileIndex?: number;
+ activeFileId?: string | null;
}
export function ThumbnailSidebar({
visible,
onToggle: _onToggle,
- activeFileIndex,
+ activeFileId,
}: ThumbnailSidebarProps) {
const { getScrollState, scrollActions, getThumbnailAPI } = useViewer();
const [thumbnails, setThumbnails] = useState<{ [key: number]: string }>({});
@@ -29,7 +29,7 @@ export function ThumbnailSidebar({
}
});
setThumbnails({});
- }, [activeFileIndex]);
+ }, [activeFileId]);
// Keep a ref to thumbnails for cleanup on unmount
const thumbnailsRef = useRef(thumbnails);
diff --git a/frontend/src/core/components/viewer/Viewer.tsx b/frontend/src/core/components/viewer/Viewer.tsx
index b8fec6defb..7052df4c67 100644
--- a/frontend/src/core/components/viewer/Viewer.tsx
+++ b/frontend/src/core/components/viewer/Viewer.tsx
@@ -5,6 +5,8 @@ import {
type ViewerProps,
} from "@app/components/viewer/NonPdfViewer";
import { useFileState } from "@app/contexts/FileContext";
+import { useViewer } from "@app/contexts/ViewerContext";
+import { isStirlingFile } from "@app/types/fileContext";
import { isPdfFile } from "@app/utils/fileUtils";
export type { ViewerProps };
@@ -12,13 +14,16 @@ export type { ViewerProps };
const Viewer = (props: ViewerProps) => {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
- const activeFileIndex = props.activeFileIndex ?? 0;
+ const { activeFileId } = useViewer();
- // Determine the active file — previewFile takes priority
+ // Determine the active file — previewFile takes priority, then look up by stable ID
const activeFile = useMemo(() => {
if (props.previewFile) return props.previewFile;
- return activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
- }, [props.previewFile, activeFiles, activeFileIndex]);
+ const byId = activeFileId
+ ? activeFiles.find((f) => isStirlingFile(f) && f.fileId === activeFileId)
+ : null;
+ return byId ?? activeFiles[0] ?? null;
+ }, [props.previewFile, activeFiles, activeFileId]);
// Route to the appropriate viewer based on file type
if (activeFile && !isPdfFile(activeFile)) {
diff --git a/frontend/src/core/components/shared/rightRail/ViewerAnnotationControls.tsx b/frontend/src/core/components/viewer/ViewerAnnotationControls.tsx
similarity index 84%
rename from frontend/src/core/components/shared/rightRail/ViewerAnnotationControls.tsx
rename to frontend/src/core/components/viewer/ViewerAnnotationControls.tsx
index c0383a58c4..78888f4188 100644
--- a/frontend/src/core/components/shared/rightRail/ViewerAnnotationControls.tsx
+++ b/frontend/src/core/components/viewer/ViewerAnnotationControls.tsx
@@ -12,9 +12,7 @@ import {
useNavigationGuard,
useNavigationActions,
} from "@app/contexts/NavigationContext";
-import { useSidebarContext } from "@app/contexts/SidebarContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { useRightRailTooltipSide } from "@app/hooks/useRightRailTooltipSide";
import { useRedactionMode, useRedaction } from "@app/contexts/RedactionContext";
import {
defaultParameters,
@@ -32,10 +30,7 @@ export default function ViewerAnnotationControls({
disabled = false,
}: ViewerAnnotationControlsProps) {
const { t } = useTranslation();
- const { sidebarRefs } = useSidebarContext();
const { setLeftPanelView, setSidebarsVisible } = useToolWorkflow();
- const { position: tooltipPosition, offset: tooltipOffset } =
- useRightRailTooltipSide(sidebarRefs);
// Viewer context for PDF controls - safely handle when not available
const viewerContext = React.useContext(ViewerContext);
@@ -129,31 +124,25 @@ export default function ViewerAnnotationControls({
// Handle redaction mode toggle
const handleRedactionToggle = async () => {
if (isRedactMode) {
- // Exit redaction mode
exitRedactionMode();
} else {
- // Check for unsaved annotation changes
const hasAnnotationChanges = historyApiRef?.current?.canUndo() ?? false;
const enterRedactionMode = async () => {
await saveAnnotationsIfNeeded();
- // Set redaction config to manual mode when opening from viewer
const manualConfig: RedactParameters = {
...defaultParameters,
mode: "manual",
};
setRedactionConfig(manualConfig);
- // Set tool and keep viewer workbench
navActions.setToolAndWorkbench("redact", "viewer");
- // Ensure sidebars are visible and open tool content
setSidebarsVisible(true);
setLeftPanelView("toolContent");
setRedactionMode(true);
- // Activate unified redact mode after a short delay
setTimeout(() => {
const currentType = redactionApiRef.current?.getActiveType?.();
if (currentType !== RedactionMode.Redact) {
@@ -171,7 +160,6 @@ export default function ViewerAnnotationControls({
};
const handleToggleAnnotationsVisibility = useCallback(() => {
- // When going from visible → hidden with unsaved changes, prompt to save first
if (!annotationsHidden && hasUnsavedChanges) {
requestNavigation(() => viewerContext?.toggleAnnotationsVisibility());
} else {
@@ -179,7 +167,6 @@ export default function ViewerAnnotationControls({
}
}, [annotationsHidden, hasUnsavedChanges, requestNavigation, viewerContext]);
- // Don't show any annotation controls in sign mode
// NOTE: This early return is placed AFTER all hooks to satisfy React's rules of hooks
if (isSignMode) {
return null;
@@ -187,15 +174,14 @@ export default function ViewerAnnotationControls({
return (
<>
- {/* Redaction Mode Toggle */}
<Tooltip
content={
isRedactMode
- ? t("rightRail.exitRedaction", "Exit Redaction Mode")
- : t("rightRail.redact", "Redact")
+ ? t("workbenchBar.exitRedaction", "Exit Redaction Mode")
+ : t("workbenchBar.redact", "Redact")
}
- position={tooltipPosition}
- offset={tooltipOffset}
+ position="bottom"
+ offset={16}
arrow
portalTarget={document.body}
>
@@ -203,26 +189,25 @@ export default function ViewerAnnotationControls({
variant={isRedactMode ? "filled" : "subtle"}
color={isRedactMode ? "blue" : undefined}
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
onClick={handleRedactionToggle}
disabled={disabled || currentView !== "viewer"}
>
<LocalIcon
icon="scan-delete-rounded"
- width="1.5rem"
- height="1.5rem"
+ width="1.25rem"
+ height="1.25rem"
/>
</ActionIcon>
</Tooltip>
- {/* Annotation Visibility Toggle */}
<Tooltip
content={t(
- "rightRail.toggleAnnotations",
+ "workbenchBar.toggleAnnotations",
"Toggle Annotations Visibility",
)}
- position={tooltipPosition}
- offset={tooltipOffset}
+ position="bottom"
+ offset={16}
arrow
portalTarget={document.body}
>
@@ -230,7 +215,7 @@ export default function ViewerAnnotationControls({
variant={annotationsHidden ? "filled" : "subtle"}
color={annotationsHidden ? "blue" : undefined}
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
onClick={handleToggleAnnotationsVisibility}
disabled={
disabled ||
@@ -247,8 +232,8 @@ export default function ViewerAnnotationControls({
? "visibility"
: "preview-off-rounded"
}
- width="1.5rem"
- height="1.5rem"
+ width="1.25rem"
+ height="1.25rem"
/>
</ActionIcon>
</Tooltip>
diff --git a/frontend/src/core/components/viewer/nonpdf/NonPdfBanner.tsx b/frontend/src/core/components/viewer/nonpdf/NonPdfBanner.tsx
index 91e73c79c1..e1f169b85b 100644
--- a/frontend/src/core/components/viewer/nonpdf/NonPdfBanner.tsx
+++ b/frontend/src/core/components/viewer/nonpdf/NonPdfBanner.tsx
@@ -1,59 +1,31 @@
-import { Badge, Box, Button, Group } from "@mantine/core";
+import { Button } from "@mantine/core";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useTranslation } from "react-i18next";
-import type { FileTypeMeta } from "@app/components/viewer/nonpdf/types";
-
interface NonPdfBannerProps {
- meta: FileTypeMeta;
onConvertToPdf?: () => void;
}
-export function NonPdfBanner({ meta, onConvertToPdf }: NonPdfBannerProps) {
+export function NonPdfBanner({ onConvertToPdf }: NonPdfBannerProps) {
const { t } = useTranslation();
+ if (!onConvertToPdf) return null;
+
return (
- <Group
- gap="xs"
- wrap="nowrap"
- align="center"
+ <Button
+ size="xs"
+ variant="light"
+ color="orange"
+ leftSection={<PictureAsPdfIcon style={{ fontSize: "0.9rem" }} />}
+ onClick={onConvertToPdf}
style={{
position: "absolute",
top: 8,
right: 8,
zIndex: 10,
- pointerEvents: "auto",
}}
>
- <Badge
- variant="default"
- size="lg"
- leftSection={
- <Box
- style={{
- display: "flex",
- alignItems: "center",
- fontSize: "0.85rem",
- }}
- >
- {meta.icon}
- </Box>
- }
- style={{ fontWeight: 600 }}
- >
- {t("viewer.nonPdf.fileTypeBadge", { type: meta.label })}
- </Badge>
- {onConvertToPdf && (
- <Button
- size="xs"
- variant="light"
- color="orange"
- leftSection={<PictureAsPdfIcon style={{ fontSize: "0.9rem" }} />}
- onClick={onConvertToPdf}
- >
- {t("viewer.nonPdf.convertToPdf")}
- </Button>
- )}
- </Group>
+ {t("viewer.nonPdf.convertToPdf")}
+ </Button>
);
}
diff --git a/frontend/src/core/components/viewer/nonpdf/TextViewer.tsx b/frontend/src/core/components/viewer/nonpdf/TextViewer.tsx
index 61c1674f3e..869d09f9e7 100644
--- a/frontend/src/core/components/viewer/nonpdf/TextViewer.tsx
+++ b/frontend/src/core/components/viewer/nonpdf/TextViewer.tsx
@@ -43,10 +43,13 @@ export function TextViewer({ file, isMarkdown }: TextViewerProps) {
{/* Toolbar */}
<Paper
radius={0}
- p="xs"
+ px="sm"
style={{
borderBottom: "1px solid var(--mantine-color-gray-2)",
flexShrink: 0,
+ minHeight: 44,
+ display: "flex",
+ alignItems: "center",
}}
>
<Group gap="md" align="center">
diff --git a/frontend/src/core/components/viewer/useViewerRightRailButtons.tsx b/frontend/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
similarity index 83%
rename from frontend/src/core/components/viewer/useViewerRightRailButtons.tsx
rename to frontend/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
index 7d54437fb9..25eacf3d9e 100644
--- a/frontend/src/core/components/viewer/useViewerRightRailButtons.tsx
+++ b/frontend/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
@@ -4,15 +4,15 @@ import { useTranslation } from "react-i18next";
import { supportedLanguages } from "@app/i18n";
import { useViewer } from "@app/contexts/ViewerContext";
import {
- useRightRailButtons,
- RightRailButtonWithAction,
-} from "@app/hooks/useRightRailButtons";
+ useWorkbenchBarButtons,
+ WorkbenchBarButtonWithAction,
+} from "@app/hooks/useWorkbenchBarButtons";
import LocalIcon from "@app/components/shared/LocalIcon";
import { Tooltip } from "@app/components/shared/Tooltip";
import { SearchInterface } from "@app/components/viewer/SearchInterface";
-import ViewerAnnotationControls from "@app/components/shared/rightRail/ViewerAnnotationControls";
+import ViewerAnnotationControls from "@app/components/viewer/ViewerAnnotationControls";
import { useSidebarContext } from "@app/contexts/SidebarContext";
-import { useRightRailTooltipSide } from "@app/hooks/useRightRailTooltipSide";
+import { useWorkbenchBarTooltipSide } from "@app/hooks/useWorkbenchBarTooltipSide";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import {
useNavigationState,
@@ -27,7 +27,7 @@ import VolumeUpIcon from "@mui/icons-material/VolumeUp";
import StopIcon from "@mui/icons-material/Stop";
import { useViewerReadAloud } from "@app/components/viewer/useViewerReadAloud";
-export function useViewerRightRailButtons(
+export function useViewerWorkbenchBarButtons(
isRulerActive?: boolean,
setIsRulerActive?: (v: boolean) => void,
) {
@@ -46,7 +46,7 @@ export function useViewerRightRailButtons(
} = viewer;
const [isPanning, setIsPanning] = useState<boolean>(false);
const { sidebarRefs } = useSidebarContext();
- const { position: tooltipPosition } = useRightRailTooltipSide(
+ const { position: tooltipPosition } = useWorkbenchBarTooltipSide(
sidebarRefs,
12,
);
@@ -105,28 +105,27 @@ export function useViewerRightRailButtons(
return () => window.removeEventListener("popstate", handlePopState);
}, [isAnnotationsPath]);
- const searchLabel = t("rightRail.search", "Search PDF");
- const panLabel = t("rightRail.panMode", "Pan Mode");
+ const searchLabel = t("workbenchBar.search", "Search PDF");
+ const panLabel = t("workbenchBar.panMode", "Pan Mode");
const applyRedactionsLabel = t(
- "rightRail.applyRedactionsFirst",
+ "workbenchBar.applyRedactionsFirst",
"Apply redactions first",
);
- const rotateLeftLabel = t("rightRail.rotateLeft", "Rotate Left");
- const rotateRightLabel = t("rightRail.rotateRight", "Rotate Right");
- const sidebarLabel = t("rightRail.toggleSidebar", "Toggle Sidebar");
- const bookmarkLabel = t("rightRail.toggleBookmarks", "Toggle Bookmarks");
+ const rotateLeftLabel = t("workbenchBar.rotateLeft", "Rotate Left");
+ const rotateRightLabel = t("workbenchBar.rotateRight", "Rotate Right");
+ const sidebarLabel = t("workbenchBar.toggleSidebar", "Toggle Sidebar");
+ const bookmarkLabel = t("workbenchBar.toggleBookmarks", "Toggle Bookmarks");
const attachmentLabel = t(
- "rightRail.toggleAttachments",
+ "workbenchBar.toggleAttachments",
"Toggle Attachments",
);
- const layersLabel = t("rightRail.toggleLayers", "Toggle Layers");
- const commentsLabel = t("rightRail.toggleComments", "Comments");
- const printLabel = t("rightRail.print", "Print PDF");
- const annotationsLabel = t("rightRail.annotations", "Annotations");
- const formFillLabel = t("rightRail.formFill", "Fill Form");
- const rulerLabel = t("rightRail.ruler", "Ruler / Measure");
- const readAloudLabel = t("rightRail.readAloud", "Read Aloud");
- const readAloudSpeedLabel = t("rightRail.readAloudSpeed", "Speed");
+ const layersLabel = t("workbenchBar.toggleLayers", "Toggle Layers");
+ const commentsLabel = t("workbenchBar.toggleComments", "Comments");
+ const annotationsLabel = t("workbenchBar.annotations", "Annotations");
+ const formFillLabel = t("workbenchBar.formFill", "Fill Form");
+ const rulerLabel = t("workbenchBar.ruler", "Ruler / Measure");
+ const readAloudLabel = t("workbenchBar.readAloud", "Read Aloud");
+ const readAloudSpeedLabel = t("workbenchBar.readAloudSpeed", "Speed");
const isFormFillActive = (selectedTool as string) === "formFill";
@@ -150,8 +149,8 @@ export function useViewerRightRailButtons(
const shouldShowLanguageSelector =
supportedLanguageCodes.size === 0 || filteredLanguages.length > 1;
- const viewerButtons = useMemo<RightRailButtonWithAction[]>(() => {
- const buttons: RightRailButtonWithAction[] = [
+ const viewerButtons = useMemo<WorkbenchBarButtonWithAction[]>(() => {
+ const buttons: WorkbenchBarButtonWithAction[] = [
{
id: "viewer-search",
tooltip: searchLabel,
@@ -179,12 +178,12 @@ export function useViewerRightRailButtons(
<ActionIcon
variant="subtle"
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
disabled={disabled}
aria-label={searchLabel}
onClick={viewer.searchInterfaceActions.toggle}
>
- <LocalIcon icon="search" width="1.5rem" height="1.5rem" />
+ <LocalIcon icon="search" width="1.25rem" height="1.25rem" />
</ActionIcon>
</div>
</Popover.Target>
@@ -203,7 +202,7 @@ export function useViewerRightRailButtons(
{
id: "viewer-pan-mode",
icon: (
- <LocalIcon icon="pan-tool-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon icon="pan-tool-rounded" width="1.25rem" height="1.25rem" />
),
tooltip:
!isPanning && pendingCount > 0 && redactionActiveType !== null
@@ -220,12 +219,16 @@ export function useViewerRightRailButtons(
!isPanning && pendingCount > 0 && redactionActiveType !== null,
onClick: () => {
viewer.panActions.togglePan();
- setIsPanning((prev) => !prev);
+ setIsPanning((prev) => {
+ const next = !prev;
+ if (next && isRulerActive) setIsRulerActive?.(false);
+ return next;
+ });
},
},
{
id: "viewer-ruler",
- icon: <StraightenIcon sx={{ fontSize: "1.5rem" }} />,
+ icon: <StraightenIcon sx={{ fontSize: "1.25rem" }} />,
tooltip: rulerLabel,
ariaLabel: rulerLabel,
section: "top" as const,
@@ -236,12 +239,13 @@ export function useViewerRightRailButtons(
setIsRulerActive?.(next);
if (next && isPanning) {
viewer.panActions.disablePan();
+ setIsPanning(false);
}
},
},
{
id: "viewer-rotate-left",
- icon: <LocalIcon icon="rotate-left" width="1.5rem" height="1.5rem" />,
+ icon: <LocalIcon icon="rotate-left" width="1.25rem" height="1.25rem" />,
tooltip: rotateLeftLabel,
ariaLabel: rotateLeftLabel,
section: "top" as const,
@@ -252,7 +256,9 @@ export function useViewerRightRailButtons(
},
{
id: "viewer-rotate-right",
- icon: <LocalIcon icon="rotate-right" width="1.5rem" height="1.5rem" />,
+ icon: (
+ <LocalIcon icon="rotate-right" width="1.25rem" height="1.25rem" />
+ ),
tooltip: rotateRightLabel,
ariaLabel: rotateRightLabel,
section: "top" as const,
@@ -263,7 +269,7 @@ export function useViewerRightRailButtons(
},
{
id: "viewer-toggle-sidebar",
- icon: <LocalIcon icon="view-list" width="1.5rem" height="1.5rem" />,
+ icon: <LocalIcon icon="view-list" width="1.25rem" height="1.25rem" />,
tooltip: sidebarLabel,
ariaLabel: sidebarLabel,
section: "top" as const,
@@ -278,8 +284,8 @@ export function useViewerRightRailButtons(
icon: (
<LocalIcon
icon="bookmark-add-rounded"
- width="1.5rem"
- height="1.5rem"
+ width="1.25rem"
+ height="1.25rem"
/>
),
tooltip: bookmarkLabel,
@@ -294,7 +300,11 @@ export function useViewerRightRailButtons(
{
id: "viewer-toggle-attachments",
icon: (
- <LocalIcon icon="attachment-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="attachment-rounded"
+ width="1.25rem"
+ height="1.25rem"
+ />
),
tooltip: attachmentLabel,
ariaLabel: attachmentLabel,
@@ -309,7 +319,7 @@ export function useViewerRightRailButtons(
? [
{
id: "viewer-toggle-layers",
- icon: <LayersIcon sx={{ fontSize: "1.5rem" }} />,
+ icon: <LayersIcon sx={{ fontSize: "1.25rem" }} />,
tooltip: layersLabel,
ariaLabel: layersLabel,
section: "top" as const,
@@ -323,7 +333,7 @@ export function useViewerRightRailButtons(
: []),
{
id: "viewer-toggle-comments",
- icon: <LocalIcon icon="comment" width="1.5rem" height="1.5rem" />,
+ icon: <LocalIcon icon="comment" width="1.25rem" height="1.25rem" />,
tooltip: commentsLabel,
ariaLabel: commentsLabel,
section: "top" as const,
@@ -333,17 +343,6 @@ export function useViewerRightRailButtons(
toggleCommentsSidebar();
},
},
- {
- id: "viewer-print",
- icon: <LocalIcon icon="print" width="1.5rem" height="1.5rem" />,
- tooltip: printLabel,
- ariaLabel: printLabel,
- section: "top" as const,
- order: 57,
- onClick: () => {
- viewer.printActions.print();
- },
- },
{
id: "viewer-read-aloud",
tooltip: readAloudLabel,
@@ -373,7 +372,7 @@ export function useViewerRightRailButtons(
<ActionIcon
variant={isReadingAloud ? "filled" : "subtle"}
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
disabled={
disabled ||
typeof window === "undefined" ||
@@ -384,9 +383,9 @@ export function useViewerRightRailButtons(
color={isReadingAloud ? "blue" : undefined}
>
{isReadingAloud ? (
- <StopIcon sx={{ fontSize: "1.5rem" }} />
+ <StopIcon sx={{ fontSize: "1.25rem" }} />
) : (
- <VolumeUpIcon sx={{ fontSize: "1.5rem" }} />
+ <VolumeUpIcon sx={{ fontSize: "1.25rem" }} />
)}
</ActionIcon>
</Tooltip>
@@ -421,9 +420,9 @@ export function useViewerRightRailButtons(
/>
{shouldShowLanguageSelector && (
<Select
- label={t("rightRail.readAloudLanguage", "Language")}
+ label={t("workbenchBar.readAloudLanguage", "Language")}
placeholder={t(
- "rightRail.selectLanguage",
+ "workbenchBar.selectLanguage",
"Select language",
)}
value={speechLanguage}
@@ -461,7 +460,7 @@ export function useViewerRightRailButtons(
<ActionIcon
variant={isAnnotationsActive ? "filled" : "subtle"}
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
onClick={() => {
if (disabled || isAnnotationsActive) return;
@@ -489,7 +488,7 @@ export function useViewerRightRailButtons(
aria-pressed={isAnnotationsActive}
color={isAnnotationsActive ? "blue" : undefined}
>
- <LocalIcon icon="edit" width="1.5rem" height="1.5rem" />
+ <LocalIcon icon="edit" width="1.25rem" height="1.25rem" />
</ActionIcon>
</Tooltip>
),
@@ -519,7 +518,7 @@ export function useViewerRightRailButtons(
<ActionIcon
variant={isFormFillActive ? "filled" : "subtle"}
radius="md"
- className="right-rail-icon"
+ className="workbench-bar-action-icon"
onClick={() => {
if (disabled) return;
if (isFormFillActive) {
@@ -532,7 +531,7 @@ export function useViewerRightRailButtons(
aria-pressed={isFormFillActive}
color={isFormFillActive ? "blue" : undefined}
>
- <TextFieldsIcon sx={{ fontSize: "1.5rem" }} />
+ <TextFieldsIcon sx={{ fontSize: "1.25rem" }} />
</ActionIcon>
</Tooltip>
),
@@ -560,7 +559,6 @@ export function useViewerRightRailButtons(
bookmarkLabel,
attachmentLabel,
layersLabel,
- printLabel,
tooltipPosition,
annotationsLabel,
isAnnotationsActive,
@@ -586,5 +584,5 @@ export function useViewerRightRailButtons(
handleSpeechLanguageChange,
]);
- useRightRailButtons(viewerButtons);
+ useWorkbenchBarButtons(viewerButtons);
}
diff --git a/frontend/src/core/contexts/FileContext.tsx b/frontend/src/core/contexts/FileContext.tsx
index c7f1fbee2b..0bfeff476c 100644
--- a/frontend/src/core/contexts/FileContext.tsx
+++ b/frontend/src/core/contexts/FileContext.tsx
@@ -480,7 +480,7 @@ function FileContextInner({
const allIds = [activeEncryptedFileId, ...encryptedQueue];
let successCount = 0;
- const failedNames: string[] = [];
+ const failedIds: FileId[] = [];
for (const fileId of allIds) {
try {
@@ -488,8 +488,7 @@ function FileContextInner({
dismissedEncryptedFilesRef.current.delete(fileId);
successCount++;
} catch {
- const name = stateRef.current.files.byId[fileId]?.name ?? fileId;
- failedNames.push(name);
+ failedIds.push(fileId);
}
}
@@ -506,17 +505,16 @@ function FileContextInner({
});
}
- if (failedNames.length > 0) {
+ if (failedIds.length > 0) {
+ const failedNames = failedIds.map(
+ (id) => stateRef.current.files.byId[id]?.name ?? id,
+ );
setUnlockError(
t("encryptedPdfUnlock.unlockAllPartialFail", {
defaultValue: "Wrong password for: {{names}}",
names: failedNames.join(", "),
}),
);
- const failedIds = allIds.filter((id) => {
- const name = stateRef.current.files.byId[id]?.name ?? id;
- return failedNames.includes(name);
- });
setEncryptedQueue(failedIds.slice(1));
setActiveEncryptedFileId(failedIds[0]);
} else {
diff --git a/frontend/src/core/contexts/FileManagerContext.tsx b/frontend/src/core/contexts/FileManagerContext.tsx
index 07bcd0924b..5e8bcf93ca 100644
--- a/frontend/src/core/contexts/FileManagerContext.tsx
+++ b/frontend/src/core/contexts/FileManagerContext.tsx
@@ -9,7 +9,7 @@ import React, {
} from "react";
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
import { fileStorage } from "@app/services/fileStorage";
-import { useFileActions } from "@app/contexts/FileContext";
+import { useFileActions, useFileManagement } from "@app/contexts/FileContext";
import { zipFileService } from "@app/services/zipFileService";
import { StirlingFileStub } from "@app/types/fileContext";
import { downloadFiles } from "@app/utils/downloadUtils";
@@ -91,10 +91,12 @@ interface FileManagerProviderProps {
isFileSupported: (fileName: string) => boolean;
isOpen: boolean;
onFileRemove: (index: number) => void;
+ onBulkRemove?: (fileIds: FileId[]) => void;
modalHeight: string;
refreshRecentFiles: () => Promise<void>;
isLoading: boolean;
activeFileIds: FileId[];
+ maxSelectable?: number | null;
}
type RemoteDeleteChoice = "local" | "server" | "both" | "leave" | "cancel";
@@ -108,10 +110,12 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
isFileSupported,
isOpen,
onFileRemove,
+ onBulkRemove,
modalHeight,
refreshRecentFiles,
isLoading,
activeFileIds,
+ maxSelectable = null,
}) => {
const [activeSource, setActiveSource] = useState<
"recent" | "local" | "drive"
@@ -119,7 +123,9 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
const [storageFilter, setStorageFilter] = useState<
"all" | "local" | "sharedWithMe" | "sharedByMe"
>("all");
- const [selectedFileIds, setSelectedFileIds] = useState<FileId[]>([]);
+ const [selectedFileIds, setSelectedFileIds] = useState<FileId[]>(
+ () => activeFileIds,
+ );
const [searchTerm, setSearchTerm] = useState("");
const [lastClickedIndex, setLastClickedIndex] = useState<number | null>(null);
const [expandedFileIds, setExpandedFileIds] = useState<Set<FileId>>(
@@ -136,6 +142,14 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
>(null);
const { t } = useTranslation();
const { actions } = useFileActions();
+ const { removeFiles } = useFileManagement();
+
+ // Re-seed selection with active file IDs each time the modal opens
+ useEffect(() => {
+ if (isOpen) {
+ setSelectedFileIds(activeFileIds);
+ }
+ }, [isOpen, activeFileIds]);
// Track blob URLs for cleanup
const createdBlobUrls = useRef<Set<string>>(new Set());
@@ -284,6 +298,11 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
selectedSet.delete(fileId);
} else {
selectedSet.add(fileId);
+ // Enforce maxSelectable: drop the oldest selection if over the limit
+ if (maxSelectable != null && selectedSet.size > maxSelectable) {
+ const [oldest] = selectedSet;
+ selectedSet.delete(oldest);
+ }
}
return Array.from(selectedSet);
@@ -293,7 +312,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
setLastClickedIndex(currentIndex);
}
},
- [filteredFiles, lastClickedIndex],
+ [filteredFiles, lastClickedIndex, maxSelectable],
);
// Helper function to safely determine which files can be deleted
@@ -389,7 +408,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
// Shared internal delete logic
const performFileDelete = useCallback(
- async (fileToRemove: StirlingFileStub, fileIndex: number) => {
+ async (fileToRemove: StirlingFileStub) => {
let deleteChoice: RemoteDeleteChoice = "local";
if (fileToRemove.remoteStorageId) {
deleteChoice = await requestDeleteChoice(fileToRemove);
@@ -548,8 +567,8 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
console.error("Failed to delete files from chain:", error);
}
- // Call the parent's deletion logic for the main file only
- onFileRemove(fileIndex);
+ // ID-based removal avoids stale index issues when multiple server files are deleted sequentially.
+ onBulkRemove?.(filesToDelete as FileId[]);
// Refresh to ensure consistent state
await refreshRecentFiles();
@@ -559,7 +578,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
setSelectedFileIds,
setExpandedFileIds,
setLoadedHistoryFiles,
- onFileRemove,
+ onBulkRemove,
refreshRecentFiles,
requestDeleteChoice,
t,
@@ -570,7 +589,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
async (index: number) => {
const fileToRemove = filteredFiles[index];
if (fileToRemove) {
- await performFileDelete(fileToRemove, index);
+ await performFileDelete(fileToRemove);
}
},
[filteredFiles, performFileDelete],
@@ -584,7 +603,7 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
const fileToRemove = filteredFiles[fileIndex];
if (fileToRemove && fileIndex !== -1) {
- await performFileDelete(fileToRemove, fileIndex);
+ await performFileDelete(fileToRemove);
}
},
[filteredFiles, performFileDelete],
@@ -646,11 +665,34 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
);
const handleOpenFiles = useCallback(() => {
- if (selectedFiles.length > 0) {
- onRecentFilesSelected(selectedFiles);
- onClose();
+ // Remove active files that were unchecked, skipping files with unsaved changes
+ const uncheckedActiveIds = activeFileIds.filter((id) => {
+ if (selectedFilesSet.has(id)) return false;
+ const stub = filteredFiles.find((f) => f.id === id);
+ return !stub?.isDirty;
+ });
+ if (uncheckedActiveIds.length > 0) {
+ removeFiles(uncheckedActiveIds, false);
}
- }, [selectedFiles, onRecentFilesSelected, onClose]);
+
+ // Add newly checked files (not already active)
+ const newlySelected = selectedFiles.filter(
+ (f) => !activeFileIds.includes(f.id),
+ );
+ if (newlySelected.length > 0) {
+ onRecentFilesSelected(newlySelected);
+ }
+
+ onClose();
+ }, [
+ selectedFiles,
+ selectedFilesSet,
+ activeFileIds,
+ filteredFiles,
+ removeFiles,
+ onRecentFilesSelected,
+ onClose,
+ ]);
const handleSearchChange = useCallback((value: string) => {
setSearchTerm(value);
@@ -683,24 +725,91 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
setSelectedFileIds([]);
setLastClickedIndex(null);
} else {
- // Select all filtered files
- setSelectedFileIds(filteredFiles.map((file) => file.id).filter(Boolean));
+ // Select all filtered files, capped at maxSelectable
+ const allIds = filteredFiles
+ .map((file) => file.id)
+ .filter(Boolean) as FileId[];
+ setSelectedFileIds(
+ maxSelectable != null ? allIds.slice(0, maxSelectable) : allIds,
+ );
setLastClickedIndex(null);
}
- }, [filteredFiles, selectedFileIds]);
+ }, [filteredFiles, selectedFileIds, maxSelectable]);
const handleDeleteSelected = useCallback(async () => {
if (selectedFileIds.length === 0) return;
- try {
- // Delete each selected file using the proven single delete logic
- for (const fileId of selectedFileIds) {
- await handleFileRemoveById(fileId);
+ // Split into server files (need modal prompts) and local files (bulk path).
+ const serverFiles = selectedFileIds
+ .map((id) => filteredFiles.find((f) => f.id === id))
+ .filter((f): f is StirlingFileStub => !!f && !!f.remoteStorageId);
+
+ const localIds = selectedFileIds.filter((id) => {
+ const f = filteredFiles.find((ff) => ff.id === id);
+ return f && !f.remoteStorageId;
+ }) as FileId[];
+
+ // Server files — sequential, each may need a modal prompt.
+ for (const file of serverFiles) {
+ await performFileDelete(file);
+ }
+
+ // Local files — single IDB transaction, one UI update.
+ if (localIds.length > 0) {
+ try {
+ const allStoredStubs = await fileStorage.getAllStirlingFileStubs();
+ const safeIds = getSafeFilesToDelete(
+ localIds,
+ allStoredStubs,
+ ) as FileId[];
+ const safeIdSet = new Set(safeIds);
+
+ // Clear UI state in one pass.
+ setSelectedFileIds((prev) => prev.filter((id) => !safeIdSet.has(id)));
+ setExpandedFileIds((prev) => {
+ const next = new Set(prev);
+ safeIds.forEach((id) => next.delete(id));
+ return next;
+ });
+ setLoadedHistoryFiles((prev) => {
+ const next = new Map(prev);
+ safeIds.forEach((id) => next.delete(id));
+ for (const [mainId, histFiles] of next.entries()) {
+ const filtered = histFiles.filter((h) => !safeIdSet.has(h.id));
+ if (filtered.length !== histFiles.length)
+ next.set(mainId, filtered);
+ }
+ return next;
+ });
+
+ // Optimistic UI update.
+ onBulkRemove?.(safeIds);
+
+ // Remove from workbench.
+ removeFiles(safeIds, false);
+
+ // Single-transaction IDB delete, then refresh.
+ fileStorage
+ .deleteMultipleStirlingFiles(safeIds)
+ .then(() => refreshRecentFiles())
+ .catch((error) => {
+ console.error("Failed to bulk delete files from IndexedDB:", error);
+ refreshRecentFiles();
+ });
+ } catch (error) {
+ console.error("Failed to bulk delete local files:", error);
+ await refreshRecentFiles();
}
- } catch (error) {
- console.error("Failed to delete selected files:", error);
}
- }, [selectedFileIds, handleFileRemoveById]);
+ }, [
+ selectedFileIds,
+ filteredFiles,
+ performFileDelete,
+ getSafeFilesToDelete,
+ removeFiles,
+ refreshRecentFiles,
+ onBulkRemove,
+ ]);
const handleDownloadSelected = useCallback(async () => {
if (selectedFileIds.length === 0) return;
diff --git a/frontend/src/core/contexts/FilesModalContext.tsx b/frontend/src/core/contexts/FilesModalContext.tsx
index aec1915954..9d9bf0bd52 100644
--- a/frontend/src/core/contexts/FilesModalContext.tsx
+++ b/frontend/src/core/contexts/FilesModalContext.tsx
@@ -8,6 +8,10 @@ import React, {
import { useFileHandler } from "@app/hooks/useFileHandler";
import { useFileActions } from "@app/contexts/FileContext";
import { useFileContext } from "@app/contexts/file/fileHooks";
+import {
+ useNavigationActions,
+ useNavigationState,
+} from "@app/contexts/NavigationContext";
import { StirlingFileStub } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
import { fileStorage } from "@app/services/fileStorage";
@@ -26,8 +30,10 @@ interface FilesModalContextType {
openFilesModal: (options?: {
insertAfterPage?: number;
customHandler?: (files: File[], insertAfterPage?: number) => void;
+ maxSelectable?: number | null;
}) => void;
closeFilesModal: () => void;
+ maxSelectable: number | null;
onFileUpload: (files: File[]) => void;
onRecentFileSelect: (stirlingFileStubs: StirlingFileStub[]) => void;
onModalClose?: () => void;
@@ -42,12 +48,17 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
const { addFiles } = useFileHandler();
const { actions } = useFileActions();
const fileCtx = useFileContext();
+ const { actions: navActions } = useNavigationActions();
+ const { workbench: currentWorkbench, selectedTool } = useNavigationState();
+ const isMultiTool =
+ currentWorkbench === "pageEditor" && selectedTool === "multiTool";
const [isFilesModalOpen, setIsFilesModalOpen] = useState(false);
const [onModalClose, setOnModalClose] = useState<(() => void) | undefined>();
const [insertAfterPage, setInsertAfterPage] = useState<number | undefined>();
const [customHandler, setCustomHandler] = useState<
((files: File[], insertAfterPage?: number) => void) | undefined
>();
+ const [maxSelectable, setMaxSelectable] = useState<number | null>(null);
const importBundleToWorkbench = useCallback(
async (
@@ -220,9 +231,11 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
(options?: {
insertAfterPage?: number;
customHandler?: (files: File[], insertAfterPage?: number) => void;
+ maxSelectable?: number | null;
}) => {
setInsertAfterPage(options?.insertAfterPage);
setCustomHandler(() => options?.customHandler);
+ setMaxSelectable(options?.maxSelectable ?? null);
setIsFilesModalOpen(true);
},
[],
@@ -238,7 +251,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
const handleFileUpload = useCallback(
async (files: File[]) => {
if (customHandler) {
- // Use custom handler for special cases (like page insertion)
+ // Use custom handler for special cases (like page insertion) — no auto-navigation
customHandler(files, insertAfterPage);
} else {
// 1) Add via standard flow (auto-selects new files)
@@ -256,6 +269,10 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
);
actions.setSelectedFiles(nextSelection);
}
+ // Stay in multi-tool; otherwise single file → viewer, multiple → active files
+ if (!isMultiTool) {
+ navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");
+ }
}
closeFilesModal();
},
@@ -266,6 +283,8 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
customHandler,
actions,
fileCtx,
+ navActions,
+ isMultiTool,
],
);
@@ -397,6 +416,12 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
console.error("addStirlingFileStubs action not available");
}
+ // Stay in multi-tool; otherwise single file → viewer, multiple → active files
+ if (!isMultiTool) {
+ const totalAdded = stirlingFileStubs.length;
+ navActions.setWorkbench(totalAdded === 1 ? "viewer" : "fileEditor");
+ }
+
closeFilesModal();
},
[
@@ -410,6 +435,8 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
downloadShareLinkFile,
extractLatestFilesFromBundle,
importBundleToWorkbench,
+ navActions,
+ isMultiTool,
],
);
@@ -426,6 +453,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
onRecentFileSelect: handleRecentFileSelect,
onModalClose,
setOnModalClose: setModalCloseCallback,
+ maxSelectable,
}),
[
isFilesModalOpen,
@@ -435,6 +463,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
handleRecentFileSelect,
onModalClose,
setModalCloseCallback,
+ maxSelectable,
],
);
diff --git a/frontend/src/core/contexts/IndexedDBContext.tsx b/frontend/src/core/contexts/IndexedDBContext.tsx
index e2c8315aa0..dffdaeb50b 100644
--- a/frontend/src/core/contexts/IndexedDBContext.tsx
+++ b/frontend/src/core/contexts/IndexedDBContext.tsx
@@ -3,7 +3,13 @@
* Integrates with FileContext to provide transparent file persistence
*/
-import React, { createContext, useContext, useCallback, useRef } from "react";
+import React, {
+ createContext,
+ useContext,
+ useCallback,
+ useRef,
+ useState,
+} from "react";
import { fileStorage } from "@app/services/fileStorage";
import { FileId } from "@app/types/file";
import {
@@ -40,6 +46,10 @@ interface IndexedDBContextValue {
}>;
updateThumbnail: (fileId: FileId, thumbnail: string) => Promise<boolean>;
markFileAsProcessed: (fileId: FileId) => Promise<boolean>;
+
+ // Incremented after any write or delete — subscribe to trigger re-reads
+ revision: number;
+ bumpRevision: () => void;
}
const IndexedDBContext = createContext<IndexedDBContextValue | null>(null);
@@ -49,6 +59,9 @@ interface IndexedDBProviderProps {
}
export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
+ const [revision, setRevision] = useState(0);
+ const bumpRevision = useCallback(() => setRevision((r) => r + 1), []);
+
// LRU File cache to avoid repeated ArrayBuffer→File conversions
const fileCache = useRef(
new Map<FileId, { file: File; lastAccessed: number }>(),
@@ -79,11 +92,13 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
fileId: FileId,
existingThumbnail?: string,
): Promise<StirlingFileStub> => {
- // Use existing thumbnail or generate new one if none provided
- const thumbnail =
- existingThumbnail || (await generateThumbnailForFile(file));
+ // existingThumbnail="" means caller explicitly opted out of a raster thumbnail;
+ // only generate when the caller passed nothing (undefined).
+ const generated =
+ existingThumbnail ?? (await generateThumbnailForFile(file));
+ const thumbnail = generated || undefined;
- // Store in IndexedDB (no history data - that's handled by direct fileStorage calls now)
+ // History is handled via direct fileStorage calls, not here
const stirlingFile = createStirlingFile(file, fileId);
// Create minimal stub for storage
@@ -116,9 +131,10 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
);
}
+ bumpRevision();
return storedFile;
},
- [],
+ [bumpRevision],
);
const loadFile = useCallback(
@@ -155,13 +171,17 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
[],
);
- const deleteFile = useCallback(async (fileId: FileId): Promise<void> => {
- // Remove from cache
- fileCache.current.delete(fileId);
+ const deleteFile = useCallback(
+ async (fileId: FileId): Promise<void> => {
+ // Remove from cache
+ fileCache.current.delete(fileId);
- // Remove from IndexedDB
- await fileStorage.deleteStirlingFile(fileId);
- }, []);
+ // Remove from IndexedDB
+ await fileStorage.deleteStirlingFile(fileId);
+ bumpRevision();
+ },
+ [bumpRevision],
+ );
const loadLeafMetadata = useCallback(async (): Promise<
StirlingFileStub[]
@@ -184,12 +204,11 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
// Remove from cache
fileIds.forEach((id) => fileCache.current.delete(id));
- // Remove from IndexedDB in parallel
- await Promise.all(
- fileIds.map((id) => fileStorage.deleteStirlingFile(id)),
- );
+ // Delete all in a single IDB transaction
+ await fileStorage.deleteMultipleStirlingFiles(fileIds);
+ bumpRevision();
},
- [],
+ [bumpRevision],
);
const clearAll = useCallback(async (): Promise<void> => {
@@ -198,7 +217,8 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
// Clear IndexedDB
await fileStorage.clearAll();
- }, []);
+ bumpRevision();
+ }, [bumpRevision]);
const getStorageStats = useCallback(async () => {
return await fileStorage.getStorageStats();
@@ -206,16 +226,20 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
const updateThumbnail = useCallback(
async (fileId: FileId, thumbnail: string): Promise<boolean> => {
- return await fileStorage.updateThumbnail(fileId, thumbnail);
+ const result = await fileStorage.updateThumbnail(fileId, thumbnail);
+ if (result) bumpRevision();
+ return result;
},
- [],
+ [bumpRevision],
);
const markFileAsProcessed = useCallback(
async (fileId: FileId): Promise<boolean> => {
- return await fileStorage.markFileAsProcessed(fileId);
+ const result = await fileStorage.markFileAsProcessed(fileId);
+ if (result) bumpRevision();
+ return result;
},
- [],
+ [bumpRevision],
);
const value: IndexedDBContextValue = {
@@ -230,6 +254,8 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
getStorageStats,
updateThumbnail,
markFileAsProcessed,
+ revision,
+ bumpRevision,
};
return (
diff --git a/frontend/src/core/contexts/PageEditorContext.tsx b/frontend/src/core/contexts/PageEditorContext.tsx
index 0386ab2421..330ec8fb08 100644
--- a/frontend/src/core/contexts/PageEditorContext.tsx
+++ b/frontend/src/core/contexts/PageEditorContext.tsx
@@ -214,6 +214,8 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
return [...validOrder, ...newIds];
});
clearPersistedDocument();
+ // Select all workbench files so they render as expanded pages
+ fileActions.setSelectedFiles(state.files.ids);
}
prevWorkbenchRef.current = nextWorkbench;
@@ -223,6 +225,7 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
state.files.ids,
setFileOrder,
setReorderedPages,
+ fileActions,
]);
const fileContextSignature = useMemo(() => {
diff --git a/frontend/src/core/contexts/RightRailContext.tsx b/frontend/src/core/contexts/RightRailContext.tsx
deleted file mode 100644
index 331292b3cd..0000000000
--- a/frontend/src/core/contexts/RightRailContext.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import React, {
- createContext,
- useCallback,
- useContext,
- useMemo,
- useState,
-} from "react";
-import { RightRailAction, RightRailButtonConfig } from "@app/types/rightRail";
-
-interface RightRailContextValue {
- buttons: RightRailButtonConfig[];
- actions: Record<string, RightRailAction>;
- allButtonsDisabled: boolean;
- registerButtons: (buttons: RightRailButtonConfig[]) => void;
- unregisterButtons: (ids: string[]) => void;
- setAction: (id: string, action?: RightRailAction) => void;
- setAllRightRailButtonsDisabled: (disabled: boolean) => void;
- clear: () => void;
-}
-
-const RightRailContext = createContext<RightRailContextValue | undefined>(
- undefined,
-);
-
-export function RightRailProvider({ children }: { children: React.ReactNode }) {
- const [buttons, setButtons] = useState<RightRailButtonConfig[]>([]);
- const [actions, setActions] = useState<Record<string, RightRailAction>>({});
- const [allButtonsDisabled, setAllButtonsDisabled] = useState<boolean>(false);
-
- const registerButtons = useCallback((newButtons: RightRailButtonConfig[]) => {
- setButtons((prev) => {
- const byId = new Map(prev.map((b) => [b.id, b] as const));
- newButtons.forEach((nb) => {
- const existing = byId.get(nb.id) || ({} as RightRailButtonConfig);
- byId.set(nb.id, { ...existing, ...nb });
- });
- const merged = Array.from(byId.values());
- merged.sort(
- (a, b) => (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id),
- );
- if (process.env.NODE_ENV === "development") {
- const ids = newButtons.map((b) => b.id);
- const dupes = ids.filter((id, idx) => ids.indexOf(id) !== idx);
- if (dupes.length)
- console.warn("[RightRail] Duplicate ids in registerButtons:", dupes);
- }
- return merged;
- });
- }, []);
-
- const unregisterButtons = useCallback((ids: string[]) => {
- setButtons((prev) => prev.filter((b) => !ids.includes(b.id)));
- setActions((prev) =>
- Object.fromEntries(
- Object.entries(prev).filter(([id]) => !ids.includes(id)),
- ),
- );
- }, []);
-
- const setAction = useCallback((id: string, action?: RightRailAction) => {
- setActions((prev) => {
- if (!action) {
- if (!(id in prev)) return prev;
- const next = { ...prev };
- delete next[id];
- return next;
- }
- return { ...prev, [id]: action };
- });
- }, []);
-
- const setAllRightRailButtonsDisabled = useCallback((disabled: boolean) => {
- setAllButtonsDisabled(disabled);
- }, []);
-
- const clear = useCallback(() => {
- setButtons([]);
- setActions({});
- }, []);
-
- const value = useMemo<RightRailContextValue>(
- () => ({
- buttons,
- actions,
- allButtonsDisabled,
- registerButtons,
- unregisterButtons,
- setAction,
- setAllRightRailButtonsDisabled,
- clear,
- }),
- [
- buttons,
- actions,
- allButtonsDisabled,
- registerButtons,
- unregisterButtons,
- setAction,
- setAllRightRailButtonsDisabled,
- clear,
- ],
- );
-
- return (
- <RightRailContext.Provider value={value}>
- {children}
- </RightRailContext.Provider>
- );
-}
-
-export function useRightRail() {
- const ctx = useContext(RightRailContext);
- if (!ctx)
- throw new Error("useRightRail must be used within RightRailProvider");
- return ctx;
-}
diff --git a/frontend/src/core/contexts/SidebarContext.tsx b/frontend/src/core/contexts/SidebarContext.tsx
index 9099c436e9..ac9ddbb0df 100644
--- a/frontend/src/core/contexts/SidebarContext.tsx
+++ b/frontend/src/core/contexts/SidebarContext.tsx
@@ -14,7 +14,6 @@ export function SidebarProvider({ children }: SidebarProviderProps) {
// All sidebar state management
const quickAccessRef = useRef<HTMLDivElement>(null);
const toolPanelRef = useRef<HTMLDivElement>(null);
- const rightRailRef = useRef<HTMLDivElement>(null);
const [sidebarsVisible, setSidebarsVisible] = useState(true);
const [leftPanelView, setLeftPanelView] = useState<
@@ -35,9 +34,8 @@ export function SidebarProvider({ children }: SidebarProviderProps) {
() => ({
quickAccessRef,
toolPanelRef,
- rightRailRef,
}),
- [quickAccessRef, toolPanelRef, rightRailRef],
+ [quickAccessRef, toolPanelRef],
);
const contextValue: SidebarContextValue = useMemo(
diff --git a/frontend/src/core/contexts/ToolWorkflowContext.tsx b/frontend/src/core/contexts/ToolWorkflowContext.tsx
index bf410c11b6..60f4124aaf 100644
--- a/frontend/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/src/core/contexts/ToolWorkflowContext.tsx
@@ -355,6 +355,29 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
setLeftPanelView,
]);
+ // When in multi-tool, sync left panel visibility with workbench:
+ // hide the panel on pageEditor, show it when navigating to viewer/fileEditor.
+ const prevMultiToolWorkbenchRef = React.useRef<WorkbenchType | null>(null);
+ useEffect(() => {
+ const prev = prevMultiToolWorkbenchRef.current;
+ prevMultiToolWorkbenchRef.current = navigationState.workbench;
+
+ if (navigationState.selectedTool !== "multiTool") return;
+
+ if (navigationState.workbench === "pageEditor" && prev !== "pageEditor") {
+ setLeftPanelView("hidden");
+ } else if (
+ navigationState.workbench !== "pageEditor" &&
+ prev === "pageEditor"
+ ) {
+ setLeftPanelView("toolPicker");
+ }
+ }, [
+ navigationState.workbench,
+ navigationState.selectedTool,
+ setLeftPanelView,
+ ]);
+
// Tool reset methods
const registerToolReset = useCallback(
(toolId: string, resetFunction: () => void) => {
diff --git a/frontend/src/core/contexts/TourOrchestrationContext.tsx b/frontend/src/core/contexts/TourOrchestrationContext.tsx
index 1a338b6b59..eca4229755 100644
--- a/frontend/src/core/contexts/TourOrchestrationContext.tsx
+++ b/frontend/src/core/contexts/TourOrchestrationContext.tsx
@@ -30,6 +30,7 @@ interface TourOrchestrationContextType {
// File operations
selectFirstFile: () => void;
pinFile: () => void;
+ revealFileCardHoverMenu: () => void;
// Crop settings (placeholder for now)
modifyCropSettings: () => void;
@@ -192,6 +193,20 @@ export const TourOrchestrationProvider: React.FC<{
window.dispatchEvent(event);
}, []);
+ const revealFileCardHoverMenu = useCallback(() => {
+ // The hover menu is hidden via CSS until the card is hovered.
+ // Override data-force-visible so the CSS rule makes it opacity:1 / pointer-events:auto,
+ // then nudge Reactour to re-measure the now-visible pin button.
+ const menu = document.querySelector(
+ '[data-hover-action-menu-mode="cssHover"]',
+ ) as HTMLElement | null;
+ if (menu) {
+ menu.setAttribute("data-force-visible", "true");
+ window.dispatchEvent(new Event("resize"));
+ requestAnimationFrame(() => window.dispatchEvent(new Event("resize")));
+ }
+ }, []);
+
const executeTool = useCallback(() => {
// Trigger the run button click
const runButton = document.querySelector(
@@ -213,6 +228,7 @@ export const TourOrchestrationProvider: React.FC<{
switchToActiveFiles,
selectFirstFile,
pinFile,
+ revealFileCardHoverMenu,
modifyCropSettings,
executeTool,
};
diff --git a/frontend/src/core/contexts/ViewerContext.tsx b/frontend/src/core/contexts/ViewerContext.tsx
index 4a6931b7c8..176b11271b 100644
--- a/frontend/src/core/contexts/ViewerContext.tsx
+++ b/frontend/src/core/contexts/ViewerContext.tsx
@@ -2,11 +2,15 @@ import React, {
createContext,
useContext,
useState,
+ useMemo,
+ useEffect,
ReactNode,
useRef,
useCallback,
} from "react";
import { useNavigation } from "@app/contexts/NavigationContext";
+import { useFileState } from "@app/contexts/FileContext";
+import { isStirlingFile } from "@app/types/fileContext";
import {
preferencesService,
type PdfRenderMode,
@@ -233,7 +237,35 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
const [isAnnotationsVisible, setIsAnnotationsVisible] = useState(true);
const [isAnnotationMode, setIsAnnotationModeState] = useState(false);
const [activeFileId, setActiveFileId] = useState<string | null>(null);
- const [activeFileIndex, setActiveFileIndex] = useState(0);
+
+ // activeFileIndex is derived from activeFileId so they can never desync.
+ // ViewerProvider sits inside FileContextProvider so useFileState is valid here.
+ const { selectors, state } = useFileState();
+
+ // Clear activeFileId when its file is removed from the workbench.
+ // Dep on state.files.ids so the effect re-runs on every add/remove.
+ useEffect(() => {
+ if (!activeFileId) return;
+ const stillInWorkbench = state.files.ids.some(
+ (id) => (id as string) === activeFileId,
+ );
+ if (!stillInWorkbench) setActiveFileId(null);
+ }, [activeFileId, state.files.ids]);
+
+ const activeFileIndex = useMemo(() => {
+ if (!activeFileId) return 0;
+ const files = selectors.getFiles();
+ const idx = files.findIndex((f) => f.fileId === activeFileId);
+ return idx >= 0 ? idx : 0;
+ }, [activeFileId, selectors]);
+ const setActiveFileIndex = useCallback(
+ (index: number) => {
+ const files = selectors.getFiles();
+ const file = files[index];
+ if (file && isStirlingFile(file)) setActiveFileId(file.fileId);
+ },
+ [selectors],
+ );
const [pdfRenderMode, setPdfRenderModeState] = useState<PdfRenderMode>(() =>
preferencesService.getPreference("pdfRenderMode"),
);
diff --git a/frontend/src/core/contexts/WorkbenchBarContext.tsx b/frontend/src/core/contexts/WorkbenchBarContext.tsx
new file mode 100644
index 0000000000..4c1e7198ab
--- /dev/null
+++ b/frontend/src/core/contexts/WorkbenchBarContext.tsx
@@ -0,0 +1,132 @@
+import React, {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+import {
+ WorkbenchBarAction,
+ WorkbenchBarButtonConfig,
+} from "@app/types/workbenchBar";
+
+interface WorkbenchBarContextValue {
+ buttons: WorkbenchBarButtonConfig[];
+ actions: Record<string, WorkbenchBarAction>;
+ allButtonsDisabled: boolean;
+ registerButtons: (buttons: WorkbenchBarButtonConfig[]) => void;
+ unregisterButtons: (ids: string[]) => void;
+ setAction: (id: string, action?: WorkbenchBarAction) => void;
+ setAllButtonsDisabled: (disabled: boolean) => void;
+ clear: () => void;
+}
+
+const WorkbenchBarContext = createContext<WorkbenchBarContextValue | undefined>(
+ undefined,
+);
+
+export function WorkbenchBarProvider({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const [buttons, setButtons] = useState<WorkbenchBarButtonConfig[]>([]);
+ const [actions, setActions] = useState<Record<string, WorkbenchBarAction>>(
+ {},
+ );
+ const [allButtonsDisabled, setAllButtonsDisabledState] =
+ useState<boolean>(false);
+
+ const registerButtons = useCallback(
+ (newButtons: WorkbenchBarButtonConfig[]) => {
+ setButtons((prev) => {
+ const byId = new Map(prev.map((b) => [b.id, b] as const));
+ newButtons.forEach((nb) => {
+ const existing = byId.get(nb.id) || ({} as WorkbenchBarButtonConfig);
+ byId.set(nb.id, { ...existing, ...nb });
+ });
+ const merged = Array.from(byId.values());
+ merged.sort(
+ (a, b) => (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id),
+ );
+ if (process.env.NODE_ENV === "development") {
+ const ids = newButtons.map((b) => b.id);
+ const dupes = ids.filter((id, idx) => ids.indexOf(id) !== idx);
+ if (dupes.length)
+ console.warn(
+ "[WorkbenchBar] Duplicate ids in registerButtons:",
+ dupes,
+ );
+ }
+ return merged;
+ });
+ },
+ [],
+ );
+
+ const unregisterButtons = useCallback((ids: string[]) => {
+ setButtons((prev) => prev.filter((b) => !ids.includes(b.id)));
+ setActions((prev) =>
+ Object.fromEntries(
+ Object.entries(prev).filter(([id]) => !ids.includes(id)),
+ ),
+ );
+ }, []);
+
+ const setAction = useCallback((id: string, action?: WorkbenchBarAction) => {
+ setActions((prev) => {
+ if (!action) {
+ if (!(id in prev)) return prev;
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ }
+ return { ...prev, [id]: action };
+ });
+ }, []);
+
+ const setAllButtonsDisabled = useCallback((disabled: boolean) => {
+ setAllButtonsDisabledState(disabled);
+ }, []);
+
+ const clear = useCallback(() => {
+ setButtons([]);
+ setActions({});
+ }, []);
+
+ const value = useMemo<WorkbenchBarContextValue>(
+ () => ({
+ buttons,
+ actions,
+ allButtonsDisabled,
+ registerButtons,
+ unregisterButtons,
+ setAction,
+ setAllButtonsDisabled,
+ clear,
+ }),
+ [
+ buttons,
+ actions,
+ allButtonsDisabled,
+ registerButtons,
+ unregisterButtons,
+ setAction,
+ setAllButtonsDisabled,
+ clear,
+ ],
+ );
+
+ return (
+ <WorkbenchBarContext.Provider value={value}>
+ {children}
+ </WorkbenchBarContext.Provider>
+ );
+}
+
+export function useWorkbenchBar() {
+ const ctx = useContext(WorkbenchBarContext);
+ if (!ctx)
+ throw new Error("useWorkbenchBar must be used within WorkbenchBarProvider");
+ return ctx;
+}
diff --git a/frontend/src/core/contexts/file/fileActions.ts b/frontend/src/core/contexts/file/fileActions.ts
index 5d6188d821..30f9d9fc7e 100644
--- a/frontend/src/core/contexts/file/fileActions.ts
+++ b/frontend/src/core/contexts/file/fileActions.ts
@@ -347,6 +347,9 @@ export async function addFiles(
`📄 addFiles: After ZIP processing, ${filesToProcess.length} files to add`,
);
+ // Collect hydrations to schedule after dispatch so updateStirlingFileStub finds files in state.
+ const pendingHydrations: Array<() => Promise<void>> = [];
+
for (const file of filesToProcess) {
const quickKey = createQuickKey(file);
@@ -419,18 +422,12 @@ export async function addFiles(
}
stirlingFileStubs.push(fileStub);
- // Dispatch immediately so each file appears as soon as it is processed
- dispatch({
- type: "ADD_FILES",
- payload: { stirlingFileStubs: [fileStub] },
- });
-
// Create StirlingFile directly
const stirlingFile = createStirlingFile(file, fileId);
stirlingFiles.push(stirlingFile);
- // Queue background hydration so add flow doesn't block on thumbnail/metadata work
- scheduleMetadataHydration(async () => {
+ // Capture per-file hydration task — scheduled after batch dispatch below
+ pendingHydrations.push(async () => {
const targetFile = filesRef.current.get(fileId);
if (!targetFile) {
return;
@@ -483,9 +480,34 @@ export async function addFiles(
if (Object.keys(updates).length > 0) {
lifecycleManager.updateStirlingFileStub(fileId, updates, stateRef);
}
+
+ // Persist the thumbnail to IndexedDB so it's available in future sessions.
+ // The file was stored before hydration ran, so it had no thumbnail yet.
+ // Skip blob URLs — they're session-only and won't be valid after reload.
+ if (
+ primaryThumbnail &&
+ enablePersistence &&
+ !primaryThumbnail.startsWith("blob:")
+ ) {
+ try {
+ await fileStorage.updateThumbnail(fileId, primaryThumbnail);
+ } catch {
+ // Non-critical — regenerated lazily on next hover
+ }
+ }
});
}
+ // Batch dispatch all files at once — one render instead of N sequential renders
+ if (stirlingFileStubs.length > 0) {
+ dispatch({ type: "ADD_FILES", payload: { stirlingFileStubs } });
+ }
+
+ // Schedule hydrations after dispatch so updateStirlingFileStub finds files in state
+ for (const task of pendingHydrations) {
+ scheduleMetadataHydration(task);
+ }
+
// Persist to storage if enabled using fileStorage service
if (enablePersistence && stirlingFiles.length > 0) {
await Promise.all(
@@ -635,56 +657,6 @@ export async function consumeFiles(
}
/**
- * Helper function to restore files to filesRef and manage IndexedDB cleanup
- */
-async function restoreFilesAndCleanup(
- filesToRestore: Array<{ file: File; record: StirlingFileStub }>,
- fileIdsToRemove: FileId[],
- filesRef: React.MutableRefObject<Map<FileId, File>>,
- indexedDB?: { deleteFile: (fileId: FileId) => Promise<void> } | null,
-): Promise<void> {
- // Remove files from filesRef
- fileIdsToRemove.forEach((id) => {
- if (filesRef.current.has(id)) {
- if (DEBUG) console.log(`📄 Removing file ${id} from filesRef`);
- filesRef.current.delete(id);
- } else {
- if (DEBUG) console.warn(`📄 File ${id} not found in filesRef`);
- }
- });
-
- // Restore files to filesRef
- filesToRestore.forEach(({ file, record }) => {
- if (file && record) {
- // Validate the file before restoring
- if (file.size === 0) {
- if (DEBUG) console.warn(`📄 Skipping empty file ${file.name}`);
- return;
- }
-
- // Restore the file to filesRef
- if (DEBUG)
- console.log(
- `📄 Restoring file ${file.name} with id ${record.id} to filesRef`,
- );
- filesRef.current.set(record.id, file);
- }
- });
-
- // Clean up IndexedDB
- if (indexedDB) {
- const indexedDBPromises = fileIdsToRemove.map((fileId) =>
- indexedDB.deleteFile(fileId).catch((error) => {
- console.error("Failed to delete file from IndexedDB:", fileId, error);
- throw error; // Re-throw to trigger rollback
- }),
- );
-
- // Execute all IndexedDB operations
- await Promise.all(indexedDBPromises);
- }
-}
-
/**
* Undoes a previous consumeFiles operation by restoring input files and removing output files (unless pinned)
*/
@@ -701,6 +673,7 @@ export async function undoConsumeFiles(
existingThumbnail?: string,
) => Promise<any>;
deleteFile: (fileId: FileId) => Promise<void>;
+ bumpRevision?: () => void;
} | null,
): Promise<void> {
if (DEBUG)
@@ -719,30 +692,21 @@ export async function undoConsumeFiles(
const backupFilesRef = new Map(filesRef.current);
try {
- // Prepare files to restore
- const filesToRestore = inputFiles.map((file, index) => ({
- file,
- record: inputStirlingFileStubs[index],
- }));
-
- // Restore input files and clean up output files
- await restoreFilesAndCleanup(
- filesToRestore,
- outputFileIds,
- filesRef,
- indexedDB,
- );
-
- // Mark restored files as dirty if they have localFilePath
- // (they now differ from what's saved on disk)
- const stubsWithDirtyMarked = inputStirlingFileStubs.map((stub) => {
- if (stub.localFilePath) {
- return { ...stub, isDirty: true };
+ // Sync filesRef before dispatch — prevents bumpRevision re-renders from seeing stale output IDs with no File objects.
+ outputFileIds.forEach((id) => filesRef.current.delete(id));
+ inputFiles.forEach((file, index) => {
+ const record = inputStirlingFileStubs[index];
+ if (file && record && file.size > 0) {
+ filesRef.current.set(record.id, file);
}
- return stub;
});
- // Dispatch the undo action (only if everything else succeeded)
+ // Mark restored files dirty if they have a local path (they now differ from disk).
+ const stubsWithDirtyMarked = inputStirlingFileStubs.map((stub) =>
+ stub.localFilePath ? { ...stub, isDirty: true } : stub,
+ );
+
+ // Dispatch with filesRef and state.files.ids now in sync.
dispatch({
type: "UNDO_CONSUME_FILES",
payload: {
@@ -751,6 +715,33 @@ export async function undoConsumeFiles(
},
});
+ // IDB cleanup fire-and-forget — state is already consistent when bumpRevision fires.
+ if (indexedDB) {
+ outputFileIds.forEach((fileId) => {
+ indexedDB.deleteFile(fileId).catch((error) => {
+ console.error(
+ "📄 undoConsumeFiles: Failed to delete output file from IDB:",
+ fileId,
+ error,
+ );
+ // Bump revision so the sidebar re-reads IDB and orphaned files reappear.
+ indexedDB.bumpRevision?.();
+ });
+ });
+ }
+
+ // Restore isLeaf in IDB — modal reads IDB directly and misses files if isLeaf=false.
+ await Promise.all(
+ inputStirlingFileStubs.map((stub) =>
+ fileStorage.markFileAsLeaf(stub.id).catch((error) => {
+ console.warn(
+ `📄 undoConsumeFiles: Failed to restore isLeaf for ${stub.id}:`,
+ error,
+ );
+ }),
+ ),
+ );
+
if (DEBUG)
console.log(
`📄 undoConsumeFiles: Successfully undone consume operation - restored ${inputStirlingFileStubs.length} inputs, removed ${outputFileIds.length} outputs`,
@@ -798,16 +789,19 @@ export async function addStirlingFileStubs(
});
}
- const existingQuickKeys = buildQuickKeySet(stateRef.current.files.byId);
const loadedFiles: StirlingFile[] = [];
let firstFileDispatched = false;
// Process and dispatch files one by one for progressive UI updates
for (const stub of stirlingFileStubs) {
- // Check for duplicates using quickKey
- if (existingQuickKeys.has(stub.quickKey || "")) {
+ // Dedup by stable fileId. Two distinct files in history can share
+ // name|size|lastModified (and therefore quickKey), so quickKey dedup
+ // here would silently drop a legitimately different file.
+ if (stateRef.current.files.byId[stub.id]) {
if (DEBUG)
- console.log(`📄 Skipping duplicate StirlingFileStub: ${stub.name}`);
+ console.log(
+ `📄 Skipping already-loaded StirlingFileStub: ${stub.name}`,
+ );
continue;
}
@@ -819,8 +813,6 @@ export async function addStirlingFileStubs(
record.insertAfterPageId = options.insertAfterPageId;
}
- existingQuickKeys.add(stub.quickKey || "");
-
// Dispatch each file immediately as we process it (progressive loading)
dispatch({ type: "ADD_FILES", payload: { stirlingFileStubs: [record] } });
@@ -883,9 +875,13 @@ export async function addStirlingFileStubs(
updates,
stateRef,
);
+ return;
}
}
}
+
+ // Stub dispatch triggers re-render so the viewer appears (ADD_FILES alone doesn't update selectors).
+ lifecycleManager.updateStirlingFileStub(fileId, {}, stateRef);
});
}
diff --git a/frontend/src/core/contexts/viewer/viewerActions.ts b/frontend/src/core/contexts/viewer/viewerActions.ts
index d1d695a451..04e9dbce33 100644
--- a/frontend/src/core/contexts/viewer/viewerActions.ts
+++ b/frontend/src/core/contexts/viewer/viewerActions.ts
@@ -20,6 +20,7 @@ export interface ZoomActions {
zoomOut: () => void;
toggleMarqueeZoom: () => void;
requestZoom: (level: any, center?: any) => void;
+ setZoomLevel: (factor: number) => void;
}
export interface PanActions {
@@ -217,6 +218,13 @@ export function createViewerActions({
api.requestZoom(level, center);
}
},
+ setZoomLevel: (factor: number) => {
+ const api = registry.current.zoom?.api;
+ if (api?.requestZoom) {
+ triggerImmediateZoomUpdate(Math.round(factor * 100));
+ api.requestZoom(factor);
+ }
+ },
};
const panActions: PanActions = {
diff --git a/frontend/src/core/data/useTranslatedToolRegistry.tsx b/frontend/src/core/data/useTranslatedToolRegistry.tsx
index f6a3e793ae..c6b7c79d8a 100644
--- a/frontend/src/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/src/core/data/useTranslatedToolRegistry.tsx
@@ -105,7 +105,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
multiTool: {
icon: (
<LocalIcon
- icon="dashboard-customize-rounded"
+ icon="dashboard-customize-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -128,7 +128,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
merge: {
icon: (
<LocalIcon
- icon="library-add-rounded"
+ icon="library-add-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -153,7 +153,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
certSign: {
icon: (
<LocalIcon
- icon="workspace-premium-rounded"
+ icon="workspace-premium-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -177,7 +177,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
timestampPdf: {
icon: (
- <LocalIcon icon="schedule-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="schedule-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.timestampPdf.title", "Timestamp PDF"),
component: lazy(() => import("@app/tools/TimestampPdf")),
@@ -236,7 +240,13 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
supportsAutomate: false,
},
addImage: {
- icon: <LocalIcon icon="image-rounded" width="1.5rem" height="1.5rem" />,
+ icon: (
+ <LocalIcon
+ icon="image-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
+ ),
name: t("home.addImage.title", "Add Image"),
component: lazy(() => import("@app/tools/AddImage")),
description: t("home.addImage.desc", "Add images anywhere in your PDF"),
@@ -249,7 +259,13 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
supportsAutomate: false,
},
annotate: {
- icon: <LocalIcon icon="edit" width="1.5rem" height="1.5rem" />,
+ icon: (
+ <LocalIcon
+ icon="edit-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
+ ),
name: t("home.annotate.title", "Annotate"),
component: lazy(() => import("@app/tools/Annotate")),
description: t(
@@ -315,7 +331,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
addStamp: {
icon: (
- <LocalIcon icon="approval-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="approval-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.addStamp.title", "Add Stamp to PDF"),
component: lazy(() => import("@app/tools/AddStamp")),
@@ -361,7 +381,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
flatten: {
icon: (
<LocalIcon
- icon="layers-clear-rounded"
+ icon="layers-clear-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -447,7 +467,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
getPdfInfo: {
icon: (
- <LocalIcon icon="fact-check-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="fact-check-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.getPdfInfo.title", "Get ALL Info on PDF"),
component: lazy(() => import("@app/tools/GetPdfInfo")),
@@ -465,7 +489,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
validateSignature: {
icon: (
- <LocalIcon icon="verified-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="verified-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.validateSignature.title", "Validate PDF Signature"),
component: lazy(() => import("@app/tools/ValidateSignature")),
@@ -485,7 +513,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
read: {
icon: (
- <LocalIcon icon="article-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="article-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.read.title", "Read"),
component: null,
@@ -503,7 +535,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
changeMetadata: {
icon: (
- <LocalIcon icon="assignment-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="assignment-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.changeMetadata.title", "Change Metadata"),
component: lazy(() => import("@app/tools/ChangeMetadata")),
@@ -658,7 +694,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
pageLayout: {
icon: (
- <LocalIcon icon="dashboard-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="dashboard-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.pageLayout.title", "Multi-Page Layout"),
component: lazy(() => import("@app/tools/PageLayout")),
@@ -677,7 +717,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
bookletImposition: {
icon: (
- <LocalIcon icon="menu-book-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="menu-book-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.bookletImposition.title", "Booklet Imposition"),
component: lazy(() => import("@app/tools/BookletImposition")),
@@ -764,7 +808,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
extractImages: {
icon: (
<LocalIcon
- icon="photo-library-rounded"
+ icon="photo-library-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -816,7 +860,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
removeBlanks: {
icon: (
<LocalIcon
- icon="scan-delete-rounded"
+ icon="scan-delete-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
@@ -971,7 +1015,9 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
// Advanced Formatting
adjustContrast: {
- icon: <LocalIcon icon="palette" width="1.5rem" height="1.5rem" />,
+ icon: (
+ <LocalIcon icon="palette-outline" width="1.5rem" height="1.5rem" />
+ ),
name: t("home.adjustContrast.title", "Adjust Colors/Contrast"),
component: lazy(() => import("@app/tools/AdjustContrast")),
description: t(
@@ -1013,7 +1059,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
scannerImageSplit: {
icon: (
- <LocalIcon icon="scanner-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="scanner-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t(
"home.scannerImageSplit.title",
@@ -1037,7 +1087,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
overlayPdfs: {
icon: (
- <LocalIcon icon="layers-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="layers-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.overlay-pdfs.title", "Overlay PDFs"),
component: lazy(() => import("@app/tools/OverlayPdfs")),
@@ -1081,7 +1135,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
},
scannerEffect: {
icon: (
- <LocalIcon icon="scanner-rounded" width="1.5rem" height="1.5rem" />
+ <LocalIcon
+ icon="scanner-outline-rounded"
+ width="1.5rem"
+ height="1.5rem"
+ />
),
name: t("home.scannerEffect.title", "Scanner Effect"),
component: null,
@@ -1314,7 +1372,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
redact: {
icon: (
<LocalIcon
- icon="visibility-off-rounded"
+ icon="visibility-off-outline-rounded"
width="1.5rem"
height="1.5rem"
/>
diff --git a/frontend/src/core/hooks/tools/changeMetadata/useMetadataExtraction.ts b/frontend/src/core/hooks/tools/changeMetadata/useMetadataExtraction.ts
index 41c20a6e2c..b99e69ce97 100644
--- a/frontend/src/core/hooks/tools/changeMetadata/useMetadataExtraction.ts
+++ b/frontend/src/core/hooks/tools/changeMetadata/useMetadataExtraction.ts
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef } from "react";
import { extractPDFMetadata } from "@app/services/pdfMetadataService";
-import { useSelectedFiles } from "@app/contexts/file/fileHooks";
+import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
import { ChangeMetadataParameters } from "@app/hooks/tools/changeMetadata/useChangeMetadataParameters";
interface MetadataExtractionParams {
@@ -11,7 +11,7 @@ interface MetadataExtractionParams {
}
export const useMetadataExtraction = (params: MetadataExtractionParams) => {
- const { selectedFiles } = useSelectedFiles();
+ const selectedFiles = useViewScopedFiles();
const [isExtractingMetadata, setIsExtractingMetadata] = useState(false);
const [hasExtractedMetadata, setHasExtractedMetadata] = useState(false);
const previousFileCountRef = useRef(0);
diff --git a/frontend/src/core/hooks/tools/getPdfInfo/useGetPdfInfoOperation.ts b/frontend/src/core/hooks/tools/getPdfInfo/useGetPdfInfoOperation.ts
index ee0715c807..0937c97096 100644
--- a/frontend/src/core/hooks/tools/getPdfInfo/useGetPdfInfoOperation.ts
+++ b/frontend/src/core/hooks/tools/getPdfInfo/useGetPdfInfoOperation.ts
@@ -51,7 +51,7 @@ export const useGetPdfInfoOperation = (): GetPdfInfoOperationHook => {
const executeOperation = useCallback(
async (_params: GetPdfInfoParameters, selectedFiles: StirlingFile[]) => {
if (selectedFiles.length === 0) {
- setErrorMessage(t("noFileSelected", "No files selected"));
+ setErrorMessage(t("noFileSelected", "No file loaded"));
return;
}
diff --git a/frontend/src/core/hooks/tools/shared/toolOperationTypes.ts b/frontend/src/core/hooks/tools/shared/toolOperationTypes.ts
index dd9b49e43f..27cc16b13a 100644
--- a/frontend/src/core/hooks/tools/shared/toolOperationTypes.ts
+++ b/frontend/src/core/hooks/tools/shared/toolOperationTypes.ts
@@ -17,6 +17,7 @@ export enum ToolType {
*/
export type ExecuteDisabledReason =
| "endpointUnavailable"
+ | "filesLoading"
| "noFiles"
| "invalidParams"
| "viewerMode"
diff --git a/frontend/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/src/core/hooks/tools/shared/useToolOperation.ts
index 8c4d41a7f1..20edf23935 100644
--- a/frontend/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/src/core/hooks/tools/shared/useToolOperation.ts
@@ -121,7 +121,7 @@ export const useToolOperation = <TParams>(
async (params: TParams, selectedFiles: StirlingFile[]): Promise<void> => {
// Validation
if (selectedFiles.length === 0) {
- actions.setError(t("noFileSelected", "No files selected"));
+ actions.setError(t("noFileSelected", "No file loaded"));
return;
}
@@ -459,7 +459,7 @@ export const useToolOperation = <TParams>(
inputStirlingFileStubs[0],
newToolOperation,
file,
- thumbnail,
+ metadata?.thumbnailUrl || thumbnail,
metadata,
),
);
@@ -523,7 +523,7 @@ export const useToolOperation = <TParams>(
createNewStirlingFileStub(
file,
undefined,
- thumbnail,
+ metadata?.thumbnailUrl || thumbnail,
metadata,
),
);
diff --git a/frontend/src/core/hooks/tools/shared/useViewScopedFiles.ts b/frontend/src/core/hooks/tools/shared/useViewScopedFiles.ts
index 87f5fd93e6..070e854700 100644
--- a/frontend/src/core/hooks/tools/shared/useViewScopedFiles.ts
+++ b/frontend/src/core/hooks/tools/shared/useViewScopedFiles.ts
@@ -1,21 +1,13 @@
import { useMemo } from "react";
-import { useAllFiles, useSelectedFiles } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useNavigationState } from "@app/contexts/NavigationContext";
import { StirlingFile } from "@app/types/fileContext";
-/**
- * Returns the effective file set for tool operations.
- *
- * - Viewer: scopes to the single file currently shown, unless ignoreViewerScope is true.
- * - FileEditor: scopes to the selected subset (empty selection → empty → button disabled).
- * - PageEditor / custom workbenches: returns all loaded files (selection tracks pages, not files).
- */
export function useViewScopedFiles(ignoreViewerScope = false): StirlingFile[] {
const { activeFileIndex } = useViewer();
const { files: allFiles } = useAllFiles();
const { workbench } = useNavigationState();
- const { selectedFiles } = useSelectedFiles();
return useMemo(() => {
if (workbench === "viewer" && !ignoreViewerScope) {
@@ -23,10 +15,6 @@ export function useViewScopedFiles(ignoreViewerScope = false): StirlingFile[] {
return viewerFile ? [viewerFile] : allFiles;
}
- if (workbench === "fileEditor") {
- return selectedFiles;
- }
-
return allFiles;
- }, [workbench, allFiles, activeFileIndex, selectedFiles, ignoreViewerScope]);
+ }, [workbench, allFiles, activeFileIndex, ignoreViewerScope]);
}
diff --git a/frontend/src/core/hooks/tools/showJS/useShowJSOperation.ts b/frontend/src/core/hooks/tools/showJS/useShowJSOperation.ts
index 478ea33fdf..fb35b42e8e 100644
--- a/frontend/src/core/hooks/tools/showJS/useShowJSOperation.ts
+++ b/frontend/src/core/hooks/tools/showJS/useShowJSOperation.ts
@@ -49,7 +49,7 @@ export const useShowJSOperation = (): ShowJSOperationHook => {
const executeOperation = useCallback(
async (_params: ShowJSParameters, selectedFiles: StirlingFile[]) => {
if (selectedFiles.length === 0) {
- setErrorMessage(t("noFileSelected", "No files selected"));
+ setErrorMessage(t("noFileSelected", "No file loaded"));
return;
}
diff --git a/frontend/src/core/hooks/tools/useToolPanelGeometry.ts b/frontend/src/core/hooks/tools/useToolPanelGeometry.ts
index aa7452a593..818057b996 100644
--- a/frontend/src/core/hooks/tools/useToolPanelGeometry.ts
+++ b/frontend/src/core/hooks/tools/useToolPanelGeometry.ts
@@ -11,14 +11,12 @@ interface UseToolPanelGeometryOptions {
enabled: boolean;
toolPanelRef: RefObject<HTMLDivElement | null>;
quickAccessRef: RefObject<HTMLDivElement | null>;
- rightRailRef?: RefObject<HTMLDivElement | null>;
}
export function useToolPanelGeometry({
enabled,
toolPanelRef,
quickAccessRef,
- rightRailRef,
}: UseToolPanelGeometryOptions) {
const [geometry, setGeometry] = useState<ToolPanelGeometry | null>(null);
const scheduleUpdateRef = useRef<() => void>(() => {});
@@ -35,39 +33,26 @@ export function useToolPanelGeometry({
return;
}
- const rightRailEl = () => rightRailRef?.current ?? null;
-
let rafId: number | null = null;
const computeAndSetGeometry = () => {
const rect = panelEl.getBoundingClientRect();
- const rail = rightRailEl();
const isRTL =
typeof document !== "undefined" &&
document.documentElement.dir === "rtl";
- const railRect = rail?.getBoundingClientRect();
- const railIsOnRight = railRect
- ? railRect.right > window.innerWidth / 2
- : false;
- const rightOffset =
- railRect && railIsOnRight
- ? Math.max(0, window.innerWidth - railRect.right)
- : 0;
let width: number;
let left: number;
if (isRTL) {
- // In RTL, QuickAccessBar is on the right, so start after it (using rect.right as the right edge)
- const quickAccessRect = quickAccessRef.current?.getBoundingClientRect();
- const quickAccessWidth = quickAccessRect ? quickAccessRect.width : 0;
- width = Math.max(
- 360,
- window.innerWidth - quickAccessWidth - rightOffset,
- );
- left = quickAccessWidth;
+ // RTL: panel is on the left, expands rightward
+ width = Math.max(360, window.innerWidth - rect.right);
+ left = rect.right;
} else {
- width = Math.max(360, window.innerWidth - rect.left - rightOffset);
- left = rect.left;
+ // LTR: panel is on the right, expands leftward to the file sidebar
+ const quickAccessRect = quickAccessRef.current?.getBoundingClientRect();
+ const leftOffset = quickAccessRect ? quickAccessRect.right : 0;
+ width = Math.max(360, rect.right - leftOffset);
+ left = leftOffset;
}
const height = Math.max(rect.height, window.innerHeight - rect.top);
setGeometry({
@@ -99,10 +84,6 @@ export function useToolPanelGeometry({
if (quickAccessRef.current) {
resizeObserver.observe(quickAccessRef.current);
}
- const rail = rightRailEl();
- if (rail) {
- resizeObserver.observe(rail);
- }
// Observe root element to react to viewport-driven layout changes
if (document.documentElement) {
resizeObserver.observe(document.documentElement);
@@ -124,21 +105,19 @@ export function useToolPanelGeometry({
scheduleUpdateRef.current = () => {};
resizeObserver?.disconnect();
};
- }, [enabled, quickAccessRef, toolPanelRef, rightRailRef]);
+ }, [enabled, quickAccessRef, toolPanelRef]);
- // Secondary effect: (re)attach observers when refs' .current become available later
+ // Secondary effect: (re)attach observer when quickAccessRef.current becomes available later
useLayoutEffect(() => {
if (!enabled) return;
if (typeof ResizeObserver === "undefined") return;
const qa = quickAccessRef.current;
- const rail = rightRailRef?.current ?? null;
- if (!qa && !rail) return;
+ if (!qa) return;
const ro = new ResizeObserver(() => scheduleUpdateRef.current());
- if (qa) ro.observe(qa);
- if (rail) ro.observe(rail);
+ ro.observe(qa);
return () => ro.disconnect();
- }, [enabled, quickAccessRef.current, rightRailRef?.current]);
+ }, [enabled, quickAccessRef.current]);
return geometry;
}
diff --git a/frontend/src/core/hooks/useFileActionTerminology.ts b/frontend/src/core/hooks/useFileActionTerminology.ts
index 48616fd315..2f8b9127ad 100644
--- a/frontend/src/core/hooks/useFileActionTerminology.ts
+++ b/frontend/src/core/hooks/useFileActionTerminology.ts
@@ -19,7 +19,7 @@ export function useFileActionTerminology() {
mobileUpload: t("landing.mobileUpload", "Upload from Mobile"),
uploadFromComputer: t("landing.uploadFromComputer", "Upload from computer"),
download: t("download", "Download"),
- downloadAll: t("rightRail.downloadAll", "Download All"),
+ downloadAll: t("workbenchBar.downloadAll", "Download All"),
downloadSelected: t("fileManager.downloadSelected", "Download Selected"),
downloadUnavailable: t(
"downloadUnavailable",
diff --git a/frontend/src/core/hooks/useFileManager.ts b/frontend/src/core/hooks/useFileManager.ts
index 51f7c3c2ee..442027364e 100644
--- a/frontend/src/core/hooks/useFileManager.ts
+++ b/frontend/src/core/hooks/useFileManager.ts
@@ -376,6 +376,8 @@ export const useFileManager = () => {
index: number,
files: StirlingFileStub[],
setFiles: (files: StirlingFileStub[]) => void,
+ onRemovedFromWorkbench?: (fileId: FileId) => void,
+ onDeleteFailed?: () => void,
) => {
const file = files[index];
if (!file.id) {
@@ -384,13 +386,19 @@ export const useFileManager = () => {
if (!indexedDB) {
throw new Error("IndexedDB context not available");
}
- try {
- await indexedDB.deleteFile(file.id);
- setFiles(files.filter((_, i) => i !== index));
- } catch (error) {
- console.error("Failed to remove file:", error);
- throw error;
- }
+ // Optimistic update — remove from UI immediately, delete IDB in background
+ setFiles(files.filter((_, i) => i !== index));
+ onRemovedFromWorkbench?.(file.id);
+ indexedDB.deleteFile(file.id).catch((error) => {
+ console.error("Failed to remove file from IndexedDB:", error);
+ // Restore consistency — file is still in IDB so refresh brings it back
+ if (onDeleteFailed) {
+ onDeleteFailed();
+ } else {
+ // No failure handler provided — refresh to restore consistent state
+ setFiles([...files]);
+ }
+ });
},
[indexedDB],
);
diff --git a/frontend/src/core/hooks/useFileThumbnail.ts b/frontend/src/core/hooks/useFileThumbnail.ts
new file mode 100644
index 0000000000..e564142c7c
--- /dev/null
+++ b/frontend/src/core/hooks/useFileThumbnail.ts
@@ -0,0 +1,19 @@
+import { StirlingFileStub } from "@app/types/fileContext";
+import { useIndexedDBThumbnail } from "@app/hooks/useIndexedDBThumbnail";
+
+export function useFileThumbnail(
+ fileStub: StirlingFileStub | null | undefined,
+): {
+ isEncrypted: boolean;
+ thumbnail: string | null;
+ isGenerating: boolean;
+} {
+ const isEncrypted = Boolean(fileStub?.processedFile?.isEncrypted);
+ const { thumbnail: indexedDBThumb, isGenerating } = useIndexedDBThumbnail(
+ isEncrypted ? null : fileStub,
+ );
+ const thumbnail = isEncrypted
+ ? null
+ : fileStub?.thumbnailUrl || indexedDBThumb || null;
+ return { isEncrypted, thumbnail, isGenerating };
+}
diff --git a/frontend/src/core/hooks/useFileWithUrl.ts b/frontend/src/core/hooks/useFileWithUrl.ts
index eb6f4a92f7..be654357b5 100644
--- a/frontend/src/core/hooks/useFileWithUrl.ts
+++ b/frontend/src/core/hooks/useFileWithUrl.ts
@@ -4,9 +4,15 @@ import { isFileObject } from "@app/types/fileContext";
/**
* Hook to convert a File object to { file: File; url: string } format
* Creates blob URL on-demand and revokes it when file changes or component unmounts.
+ *
+ * @param stableKey - Optional stable identity key (e.g. fileId). When provided, the blob
+ * URL is only recreated when this key changes, not when the `file` object reference
+ * changes. This prevents spurious URL churn caused by getFiles() creating new
+ * StirlingFile references on every FileContext render.
*/
export function useFileWithUrl(
file: File | Blob | null,
+ stableKey?: string | null,
): { file: File | Blob; url: string } | null {
const result = useMemo(() => {
if (!file) return null;
@@ -28,7 +34,9 @@ export function useFileWithUrl(
);
return null;
}
- }, [file]);
+ // When stableKey is provided, only recreate when the file identity changes — not
+ // when getFiles() returns a new object reference for the same underlying file.
+ }, [stableKey != null ? stableKey : file]);
useEffect(() => {
const url = result?.url;
diff --git a/frontend/src/core/hooks/useRightRailTooltipSide.ts b/frontend/src/core/hooks/useRightRailTooltipSide.ts
deleted file mode 100644
index ddd7e0f7ac..0000000000
--- a/frontend/src/core/hooks/useRightRailTooltipSide.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { useEffect, useState } from "react";
-import { SidebarRefs } from "@app/types/sidebar";
-
-export function useRightRailTooltipSide(
- sidebarRefs?: SidebarRefs,
- defaultOffset: number = 16,
-): { position: "left" | "right"; offset: number } {
- const [position, setPosition] = useState<"left" | "right">("left");
-
- useEffect(() => {
- const computePosition = () => {
- const rail = sidebarRefs?.rightRailRef?.current;
- const isRTL =
- typeof document !== "undefined" &&
- document.documentElement.dir === "rtl";
-
- // Fallback to left if we can't measure
- if (!rail || typeof window === "undefined") {
- setPosition(isRTL ? "left" : "left");
- return;
- }
-
- const rect = rail.getBoundingClientRect();
- const center = rect.left + rect.width / 2;
- const preferred = center > window.innerWidth / 2 ? "left" : "right";
- setPosition(isRTL ? "left" : preferred);
- };
-
- computePosition();
- window.addEventListener("resize", computePosition);
- return () => window.removeEventListener("resize", computePosition);
- }, [sidebarRefs]);
-
- return { position, offset: defaultOffset };
-}
diff --git a/frontend/src/core/hooks/useTooltipPosition.ts b/frontend/src/core/hooks/useTooltipPosition.ts
index 626f6a3bea..3e22c5b692 100644
--- a/frontend/src/core/hooks/useTooltipPosition.ts
+++ b/frontend/src/core/hooks/useTooltipPosition.ts
@@ -116,8 +116,10 @@ export function useTooltipPosition({
const tooltipRect = tooltipRef.current?.getBoundingClientRect() || null;
- // Position adjacent to sidebar; mirror for RTL
- if (isRTL) {
+ // Position adjacent to sidebar: left of panel when on the right half, right of panel when on left half; mirror for RTL
+ const panelCenter = rect.left + rect.width / 2;
+ const panelIsOnRight = panelCenter > window.innerWidth / 2;
+ if (isRTL ? !panelIsOnRight : panelIsOnRight) {
left = rect.left - (tooltipRect?.width || 0) - 20;
} else {
left = rect.right + 20;
diff --git a/frontend/src/core/hooks/useUrlSync.ts b/frontend/src/core/hooks/useUrlSync.ts
index 27ae833a70..ec4ede495d 100644
--- a/frontend/src/core/hooks/useUrlSync.ts
+++ b/frontend/src/core/hooks/useUrlSync.ts
@@ -60,15 +60,14 @@ export function useNavigationUrlSync(
firePixel(currentPath);
const route = parseToolRoute(registry);
- if (route.toolId !== selectedTool) {
- if (route.toolId) {
+ if (route.toolId) {
+ // URL specifies a tool — navigate to it (URL takes precedence over startup view preference)
+ if (route.toolId !== selectedTool) {
checkPremiumAndSelect(route.toolId);
- } else if (selectedTool !== null) {
- // Only clear selection if we actually had a tool selected
- // Don't clear on initial load when selectedTool starts as null
- clearToolSelection();
}
}
+ // When the URL is the home path (no tool), leave selectedTool untouched so that
+ // the startup view preference (defaultStartupView) is respected.
hasInitialized.current = true;
}, [checkPremiumAndSelect, config, enableSync, registry, selectedTool]); // Include dependencies
diff --git a/frontend/src/core/hooks/useRightRailButtons.ts b/frontend/src/core/hooks/useWorkbenchBarButtons.ts
similarity index 61%
rename from frontend/src/core/hooks/useRightRailButtons.ts
rename to frontend/src/core/hooks/useWorkbenchBarButtons.ts
index a4def11c61..a03130420b 100644
--- a/frontend/src/core/hooks/useRightRailButtons.ts
+++ b/frontend/src/core/hooks/useWorkbenchBarButtons.ts
@@ -1,23 +1,26 @@
import { useEffect, useMemo } from "react";
-import { useRightRail } from "@app/contexts/RightRailContext";
-import { RightRailAction, RightRailButtonConfig } from "@app/types/rightRail";
-
-export interface RightRailButtonWithAction extends RightRailButtonConfig {
- onClick?: RightRailAction;
+import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
+import {
+ WorkbenchBarAction,
+ WorkbenchBarButtonConfig,
+} from "@app/types/workbenchBar";
+
+export interface WorkbenchBarButtonWithAction extends WorkbenchBarButtonConfig {
+ onClick?: WorkbenchBarAction;
}
/**
- * Registers one or more RightRail buttons and their actions.
+ * Registers one or more WorkbenchBar buttons and their actions.
* - Automatically registers on mount and unregisters on unmount
* - Updates registration when the input array reference changes
*/
-export function useRightRailButtons(
- buttons: readonly RightRailButtonWithAction[],
+export function useWorkbenchBarButtons(
+ buttons: readonly WorkbenchBarButtonWithAction[],
) {
- const { registerButtons, unregisterButtons, setAction } = useRightRail();
+ const { registerButtons, unregisterButtons, setAction } = useWorkbenchBar();
// Memoize configs and ids to reduce churn
- const configs: RightRailButtonConfig[] = useMemo(
+ const configs: WorkbenchBarButtonConfig[] = useMemo(
() => buttons.map(({ onClick, ...cfg }) => cfg),
[buttons],
);
@@ -31,9 +34,9 @@ export function useRightRailButtons(
const idSet = new Set<string>();
buttons.forEach((b) => {
if (!b.onClick && !b.render)
- console.warn("[RightRail] Missing onClick/render for id:", b.id);
+ console.warn("[WorkbenchBar] Missing onClick/render for id:", b.id);
if (idSet.has(b.id))
- console.warn("[RightRail] Duplicate id in buttons array:", b.id);
+ console.warn("[WorkbenchBar] Duplicate id in buttons array:", b.id);
idSet.add(b.id);
});
}
diff --git a/frontend/src/core/hooks/useWorkbenchBarTooltipSide.ts b/frontend/src/core/hooks/useWorkbenchBarTooltipSide.ts
new file mode 100644
index 0000000000..3029fc3780
--- /dev/null
+++ b/frontend/src/core/hooks/useWorkbenchBarTooltipSide.ts
@@ -0,0 +1,8 @@
+import { SidebarRefs } from "@app/types/sidebar";
+
+export function useWorkbenchBarTooltipSide(
+ _sidebarRefs?: SidebarRefs,
+ defaultOffset: number = 16,
+): { position: "left" | "right" | "bottom"; offset: number } {
+ return { position: "bottom", offset: defaultOffset };
+}
diff --git a/frontend/src/core/pages/HomePage.tsx b/frontend/src/core/pages/HomePage.tsx
index 2119c53233..1a32ebe770 100644
--- a/frontend/src/core/pages/HomePage.tsx
+++ b/frontend/src/core/pages/HomePage.tsx
@@ -15,12 +15,12 @@ import {
useNavigationActions,
} from "@app/contexts/NavigationContext";
import { useViewer } from "@app/contexts/ViewerContext";
+import { useLocation } from "react-router-dom";
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 FileSidebar from "@app/components/shared/FileSidebar";
import FileManager from "@app/components/FileManager";
import LocalIcon from "@app/components/shared/LocalIcon";
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
@@ -56,6 +56,15 @@ export default function HomePage() {
const [activeMobileView, setActiveMobileView] = useState<MobileView>("tools");
const isProgrammaticScroll = useRef(false);
const [configModalOpen, setConfigModalOpen] = useState(false);
+ const [fileSidebarCollapsed, setFileSidebarCollapsed] = useState(false);
+ const location = useLocation();
+
+ // Open the config modal whenever the URL is /settings/* (e.g. from the admin
+ // tour's openConfigModal action which navigates to /settings/overview).
+ useEffect(() => {
+ const isSettings = location.pathname.startsWith("/settings");
+ setConfigModalOpen(isSettings);
+ }, [location.pathname]);
const { activeFiles } = useFileContext();
const navigationState = useNavigationState();
@@ -291,7 +300,6 @@ export default function HomePage() {
<div className="mobile-slide-content">
<div className="flex-1 min-h-0 flex">
<Workbench />
- <RightRail />
</div>
</div>
</div>
@@ -366,11 +374,19 @@ export default function HomePage() {
</div>
) : (
<Group align="flex-start" gap={0} h="100%" className="flex-nowrap flex">
- <QuickAccessBar ref={quickAccessRef} />
- {!hideToolPanel && <ToolPanel />}
+ <FileSidebar
+ ref={quickAccessRef}
+ collapsed={fileSidebarCollapsed}
+ onToggleCollapse={() => setFileSidebarCollapsed((c) => !c)}
+ onOpenSettings={() => setConfigModalOpen(true)}
+ />
<Workbench />
- <RightRail />
+ {!hideToolPanel && <ToolPanel />}
<FileManager selectedTool={selectedTool as any /* FIX ME */} />
+ <AppConfigModal
+ opened={configModalOpen}
+ onClose={() => setConfigModalOpen(false)}
+ />
</Group>
)}
</div>
diff --git a/frontend/src/core/services/fileStorage.ts b/frontend/src/core/services/fileStorage.ts
index e3f59f866f..1676811f51 100644
--- a/frontend/src/core/services/fileStorage.ts
+++ b/frontend/src/core/services/fileStorage.ts
@@ -19,11 +19,14 @@ import {
* Storage record - single source of truth
* Contains all data needed for both StirlingFile and StirlingFileStub
*/
+const THUMBNAIL_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
+
export interface StoredStirlingFileRecord extends BaseFileMetadata {
data: ArrayBuffer;
fileId: FileId; // Matches runtime StirlingFile.fileId exactly
quickKey: string; // Matches runtime StirlingFile.quickKey exactly
thumbnail?: string;
+ thumbnailStoredAt?: number; // Epoch ms — sliding 30-day TTL
url?: string; // For compatibility with existing components
}
@@ -45,6 +48,44 @@ class FileStorageService {
return indexedDBManager.openDatabase(this.dbConfig);
}
+ /** Returns thumbnail if within TTL, otherwise undefined. */
+ private isThumbnailFresh(record: StoredStirlingFileRecord): boolean {
+ if (!record.thumbnail) return false;
+ if (!record.thumbnailStoredAt) return false;
+ return Date.now() - record.thumbnailStoredAt < THUMBNAIL_TTL_MS;
+ }
+
+ /** Fire-and-forget: bump thumbnailStoredAt (or clear expired thumbnail) for a set of ids. */
+ private async bumpThumbnailTTL(ids: FileId[], clear = false): Promise<void> {
+ if (ids.length === 0) return;
+ const db = await this.getDatabase();
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction([this.storeName], "readwrite");
+ const store = transaction.objectStore(this.storeName);
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => reject(transaction.error);
+ transaction.onabort = () => reject(transaction.error);
+
+ // Issue all gets up front — each onsuccess creates a put before the
+ // transaction can auto-commit, keeping it alive until all puts settle.
+ ids.forEach((id) => {
+ const req = store.get(id);
+ req.onsuccess = () => {
+ const record = req.result as StoredStirlingFileRecord | undefined;
+ if (!record) return;
+ if (clear) {
+ record.thumbnail = undefined;
+ record.thumbnailStoredAt = undefined;
+ } else {
+ record.thumbnailStoredAt = Date.now();
+ }
+ store.put(record);
+ };
+ req.onerror = () => reject(req.error);
+ });
+ });
+ }
+
/**
* Store a StirlingFile with its metadata from StirlingFileStub
*/
@@ -66,6 +107,7 @@ class FileStorageService {
createdAt: stub.createdAt,
data: arrayBuffer,
thumbnail: stub.thumbnailUrl,
+ thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
isLeaf: stub.isLeaf ?? true,
remoteStorageId: stub.remoteStorageId,
remoteStorageUpdatedAt: stub.remoteStorageUpdatedAt,
@@ -174,6 +216,9 @@ class FileStorageService {
}
// Create StirlingFileStub from metadata (no file data)
+ const fresh = this.isThumbnailFresh(record);
+ void this.bumpThumbnailTTL([record.id], !fresh);
+
const stub: StirlingFileStub = {
id: record.id,
name: record.name,
@@ -181,7 +226,7 @@ class FileStorageService {
size: record.size,
lastModified: record.lastModified,
quickKey: record.quickKey,
- thumbnailUrl: record.thumbnail,
+ thumbnailUrl: fresh ? record.thumbnail : undefined,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
@@ -215,13 +260,20 @@ class FileStorageService {
const request = store.openCursor();
const stubs: StirlingFileStub[] = [];
+ const tobump: FileId[] = [];
+ const toexpire: FileId[] = [];
+
request.onerror = () => reject(request.error);
request.onsuccess = (event) => {
const cursor = (event.target as IDBRequest).result;
if (cursor) {
const record = cursor.value as StoredStirlingFileRecord;
if (record && record.name && typeof record.size === "number") {
- // Extract metadata only - no file data
+ const fresh = this.isThumbnailFresh(record);
+ if (record.thumbnail) {
+ if (fresh) tobump.push(record.id);
+ else toexpire.push(record.id);
+ }
stubs.push({
id: record.id,
name: record.name,
@@ -229,7 +281,7 @@ class FileStorageService {
size: record.size,
lastModified: record.lastModified,
quickKey: record.quickKey,
- thumbnailUrl: record.thumbnail,
+ thumbnailUrl: fresh ? record.thumbnail : undefined,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
@@ -248,6 +300,8 @@ class FileStorageService {
}
cursor.continue();
} else {
+ void this.bumpThumbnailTTL(tobump);
+ void this.bumpThumbnailTTL(toexpire, true);
resolve(stubs);
}
};
@@ -277,6 +331,8 @@ class FileStorageService {
const store = transaction.objectStore(this.storeName);
const request = store.openCursor();
const leafStubs: StirlingFileStub[] = [];
+ const tobump: FileId[] = [];
+ const toexpire: FileId[] = [];
request.onerror = () => reject(request.error);
request.onsuccess = (event) => {
@@ -290,6 +346,11 @@ class FileStorageService {
typeof record.size === "number" &&
record.isLeaf !== false
) {
+ const fresh = this.isThumbnailFresh(record);
+ if (record.thumbnail) {
+ if (fresh) tobump.push(record.id);
+ else toexpire.push(record.id);
+ }
leafStubs.push({
id: record.id,
name: record.name,
@@ -297,7 +358,7 @@ class FileStorageService {
size: record.size,
lastModified: record.lastModified,
quickKey: record.quickKey,
- thumbnailUrl: record.thumbnail,
+ thumbnailUrl: fresh ? record.thumbnail : undefined,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
@@ -316,6 +377,8 @@ class FileStorageService {
}
cursor.continue();
} else {
+ void this.bumpThumbnailTTL(tobump);
+ void this.bumpThumbnailTTL(toexpire, true);
resolve(leafStubs);
}
};
@@ -338,6 +401,24 @@ class FileStorageService {
});
}
+ /**
+ * Delete multiple StirlingFiles in a single transaction
+ */
+ async deleteMultipleStirlingFiles(ids: FileId[]): Promise<void> {
+ if (ids.length === 0) return;
+ const db = await this.getDatabase();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction([this.storeName], "readwrite");
+ const store = transaction.objectStore(this.storeName);
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => reject(transaction.error);
+ transaction.onabort = () =>
+ reject(transaction.error ?? new Error("Transaction aborted"));
+ ids.forEach((id) => store.delete(id));
+ });
+ }
+
/**
* Update thumbnail for existing file
*/
@@ -354,6 +435,7 @@ class FileStorageService {
const record = getRequest.result as StoredStirlingFileRecord;
if (record) {
record.thumbnail = thumbnail;
+ record.thumbnailStoredAt = Date.now();
const updateRequest = store.put(record);
updateRequest.onsuccess = () => {
diff --git a/frontend/src/core/styles/theme.css b/frontend/src/core/styles/theme.css
index 46809c07a3..e5a02f7a6a 100644
--- a/frontend/src/core/styles/theme.css
+++ b/frontend/src/core/styles/theme.css
@@ -209,13 +209,6 @@
--icon-config-bg: #9ca3af;
--icon-config-color: #ffffff;
- /* RightRail (light) */
- --right-rail-bg: #f5f6f8; /* light background */
- --right-rail-foreground: #e3e4e5; /* panel behind custom tool icons */
- --right-rail-icon: #4b5563; /* icon color */
- --right-rail-icon-disabled: #cecece; /* disabled icon */
- --right-rail-pan-active-bg: #eaeaea;
-
/* Colors for tooltips */
--tooltip-title-bg: #dbefff;
--tooltip-title-color: #31528e;
@@ -228,7 +221,7 @@
--icon-inactive-color: #ffffff;
/* New theme colors for text and icons */
- --tools-text-and-icon-color: #374151;
+ --tools-text-and-icon-color: var(--text-primary);
/* Tool picker sticky header variables (light mode) */
--tool-header-bg: #dbefff;
@@ -251,6 +244,7 @@
/* Placeholder text colors */
--search-text-and-icon-color: #6b7382;
+ --input-bg: #ffffff;
/* Tool panel search bar background colors */
--tool-panel-search-bg: #eff1f4;
@@ -552,13 +546,6 @@
--icon-inactive-bg: #2a2f36;
--icon-inactive-color: #6e7581;
- /* RightRail (dark) */
- --right-rail-bg: #1f2329; /* dark background */
- --right-rail-foreground: #2a2f36; /* panel behind custom tool icons */
- --right-rail-icon: #bcbebf; /* icon color */
- --right-rail-icon-disabled: #43464b; /* disabled icon */
- --right-rail-pan-active-bg: #eaeaea;
-
/* Dark mode tooltip colors */
--tooltip-title-bg: #4b525a;
--tooltip-title-color: #fff;
@@ -620,7 +607,7 @@
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.4);
--shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.4);
- --tools-text-and-icon-color: #d0d6dc;
+ --tools-text-and-icon-color: var(--text-primary);
/* Tool picker sticky header variables (dark mode) */
--tool-header-bg: #2a2f36;
@@ -639,6 +626,7 @@
/* Placeholder text colors (dark mode) */
--search-text-and-icon-color: #ffffff !important;
+ --input-bg: #4b525a;
/* Tool panel search bar background colors (dark mode) */
--tool-panel-search-bg: #1f2329;
@@ -1008,6 +996,17 @@
--shadow-color: rgba(0, 0, 0, 0.75);
}
+/* ---- Wordmark light/dark switching (use instead of JS colorScheme checks) ---- */
+.wordmark-dark-only {
+ display: none;
+}
+[data-mantine-color-scheme="dark"] .wordmark-light-only {
+ display: none;
+}
+[data-mantine-color-scheme="dark"] .wordmark-dark-only {
+ display: block;
+}
+
/* Theme-aware image display utilities */
/* Use .theme-img-light-only for images to show in light mode only */
/* Use .theme-img-dark-only for images to show in dark mode only */
diff --git a/frontend/src/core/tests/enterprise/license-and-features.spec.ts b/frontend/src/core/tests/enterprise/license-and-features.spec.ts
index 26fb469d96..c7f9bc367a 100644
--- a/frontend/src/core/tests/enterprise/license-and-features.spec.ts
+++ b/frontend/src/core/tests/enterprise/license-and-features.spec.ts
@@ -24,7 +24,7 @@ async function uiLogin(page: import("@playwright/test").Page) {
await page.locator('button[type="submit"]').click();
await page.waitForURL("/", { timeout: 15_000 });
await expect(
- page.getByRole("link", { name: /^Tools$/i }).first(),
+ page.locator('[data-testid="config-button"]').first(),
).toBeVisible({ timeout: 15_000 });
}
diff --git a/frontend/src/core/tests/enterprise/oauth-keycloak-login.spec.ts b/frontend/src/core/tests/enterprise/oauth-keycloak-login.spec.ts
index 96b99b2d13..eba8995227 100644
--- a/frontend/src/core/tests/enterprise/oauth-keycloak-login.spec.ts
+++ b/frontend/src/core/tests/enterprise/oauth-keycloak-login.spec.ts
@@ -53,7 +53,7 @@ test.describe("Enterprise OAuth (Keycloak) — full SSO flow", () => {
timeout: 30_000,
});
await expect(
- page.getByRole("link", { name: /^Tools$/i }).first(),
+ page.locator('[data-testid="config-button"]').first(),
).toBeVisible({ timeout: 15_000 });
// ── 2. Identity surfaced in settings → Account ────────────
diff --git a/frontend/src/core/tests/enterprise/saml-keycloak-login.spec.ts b/frontend/src/core/tests/enterprise/saml-keycloak-login.spec.ts
index e8fe288fe8..416b68bfed 100644
--- a/frontend/src/core/tests/enterprise/saml-keycloak-login.spec.ts
+++ b/frontend/src/core/tests/enterprise/saml-keycloak-login.spec.ts
@@ -47,7 +47,7 @@ test.describe("Enterprise SAML (Keycloak) — full SSO flow", () => {
timeout: 30_000,
});
await expect(
- page.getByRole("link", { name: /^Tools$/i }).first(),
+ page.locator('[data-testid="config-button"]').first(),
).toBeVisible({ timeout: 15_000 });
// ── 2. Identity in settings → Account ────────────────────
diff --git a/frontend/src/core/tests/helpers/api-stubs.ts b/frontend/src/core/tests/helpers/api-stubs.ts
index 4dd0286b1d..a8291a181e 100644
--- a/frontend/src/core/tests/helpers/api-stubs.ts
+++ b/frontend/src/core/tests/helpers/api-stubs.ts
@@ -118,6 +118,8 @@ const DEFAULT_ENDPOINTS_AVAILABILITY = Object.fromEntries(
export interface MockAppApiOptions {
/** Override `enableLogin`. Default `false` — app loads in anonymous mode. */
enableLogin?: boolean;
+ /** Override `isAdmin` in app-config. Default `false`. */
+ isAdmin?: boolean;
/** Override the logged-in user returned by `/auth/me`. */
user?: {
id?: number;
@@ -145,6 +147,7 @@ export async function mockAppApis(
): Promise<void> {
const {
enableLogin = false,
+ isAdmin = false,
user = {
id: 1,
username: "testuser",
@@ -167,6 +170,7 @@ export async function mockAppApis(
route.fulfill({
json: {
enableLogin,
+ isAdmin,
languages,
defaultLocale,
},
@@ -226,6 +230,11 @@ export async function mockAppApis(
route.fulfill({ json: {} }),
);
+ // License info — stubbed so admin settings doesn't log proxy errors
+ await page.route("**/api/v1/admin/license-info", (route: Route) =>
+ route.fulfill({ json: { licenseType: "FREE", valid: true, maxUsers: 5 } }),
+ );
+
// Settings sections touched by the settings page
await page.route("**/api/v1/admin/settings", (route: Route) =>
route.fulfill({ json: {} }),
diff --git a/frontend/src/core/tests/helpers/stub-test-base.ts b/frontend/src/core/tests/helpers/stub-test-base.ts
index 72116e909a..5752108d42 100644
--- a/frontend/src/core/tests/helpers/stub-test-base.ts
+++ b/frontend/src/core/tests/helpers/stub-test-base.ts
@@ -1,5 +1,6 @@
import { test as base, expect } from "@playwright/test";
import {
+ bypassOnboarding,
mockAppApis,
seedCookieConsent,
skipOnboarding,
@@ -32,21 +33,42 @@ import {
* To override the stub options (enable login, change user, …):
* test.use({ stubOptions: { enableLogin: true } });
*
+ * To seed a JWT so the user is treated as logged-in (required when
+ * `enableLogin: true`, otherwise Landing redirects to /login):
+ * test.use({ stubOptions: { enableLogin: true }, seedJwt: true });
+ *
* To register a narrower stub for a tool endpoint, just call `page.route(...)`
* after the fixture runs — Playwright uses last-registered-wins.
*/
type StubFixtures = {
stubOptions: MockAppApiOptions;
autoGoto: false | string;
+ seedJwt: boolean;
};
+// Minimal JWT-shaped value — the proprietary auth client only checks for
+// the token's *presence* in localStorage before treating the user as
+// logged-in; the stubbed `/auth/me` route supplies the actual user.
+const STUB_JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzdHViLXVzZXIifQ.signature";
+
export const test = base.extend<StubFixtures>({
stubOptions: [{}, { option: true }],
autoGoto: ["/", { option: true }],
+ seedJwt: [false, { option: true }],
- page: async ({ page, stubOptions, autoGoto }, use) => {
+ page: async ({ page, stubOptions, autoGoto, seedJwt }, use) => {
await seedCookieConsent(page);
- await skipOnboarding(page);
+ if (seedJwt) {
+ // Logged-in users hit the orchestrator path that surfaces the
+ // analytics opt-in / MFA prompts — use the stronger bypass-all flag
+ // so those overlays don't block clicks.
+ await bypassOnboarding(page);
+ await page.addInitScript((token) => {
+ localStorage.setItem("stirling_jwt", token);
+ }, STUB_JWT);
+ } else {
+ await skipOnboarding(page);
+ }
await mockAppApis(page, stubOptions);
if (autoGoto !== false) {
// waitUntil: 'domcontentloaded' avoids hanging on third-party CDN
diff --git a/frontend/src/core/tests/stubbed/automation-page-ui.spec.ts b/frontend/src/core/tests/stubbed/automation-page-ui.spec.ts
index fc2495fc4f..126e13060c 100644
--- a/frontend/src/core/tests/stubbed/automation-page-ui.spec.ts
+++ b/frontend/src/core/tests/stubbed/automation-page-ui.spec.ts
@@ -81,8 +81,8 @@ test.describe("11. Automation Page", () => {
test.describe("11.1 Automation - Suggested Workflows", () => {
test("should display saved and suggested workflows", async ({ page }) => {
- const automateLink = page.locator('a[href="/automate"]').first();
- await expect(automateLink).toBeVisible();
+ // Step 1: Verify the Automation Selection header is present
+ await expect(page).toHaveURL(/\/automate/);
await expect(
page.getByText(/Automation Selection/i).first(),
diff --git a/frontend/src/core/tests/stubbed/compare.spec.ts b/frontend/src/core/tests/stubbed/compare.spec.ts
index 7963c4272c..6bcaaee538 100644
--- a/frontend/src/core/tests/stubbed/compare.spec.ts
+++ b/frontend/src/core/tests/stubbed/compare.spec.ts
@@ -39,12 +39,10 @@ async function uploadIntoSlot(
filePath: string,
expectedFilename: string,
) {
- await page.locator(`[data-testid="compare-slot-${role}-add"]`).click();
- await page.waitForSelector(".mantine-Modal-overlay", {
- state: "visible",
- timeout: 5000,
- });
- await page.locator('[data-testid="file-input"]').setInputFiles(filePath);
+ // Set files directly on the hidden input (always in DOM, no popover needed)
+ await page
+ .getByTestId(`compare-slot-${role}-add-input`)
+ .setInputFiles(filePath);
// The slot becoming filled is the user-visible outcome we actually care
// about. Don't gate on the modal-overlay close animation — Mantine 9's
@@ -77,39 +75,6 @@ test.describe("Compare tool slot selection", () => {
});
});
- test("Original slot fills when a PDF is dropped via the landing dropzone", async ({
- page,
- }) => {
- // Regression guard for the "middle state" bug: the landing dropzone path
- // (FileManager's hidden file-input used by the drop-prompt on the empty
- // workbench) dispatches ADD_FILES and SET_SELECTED_FILES on a different
- // cadence than the modal-based upload. During the window where files.ids
- // has the new file but selectedFileIds is still empty, the slot would
- // show the placeholder unless the auto-fill falls back to allIds.
- await navigateToCompare(page);
-
- const baseSlot = page.locator('[data-testid="compare-slot-base"]');
- await expect(baseSlot).toHaveAttribute("data-slot-state", "empty");
-
- // Target the visible landing-prompt file input on the empty Compare tool.
- const visibleFileInput = page.locator(
- 'input[type="file"]:not([data-testid="file-input"])',
- );
- await visibleFileInput.first().setInputFiles(PDF_A);
-
- // Assert the slot fills within a short window. Without the allIds
- // fallback the slot stayed on the placeholder for 4+ seconds in manual
- // testing because the SET_SELECTED_FILES dispatch lagged the ADD_FILES
- // dispatch by many renders.
- await expect(baseSlot).toHaveAttribute("data-slot-state", "filled", {
- timeout: 2000,
- });
- await expect(baseSlot).toHaveAttribute(
- "data-slot-filename",
- "compare_sample_a.pdf",
- );
- });
-
test("uploading a PDF via the Original add button fills the Original slot", async ({
page,
}) => {
@@ -164,85 +129,74 @@ test.describe("Compare tool slot selection", () => {
await expect(compareButton).toBeEnabled();
});
- test("picking a stored file from the recent-files modal unions it with the current selection", async ({
+ test("picking a saved file from the FileSelectorPicker popover fills the comparison slot", async ({
page,
}) => {
- // This test specifically guards the handleRecentFileSelect code path in
- // FilesModalContext. Setup:
- // 1. Upload PDF_A so it lands in IndexedDB storage.
- // 2. Reload the page — workbench resets but IndexedDB persists.
- // 3. Upload PDF_B fresh so only PDF_B is in the workbench and selected.
- // 4. Open the Files modal and pick PDF_A from "Recent".
- // Without the fix, step 4 REPLACES the selection with [PDF_A] and the
- // Compare Original slot jumps to PDF_A while Edited stays empty. With the
- // fix, the selection becomes [PDF_B, PDF_A] and both slots populate.
+ // Guards the FileSelectorPicker "Saved files" tab flow. Steps:
+ // 1. Upload PDF_A into the base slot → stored in IndexedDB and slot fills.
+ // 2. Clear the base slot (X button) so both slots are empty again.
+ // 3. Upload PDF_B into the base slot.
+ // 4. Open the comparison slot's FileSelectorPicker and pick PDF_A from
+ // the Saved files tab.
+ // Result: base = PDF_B, comparison = PDF_A.
- // Step 1 — upload PDF_A so it's persisted in IndexedDB.
await navigateToCompare(page);
+
+ // Step 1 — upload PDF_A and confirm base slot fills (also persists to IndexedDB).
await uploadIntoSlot(page, "base", PDF_A, "compare_sample_a.pdf");
- // Step 2 — reload. Workbench clears but IndexedDB retains PDF_A.
- // page.goto reuses the mocked routes and re-applies bypassOnboarding.
- await page.goto("/?bypassOnboarding=true");
- await page.waitForSelector('[data-tour="tool-button-compare"]', {
- timeout: 10000,
- });
- await navigateToCompare(page);
+ // Step 2 — clear the base slot via the X button so both slots reset.
+ await page
+ .locator('[data-testid="compare-slot-base"]')
+ .getByRole("button", { name: "Remove file" })
+ .click();
await expect(
page.locator('[data-testid="compare-slot-base"]'),
).toHaveAttribute("data-slot-state", "empty");
- // Step 3 — upload PDF_B fresh. Now workbench = [PDF_B], IndexedDB = [A, B].
+ // Step 3 — upload PDF_B into base. IndexedDB now has both A and B.
await uploadIntoSlot(page, "base", PDF_B, "compare_sample_b.pdf");
await expect(
page.locator('[data-testid="compare-slot-comparison"]'),
).toHaveAttribute("data-slot-state", "empty");
- // Step 4 — open the modal from the sidebar Files button and pick PDF_A
- // from the recent list.
- await page.getByTestId("files-button").click();
- await page.waitForSelector(".mantine-Modal-overlay", {
+ // Step 4 — open the comparison slot's FileSelectorPicker and pick PDF_A
+ // from the Saved files tab.
+ await page.locator('[data-testid="compare-slot-comparison-add"]').click();
+
+ // Wait for the popover dropdown to open (withinPortal → attaches to body).
+ await page.waitForSelector('[aria-pressed="true"]', {
state: "visible",
timeout: 5000,
});
- // The recent-files list renders an entry per stored file. Click the
- // checkbox for PDF_A (NOT the ACTIVE entry for PDF_B). We target the
- // label text to disambiguate.
- const pdfARow = page
- .locator(".mantine-Modal-root")
- .locator("text=compare_sample_a.pdf")
- .first();
+ // The list should contain PDF_A (PDF_B is excluded as it's in the base slot).
+ const pdfARow = page.locator("text=compare_sample_a.pdf").first();
await pdfARow.click();
- // Confirm selection via "Open File".
- await page.getByRole("button", { name: "Open File" }).click();
- await page.waitForSelector(".mantine-Modal-overlay", {
- state: "hidden",
- timeout: 10000,
- });
-
- // Both slots must be populated. Specifically, the Original slot must still
- // be PDF_B (the pre-existing selection, not clobbered) and the Edited slot
- // must be PDF_A (newly unioned in).
+ // Comparison slot must fill with PDF_A; base slot stays PDF_B.
const baseSlot = page.locator('[data-testid="compare-slot-base"]');
const comparisonSlot = page.locator(
'[data-testid="compare-slot-comparison"]',
);
- await expect(baseSlot).toHaveAttribute("data-slot-state", "filled", {
- timeout: 10000,
- });
await expect(comparisonSlot).toHaveAttribute("data-slot-state", "filled", {
timeout: 10000,
});
+ await expect(comparisonSlot).toHaveAttribute(
+ "data-slot-filename",
+ "compare_sample_a.pdf",
+ );
+ await expect(baseSlot).toHaveAttribute("data-slot-state", "filled");
+ await expect(baseSlot).toHaveAttribute(
+ "data-slot-filename",
+ "compare_sample_b.pdf",
+ );
const compareButton = page.getByRole("button", { name: "Compare" });
await expect(compareButton).toBeEnabled();
});
- test("Clear selected empties both slots, clears the selection banner, and removes files from the workbench", async ({
- page,
- }) => {
+ test("Clear selected empties both slots", async ({ page }) => {
await navigateToCompare(page);
await uploadIntoSlot(page, "base", PDF_A, "compare_sample_a.pdf");
await uploadIntoSlot(page, "comparison", PDF_B, "compare_sample_b.pdf");
@@ -257,9 +211,17 @@ test.describe("Compare tool slot selection", () => {
// Open the Clear confirmation modal and confirm.
await page.getByRole("button", { name: "Clear selected" }).click();
- await page.getByRole("button", { name: "Clear and return" }).click();
+ // Wait for the confirmation modal to appear before clicking confirm.
+ await page.waitForSelector(".mantine-Modal-overlay", {
+ state: "visible",
+ timeout: 5000,
+ });
+ await page
+ .locator('[role="dialog"]')
+ .getByRole("button", { name: "Clear Selected" })
+ .click();
- // The tool re-mounts on workbench switch; wait for the empty-state base slot.
+ // Both slots must be empty after clearing.
await page.waitForSelector(
'[data-testid="compare-slot-base"][data-slot-state="empty"]',
{ timeout: 10000 },
@@ -267,11 +229,5 @@ test.describe("Compare tool slot selection", () => {
await expect(
page.locator('[data-testid="compare-slot-comparison"]'),
).toHaveAttribute("data-slot-state", "empty");
-
- // The "N files selected" / "Selected: X" banner must be gone because the
- // files have been removed from the workbench.
- await expect(
- page.getByText(/\d+\s+files?\s+selected|Selected:\s+/i),
- ).toHaveCount(0);
});
});
diff --git a/frontend/src/core/tests/stubbed/language-localization.spec.ts b/frontend/src/core/tests/stubbed/language-localization.spec.ts
index 3d31f650c3..b351acb1be 100644
--- a/frontend/src/core/tests/stubbed/language-localization.spec.ts
+++ b/frontend/src/core/tests/stubbed/language-localization.spec.ts
@@ -17,14 +17,26 @@ test.describe("13. Language / Localization", () => {
test.describe("13.1 Language Switcher", () => {
test("should switch UI text when language is changed", async ({ page }) => {
- // Step 1: Locate the Language selector in the right rail
- // The LanguageSelector uses an ActionIcon with a "language" icon and optional title="Language"
- const languageButton = page
- .locator(".right-rail-icon")
- .filter({ has: page.locator('[class*="language"]') })
- .first()
- .or(page.locator('button[title="Language"]').first())
- .or(page.locator('[data-tour="right-rail-settings"] button').nth(1));
+ // Step 1: Locate the Language selector.
+ // The language selector is accessed via Settings > General.
+
+ let languageButton = page
+ .locator('[data-testid="language-selector-button"]')
+ .first();
+
+ if (
+ !(await languageButton.isVisible({ timeout: 1000 }).catch(() => false))
+ ) {
+ // Open Settings to access the language selector in the General section
+ await page.locator('[data-testid="config-button"]').first().click();
+ await page
+ .locator(".mantine-Modal-content")
+ .first()
+ .waitFor({ state: "visible", timeout: 5000 });
+ languageButton = page
+ .locator('[data-testid="language-selector-button"]')
+ .first();
+ }
// Step 2: Click the language button
await expect(languageButton).toBeVisible({ timeout: 5000 });
diff --git a/frontend/src/core/tests/stubbed/main-dashboard.spec.ts b/frontend/src/core/tests/stubbed/main-dashboard.spec.ts
index 616099421c..346f9ccae1 100644
--- a/frontend/src/core/tests/stubbed/main-dashboard.spec.ts
+++ b/frontend/src/core/tests/stubbed/main-dashboard.spec.ts
@@ -10,21 +10,9 @@ test.describe("2. Main Dashboard / Home Page", () => {
test("should display all navigation elements and tool categories", async ({
page,
}) => {
- await expect(
- page.getByRole("link", { name: /^Tools$/i }).first(),
- ).toBeVisible({ timeout: 10000 });
- await expect(
- page.locator('[data-testid="read-button"]').first(),
- ).toBeVisible();
- await expect(
- page.locator('[data-testid="automate-button"]').first(),
- ).toBeVisible();
await expect(
page.locator('[data-testid="files-button"]').first(),
- ).toBeVisible();
- await expect(
- page.locator('[data-tour="help-button"]').first(),
- ).toBeVisible();
+ ).toBeVisible({ timeout: 10000 });
await expect(
page.locator('[data-testid="config-button"]').first(),
).toBeVisible();
diff --git a/frontend/src/core/tests/stubbed/merge-tool.spec.ts b/frontend/src/core/tests/stubbed/merge-tool.spec.ts
index e47a5401db..4db02a54cd 100644
--- a/frontend/src/core/tests/stubbed/merge-tool.spec.ts
+++ b/frontend/src/core/tests/stubbed/merge-tool.spec.ts
@@ -32,10 +32,9 @@ test.describe("5. Merge Tool", () => {
await expect(mergeButton).toBeDisabled();
// Step 4: Verify the file upload drop zone is visible
+ // (input[type="file"] is excluded — it is hidden in the FileSidebar)
await expect(
- page
- .locator('[class*="upload"], [class*="dropzone"], input[type="file"]')
- .first(),
+ page.locator('[class*="upload"], [class*="dropzone"]').first(),
).toBeVisible();
});
});
diff --git a/frontend/src/core/tests/stubbed/navigation.spec.ts b/frontend/src/core/tests/stubbed/navigation.spec.ts
index f30b9a5734..00305c16fd 100644
--- a/frontend/src/core/tests/stubbed/navigation.spec.ts
+++ b/frontend/src/core/tests/stubbed/navigation.spec.ts
@@ -31,8 +31,9 @@ test.describe("Navigation", () => {
await page.locator('a[href="/merge"]').first().click();
await expect(page).toHaveURL(/\/merge/);
+ // In the redesigned UI, "Back to tools" button replaces the old "Tools" link
await page
- .getByRole("link", { name: /^Tools$/i })
+ .getByRole("button", { name: /Back to tools/i })
.first()
.click();
await expect(page).toHaveURL("/");
diff --git a/frontend/src/core/tests/stubbed/pdf-text-search.spec.ts b/frontend/src/core/tests/stubbed/pdf-text-search.spec.ts
index 8da8d8e4e7..a3bea2f1e2 100644
--- a/frontend/src/core/tests/stubbed/pdf-text-search.spec.ts
+++ b/frontend/src/core/tests/stubbed/pdf-text-search.spec.ts
@@ -28,27 +28,23 @@ test.describe("Reader — in-document text search", () => {
timeout: 10_000,
});
- // The viewer toolbar exposes a search button or the search input directly.
- const searchTrigger = page
- .getByRole("button", { name: /search|find/i })
- .or(page.getByPlaceholder(/search|find in document/i))
+ // The WorkbenchBar exposes a "Search PDF" button (aria-label="Search PDF")
+ // that opens a Popover with the in-document search input.
+ // We target this button specifically to avoid matching the FileSidebar's
+ // "Search" button (a <div role="button">) which appears earlier in the DOM.
+ const searchBtn = page
+ .getByRole("button", { name: /^Search PDF$/i })
.first();
- if (
- !(await searchTrigger.isVisible({ timeout: 5_000 }).catch(() => false))
- ) {
- test.skip(true, "Reader toolbar search not visible on this build");
+ if (!(await searchBtn.isVisible({ timeout: 5_000 }).catch(() => false))) {
+ test.skip(true, "Search PDF button not visible on this build");
return;
}
- // If it's a button, click it to open the input; if it's an input
- // already, fill directly.
- const tag = await searchTrigger.evaluate((el) => el.tagName);
- if (tag === "BUTTON") {
- await searchTrigger.click();
- }
+ await searchBtn.click();
- const input = page.getByPlaceholder(/search|find/i).first();
+ // The SearchInterface renders inside a Popover with placeholder "Enter search term..."
+ const input = page.getByPlaceholder(/enter search term/i).first();
await expect(input).toBeVisible({ timeout: 5_000 });
await input.fill("page");
await expect(input).toHaveValue("page");
diff --git a/frontend/src/core/tests/stubbed/settings.spec.ts b/frontend/src/core/tests/stubbed/settings.spec.ts
index 43a7c58aed..ebd82df7c7 100644
--- a/frontend/src/core/tests/stubbed/settings.spec.ts
+++ b/frontend/src/core/tests/stubbed/settings.spec.ts
@@ -54,8 +54,9 @@ test.describe("Settings dialog", () => {
}) => {
await openSettings(page);
await closeSettings(page);
+ // Verify the main UI is restored — the FileSidebar is always visible
await expect(
- page.locator('[data-tour="quick-access-bar"]').first(),
+ page.locator('[data-testid="files-button"]').first(),
).toBeVisible();
});
@@ -70,8 +71,14 @@ test.describe("Settings dialog", () => {
return;
}
+ // Click the visible label wrapper rather than the hidden input directly —
+ // force-clicking the input doesn't register a state change in Firefox.
+ const toggleLabel = dialog
+ .locator('label:has(input[role="switch"]), .mantine-Switch-body')
+ .first();
+
const before = await toggle.isChecked();
- await toggle.click({ force: true });
+ await toggleLabel.click();
const after = await toggle.isChecked();
expect(after).not.toBe(before);
@@ -83,7 +90,7 @@ test.describe("Settings dialog", () => {
// Restore
if (persisted !== before) {
- await toggle.click({ force: true });
+ await toggleLabel.click();
}
});
diff --git a/frontend/src/core/tests/stubbed/tool-pages-common.spec.ts b/frontend/src/core/tests/stubbed/tool-pages-common.spec.ts
index c94fc72842..250bff4474 100644
--- a/frontend/src/core/tests/stubbed/tool-pages-common.spec.ts
+++ b/frontend/src/core/tests/stubbed/tool-pages-common.spec.ts
@@ -17,10 +17,9 @@ test.describe("4. PDF Tool Pages - Common Patterns", () => {
await expect(actionButton).toBeDisabled();
// Step 3: Verify the file upload area is displayed
+ // (input[type="file"] is excluded — it is hidden in the FileSidebar)
await expect(
- page
- .locator('[class*="upload"], [class*="dropzone"], input[type="file"]')
- .first(),
+ page.locator('[class*="upload"], [class*="dropzone"]').first(),
).toBeVisible();
// Step 4: Verify that clicking the disabled action button does nothing
@@ -37,10 +36,11 @@ test.describe("4. PDF Tool Pages - Common Patterns", () => {
await page.goto("/compress");
await page.waitForLoadState("domcontentloaded");
- // Step 2: Click the sidebar "Tools" link to go back to /.
- // Prefer the sidebar link to the breadcrumb: on webkit the breadcrumb
- // click doesn't always trigger router navigation.
- const homeLink = page.getByRole("link", { name: /^Tools$/i }).first();
+ // Step 2: Click the "Back to tools" button in ToolPanel to go back to /.
+ // In the redesigned UI this replaces the old "Tools" sidebar link.
+ const homeLink = page
+ .getByRole("button", { name: /Back to tools/i })
+ .first();
await homeLink.click();
// Step 3: Verify navigation back to the home dashboard
diff --git a/frontend/src/core/tests/stubbed/tour-onboarding.spec.ts b/frontend/src/core/tests/stubbed/tour-onboarding.spec.ts
index 20e424ded3..2cfa47a3e5 100644
--- a/frontend/src/core/tests/stubbed/tour-onboarding.spec.ts
+++ b/frontend/src/core/tests/stubbed/tour-onboarding.spec.ts
@@ -1,65 +1,227 @@
+import path from "path";
import { test, expect } from "@app/tests/helpers/stub-test-base";
+import { uploadFiles, openSettings } from "@app/tests/helpers/ui-helpers";
-test.describe("15. Tour/Onboarding", () => {
- test.describe("15.1 Tour Button", () => {
- test("should start and dismiss tour guide", async ({ page }) => {
- // Step 1: Click the Tours button in the quick access bar (identified by data-tour="help-button")
- const tourButton = page.locator('[data-tour="help-button"]').first();
- await expect(tourButton).toBeVisible({ timeout: 5000 });
- await tourButton.click();
-
- // Step 2: Verify the tours menu opens with tour options
- const toursMenu = page.locator(".mantine-Menu-dropdown").first();
- await expect(toursMenu).toBeVisible({ timeout: 5000 });
-
- // Step 3: Click on the "See what's new in V2" tour option to start a tour
- const whatsNewOption = page.getByText(/what.?s new|See what/i).first();
- await expect(whatsNewOption).toBeVisible({ timeout: 5000 });
- await whatsNewOption.click();
-
- // Step 4: Verify the reactour popover appears (tour has started)
- const tourPopover = page.locator(".reactour__popover").first();
- await expect(tourPopover).toBeVisible({ timeout: 10000 });
-
- // Step 5: Dismiss the tour by clicking the close button inside the popover
- const closeButton = tourPopover.locator("button").first();
- if (await closeButton.isVisible({ timeout: 3000 }).catch(() => false)) {
- await closeButton.click();
- } else {
- // Fallback: press Escape to close the tour
- await page.keyboard.press("Escape");
- }
+/**
+ * Tour selector integrity tests.
+ *
+ * Each test asserts that a `data-tour="…"` element referenced by one of the
+ * three guided tours (user, admin, whats-new) is actually present in the DOM
+ * at the point in the UI where the tour step would fire. If an element is
+ * renamed or removed the test fails immediately, surfacing the breakage before
+ * it silently breaks the tour for real users.
+ *
+ * Selectors under test come from:
+ * - userStepsConfig.ts
+ * - adminStepsConfig.ts
+ * - whatsNewStepsConfig.ts
+ */
+
+const SAMPLE_PDF = path.join(__dirname, "../test-fixtures/sample.pdf");
- // Step 6: Verify the tour popover disappears
- await expect(tourPopover).not.toBeVisible({ timeout: 5000 });
+// ---------------------------------------------------------------------------
+// 15.1 Static layout — always visible on the main page
+// ---------------------------------------------------------------------------
+test.describe("15.1 Tour selectors — static layout", () => {
+ test("tool-panel is present", async ({ page }) => {
+ await expect(page.locator('[data-tour="tool-panel"]').first()).toBeVisible({
+ timeout: 10_000,
});
});
- test.describe("15.2 Tour Tooltip", () => {
- test("should show and dismiss tour tooltip", async ({ page }) => {
- // Step 1: Check if a tours tooltip with a close button appears near the help button
- // The tooltip uses the custom Tooltip component with showCloseButton enabled
- const tooltipContent = page
- .locator('[data-radix-popper-content-wrapper], [role="tooltip"]')
- .first();
+ test("quick-access-bar (FileSidebar) is present", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="quick-access-bar"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
- // Step 2: If a tooltip with a close button is visible, dismiss it
- const closeButton = tooltipContent.locator("button").first();
- if (await closeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
- await closeButton.click();
+ test("files-button is present", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="files-button"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
- // Step 3: Verify the tooltip content disappears
- await expect(tooltipContent).not.toBeVisible({ timeout: 5000 });
- }
+ test("config-button is present", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="config-button"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
- // Step 4: Refresh the page and verify it loads normally
- await page.reload();
- await page.waitForLoadState("domcontentloaded");
+ test("tool-button-crop is present in tool panel", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="tool-button-crop"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ // help-button: not yet implemented in the redesigned FileSidebar layout.
+ // Re-enable once a tours/help entry point is added to the new UI.
+ test.skip("help-button is present — TODO: add to new sidebar layout", async ({
+ page,
+ }) => {
+ await expect(page.locator('[data-tour="help-button"]').first()).toBeVisible(
+ { timeout: 10_000 },
+ );
+ });
+});
- // Step 5: Verify the page loaded (search box or navigation visible)
- await expect(page.getByPlaceholder(/search|cari/i).first()).toBeVisible({
- timeout: 10000,
- });
+// ---------------------------------------------------------------------------
+// 15.2 Tour selectors — files modal
+// ---------------------------------------------------------------------------
+test.describe("15.2 Tour selectors — files modal", () => {
+ test("file-sources is present when files modal is open", async ({ page }) => {
+ await page.getByTestId("files-button").click();
+ await expect(
+ page.locator('[data-tour="file-sources"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await page.keyboard.press("Escape");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 15.3 Tour selectors — workbench elements (require a loaded file)
+// ---------------------------------------------------------------------------
+test.describe("15.3 Tour selectors — workbench with file", () => {
+ test.beforeEach(async ({ page }) => {
+ await uploadFiles(page, SAMPLE_PDF);
+ });
+
+ test("workbench is present", async ({ page }) => {
+ await expect(page.locator('[data-tour="workbench"]').first()).toBeVisible({
+ timeout: 10_000,
});
});
+
+ test("view-switcher is present in viewer mode", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="view-switcher"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 15.4 Tour selectors — active files view (file-card-checkbox, file-card-pin)
+// Two files → app auto-navigates to fileEditor (active files) mode.
+// ---------------------------------------------------------------------------
+test.describe("15.4 Tour selectors — active files view", () => {
+ test.beforeEach(async ({ page }) => {
+ // Two files → getStartupNavigationAction returns workbench:"fileEditor"
+ await uploadFiles(page, [SAMPLE_PDF, SAMPLE_PDF]);
+ });
+
+ test("file-card-checkbox is present in active files view", async ({
+ page,
+ }) => {
+ await expect(
+ page.locator('[data-tour="file-card-checkbox"]').first(),
+ ).toBeVisible({ timeout: 15_000 });
+ });
+
+ test("file-card-pin is in DOM when file cards are rendered", async ({
+ page,
+ }) => {
+ // The pin button lives inside HoverActionMenu (CSS-hover driven, always
+ // attached to DOM). Hover over the first file card to ensure the element
+ // is rendered, then assert it is attached.
+ const fileCard = page.locator('[data-tour="file-card-checkbox"]').first();
+ await expect(fileCard).toBeVisible({ timeout: 15_000 });
+ await fileCard.hover();
+ await expect(
+ page.locator('[data-tour="file-card-pin"]').first(),
+ ).toBeAttached({ timeout: 5_000 });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 15.5 Tour selectors — crop tool (crop-settings, run-button)
+// ---------------------------------------------------------------------------
+test.describe("15.5 Tour selectors — crop tool", () => {
+ test.beforeEach(async ({ page }) => {
+ await page.goto("/crop", { waitUntil: "domcontentloaded" });
+ await uploadFiles(page, SAMPLE_PDF);
+ });
+
+ test("crop-settings is present", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="crop-settings"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("run-button is present", async ({ page }) => {
+ await expect(page.locator('[data-tour="run-button"]').first()).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 15.6 Tour selectors — config modal (non-admin)
+// ---------------------------------------------------------------------------
+test.describe("15.6 Tour selectors — config modal", () => {
+ test.beforeEach(async ({ page }) => {
+ await openSettings(page);
+ });
+
+ test("modal-nav is present", async ({ page }) => {
+ await expect(page.locator(".modal-nav").first()).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+
+ test("settings-content-area is present", async ({ page }) => {
+ await expect(
+ page.locator('[data-tour="settings-content-area"]').first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 15.7 Tour selectors — admin config modal nav items
+// Requires isAdmin:true in app-config so the proprietary admin sections render.
+// These nav items are EE-only; the test is skipped in core-only builds where
+// the sections are not registered.
+// ---------------------------------------------------------------------------
+test.describe("15.7 Tour selectors — admin modal nav items", () => {
+ // enableLogin:true makes Landing require a session — seed a JWT so the
+ // dashboard renders instead of redirecting to /login.
+ test.use({
+ stubOptions: { enableLogin: true, isAdmin: true },
+ seedJwt: true,
+ });
+
+ const adminNavSections = [
+ "people",
+ "teams",
+ "adminGeneral",
+ "adminFeatures",
+ "adminEndpoints",
+ "adminDatabase",
+ "adminConnections",
+ "adminAudit",
+ "adminUsage",
+ "help",
+ ] as const;
+
+ for (const section of adminNavSections) {
+ test(`admin-${section}-nav is present`, async ({ page }) => {
+ await openSettings(page);
+ const navItem = page
+ .locator(`[data-tour="admin-${section}-nav"]`)
+ .first();
+ // Use waitFor attached (not isVisible) because admin nav items live in a
+ // scrollable sidebar and may be below the visible fold even when rendered.
+ const isPresent = await navItem
+ .waitFor({ state: "attached", timeout: 5_000 })
+ .then(() => true)
+ .catch(() => false);
+ if (!isPresent) {
+ test.skip(
+ true,
+ `admin-${section}-nav not rendered — section may be EE-only or not yet ported to this build`,
+ );
+ return;
+ }
+ await navItem.scrollIntoViewIfNeeded();
+ await expect(navItem).toBeVisible();
+ });
+ }
});
diff --git a/frontend/src/core/tests/stubbed/workspace-people-teams.spec.ts b/frontend/src/core/tests/stubbed/workspace-people-teams.spec.ts
index 06c32f744a..f6f3f1fb1e 100644
--- a/frontend/src/core/tests/stubbed/workspace-people-teams.spec.ts
+++ b/frontend/src/core/tests/stubbed/workspace-people-teams.spec.ts
@@ -39,7 +39,7 @@ test.describe("26. Workspace Features", () => {
// Step 2: Verify the teams management section loads
await page.waitForTimeout(500);
const bodyContent = await page
- .locator('[role="dialog"], [class*="modal"], [class*="settings"]')
+ .locator(".mantine-Modal-content")
.first()
.textContent();
expect(bodyContent).toBeTruthy();
diff --git a/frontend/src/core/tools/Annotate.tsx b/frontend/src/core/tools/Annotate.tsx
index df95f88f80..563f7db6e8 100644
--- a/frontend/src/core/tools/Annotate.tsx
+++ b/frontend/src/core/tools/Annotate.tsx
@@ -3,7 +3,7 @@ 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 { useAllFiles } from "@app/contexts/FileContext";
import { BaseToolProps } from "@app/types/tool";
import { useSignature } from "@app/contexts/SignatureContext";
import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";
@@ -74,7 +74,7 @@ const isKnownAnnotationTool = (
const Annotate = (_props: BaseToolProps) => {
const { t } = useTranslation();
const { selectedTool, workbench, hasUnsavedChanges } = useNavigation();
- const { selectedFiles } = useFileSelection();
+ const { files: allFiles } = useAllFiles();
const {
signatureApiRef,
annotationApiRef,
@@ -682,7 +682,7 @@ const Annotate = (_props: BaseToolProps) => {
});
const steps =
- selectedFiles.length === 0
+ allFiles.length === 0
? []
: [
{
@@ -725,7 +725,7 @@ const Annotate = (_props: BaseToolProps) => {
];
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles: allFiles,
isCollapsed: false,
},
steps,
diff --git a/frontend/src/core/tools/Automate.tsx b/frontend/src/core/tools/Automate.tsx
index 8cc30eed60..6952bb31c1 100644
--- a/frontend/src/core/tools/Automate.tsx
+++ b/frontend/src/core/tools/Automate.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { useFileSelection } from "@app/contexts/FileContext";
+import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
import { useNavigationActions } from "@app/contexts/NavigationContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
@@ -24,7 +24,7 @@ import { AUTOMATION_STEPS } from "@app/constants/automation";
const Automate = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
const { t } = useTranslation();
- const { selectedFiles } = useFileSelection();
+ const selectedFiles = useViewScopedFiles();
const { actions } = useNavigationActions();
const { registerToolReset } = useToolWorkflow();
diff --git a/frontend/src/core/tools/Compare.tsx b/frontend/src/core/tools/Compare.tsx
index 01bf5e2e21..8f3ca6131f 100644
--- a/frontend/src/core/tools/Compare.tsx
+++ b/frontend/src/core/tools/Compare.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import CompareRoundedIcon from "@mui/icons-material/CompareRounded";
+import CloseIcon from "@mui/icons-material/Close";
import {
Box,
Group,
@@ -9,10 +10,8 @@ import {
Button,
Modal,
ActionIcon,
- SegmentedControl,
} from "@mantine/core";
import SwapVertRoundedIcon from "@mui/icons-material/SwapVertRounded";
-import AddIcon from "@mui/icons-material/Add";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
import { BaseToolProps, ToolComponent } from "@app/types/tool";
@@ -27,14 +26,17 @@ import {
import CompareWorkbenchView from "@app/components/tools/compare/CompareWorkbenchView";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useNavigationActions } from "@app/contexts/NavigationContext";
-import { useFileContext, useFileState } from "@app/contexts/file/fileHooks";
import type { FileId } from "@app/types/file";
import type { StirlingFile } from "@app/types/fileContext";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
import type { CompareWorkbenchData } from "@app/types/compare";
import { getDefaultWorkbench } from "@app/types/workbench";
-import { useFilesModalContext } from "@app/contexts/FilesModalContext";
import { truncateCenter } from "@app/utils/textUtils";
+import {
+ FileSelectorPicker,
+ FileSelectorResult,
+} from "@app/components/shared/FileSelectorPicker";
+import "@app/components/tools/compare/compareView.css";
const CUSTOM_VIEW_ID = "compareWorkbenchView";
const CUSTOM_WORKBENCH_ID = "custom:compareWorkbenchView" as const;
@@ -48,9 +50,6 @@ const Compare = (props: BaseToolProps) => {
setCustomWorkbenchViewData,
clearCustomWorkbenchViewData,
} = useToolWorkflow();
- const { selectors, actions: fileActions } = useFileContext();
- const { state: fileState } = useFileState();
- const { openFilesModal } = useFilesModalContext();
const base = useBaseTool(
"compare",
@@ -58,11 +57,8 @@ const Compare = (props: BaseToolProps) => {
useCompareOperation,
props,
{
- minFiles: 2,
+ minFiles: 0,
ignoreViewerScope: true,
- // Compare auto-fills slots from loaded files via its own effect; the
- // shared reset races and clobbers those writes.
- skipResetParamsOnFirstFiles: true,
},
);
@@ -75,6 +71,20 @@ const Compare = (props: BaseToolProps) => {
);
const [swapConfirmOpen, setSwapConfirmOpen] = useState(false);
const [clearConfirmOpen, setClearConfirmOpen] = useState(false);
+
+ // Slot state — files loaded directly for comparison, never added to workbench
+ const [baseSlot, setBaseSlot] = useState<FileSelectorResult | null>(null);
+ const [compSlot, setCompSlot] = useState<FileSelectorResult | null>(null);
+
+ // Sync params fileIds from slots (needed for operation result matching)
+ useEffect(() => {
+ base.params.setParameters((prev) => ({
+ ...prev,
+ baseFileId: baseSlot?.stirlingFile.fileId ?? null,
+ comparisonFileId: compSlot?.stirlingFile.fileId ?? null,
+ }));
+ }, [baseSlot?.stirlingFile.fileId, compSlot?.stirlingFile.fileId]);
+
const performClearSelected = useCallback(() => {
try {
base.operation.cancelOperation();
@@ -86,37 +96,11 @@ const Compare = (props: BaseToolProps) => {
} catch {
console.error("Failed to reset results");
}
- base.params.setParameters((prev) => ({
- ...prev,
- baseFileId: null,
- comparisonFileId: null,
- }));
- try {
- fileActions.clearSelections();
- } catch {
- console.error("Failed to clear selections");
- }
- // Also remove the loaded files from the workbench so the selection
- // indicator resets to zero. Files stay in IndexedDB so users can re-pick
- // them from "Recent" later.
- try {
- const loadedIds = fileState.files.ids as FileId[];
- if (loadedIds.length > 0) {
- void fileActions.removeFiles(loadedIds, false);
- }
- } catch {
- console.error("Failed to remove workbench files");
- }
+ setBaseSlot(null);
+ setCompSlot(null);
clearCustomWorkbenchViewData(CUSTOM_VIEW_ID);
navigationActions.setWorkbench(getDefaultWorkbench());
- }, [
- base.operation,
- base.params,
- clearCustomWorkbenchViewData,
- fileActions,
- fileState.files.ids,
- navigationActions,
- ]);
+ }, [base.operation, clearCustomWorkbenchViewData, navigationActions]);
useEffect(() => {
const handler = () => {
@@ -138,7 +122,6 @@ const Compare = (props: BaseToolProps) => {
registerCustomWorkbenchView({
id: CUSTOM_VIEW_ID,
workbenchId: CUSTOM_WORKBENCH_ID,
- // Use a static label at registration time to avoid re-registering on i18n changes
label: "Compare view",
icon: compareIcon,
component: CompareWorkbenchView,
@@ -147,99 +130,9 @@ const Compare = (props: BaseToolProps) => {
return () => {
unregisterCustomWorkbenchView(CUSTOM_VIEW_ID);
};
- // Register once; avoid re-registering on translation/prop changes which clears data mid-flight
- }, []);
-
- // On mount: clear selections unless exactly 2 files are loaded.
- useEffect(() => {
- if ((fileState.files.ids as FileId[]).length !== 2) {
- fileActions.clearSelections();
- }
+ // Register once only
}, []);
- // Keep slot params in sync with the current workbench/selection state.
- //
- // The effect must be idempotent: it can fire repeatedly during an upload
- // burst (ADD_FILES, SET_SELECTED_FILES, and downstream dispatches all land
- // in quick succession), and any "did the count transition?" tracking via
- // a ref races with React's batched re-renders under load. With workers=3
- // in CI, that race surfaced as a "Maximum update depth exceeded" crash
- // when the second slot was filled. So the implementation derives the
- // target params purely from current state and bails when there's nothing
- // to change.
- useEffect(() => {
- const selectedIds = fileState.ui.selectedFileIds as FileId[];
- const allIds = fileState.files.ids as FileId[];
-
- if (selectedIds.length > 2) {
- fileActions.setSelectedFiles(selectedIds.slice(0, 2) as FileId[]);
- return;
- }
-
- // When exactly 2 files are loaded but the selection doesn't cover both,
- // promote the selection so Compare can run. Skips when the selection is
- // already correct so we don't dispatch a fresh array reference and
- // retrigger this effect. Covers the upload window where ADD_FILES has
- // landed but SET_SELECTED_FILES is still in flight.
- if (allIds.length === 2) {
- const selectionMatchesAllIds =
- selectedIds.length === 2 &&
- allIds.every((id) => selectedIds.includes(id));
- if (!selectionMatchesAllIds) {
- fileActions.setSelectedFiles([...allIds] as FileId[]);
- }
- }
-
- // Sticky slot mapping: preserve the current slot if its file is still selected,
- // otherwise fill empty slots from the selection in order. This lets users add/remove
- // files from the selection without the other slot being clobbered.
- //
- // Fallback: when there's no selection yet but files are loaded in the workbench,
- // draw from `allIds`. This covers the brief window between ADD_FILES and
- // SET_SELECTED_FILES during an upload (the selection dispatch can lag the file
- // dispatch by several renders), which would otherwise leave the slot showing
- // the "Select the original PDF" placeholder until the selection catches up.
- const sourceIds = selectedIds.length > 0 ? selectedIds : allIds;
- base.params.setParameters((prev) => {
- const prevBase = prev.baseFileId as FileId | null;
- const prevComp = prev.comparisonFileId as FileId | null;
-
- const keepBase =
- prevBase && sourceIds.includes(prevBase) ? prevBase : null;
- const nextBase: FileId | null =
- keepBase ?? ((sourceIds[0] ?? null) as FileId | null);
-
- const keepComp =
- prevComp && sourceIds.includes(prevComp) && prevComp !== nextBase
- ? prevComp
- : null;
- const nextComp: FileId | null =
- keepComp ??
- ((sourceIds.find((id) => id !== nextBase) ?? null) as FileId | null);
-
- if (prev.baseFileId === nextBase && prev.comparisonFileId === nextComp)
- return prev;
- return { ...prev, baseFileId: nextBase, comparisonFileId: nextComp };
- });
- }, [fileState.ui.selectedFileIds, fileState.files.ids]);
-
- // Clear a slot if its file is removed from the workbench.
- useEffect(() => {
- const allIds = fileState.files.ids as FileId[];
- if (params.baseFileId && !allIds.includes(params.baseFileId as FileId)) {
- base.params.setParameters((prev) => ({ ...prev, baseFileId: null }));
- }
- if (
- params.comparisonFileId &&
- !allIds.includes(params.comparisonFileId as FileId)
- ) {
- base.params.setParameters((prev) => ({
- ...prev,
- comparisonFileId: null,
- }));
- }
- }, [fileState.files.ids]);
-
// Track workbench data and drive loading/result state transitions
const lastProcessedAtRef = useRef<number | null>(null);
const lastWorkbenchDataRef = useRef<CompareWorkbenchData | null>(null);
@@ -268,39 +161,23 @@ const Compare = (props: BaseToolProps) => {
(
baseId: FileId | null,
compId: FileId | null,
- options?: {
- baseFile?: StirlingFile | null;
- comparisonFile?: StirlingFile | null;
- },
+ baseFile: StirlingFile | null,
+ comparisonFile: StirlingFile | null,
) => {
- if (!baseId || !compId) {
- return;
- }
-
- const previous = lastWorkbenchDataRef.current;
- const resolvedBaseFile =
- options?.baseFile ??
- (baseId ? selectors.getFile(baseId) : null) ??
- previous?.baseLocalFile ??
- null;
- const resolvedComparisonFile =
- options?.comparisonFile ??
- (compId ? selectors.getFile(compId) : null) ??
- previous?.comparisonLocalFile ??
- null;
+ if (!baseId || !compId) return;
updateWorkbenchData({
result: null,
baseFileId: baseId,
comparisonFileId: compId,
- baseLocalFile: resolvedBaseFile,
- comparisonLocalFile: resolvedComparisonFile,
+ baseLocalFile: baseFile,
+ comparisonLocalFile: comparisonFile,
isLoading: true,
});
lastProcessedAtRef.current = null;
},
- [selectors, updateWorkbenchData],
+ [updateWorkbenchData],
);
useEffect(() => {
@@ -325,20 +202,14 @@ const Compare = (props: BaseToolProps) => {
result.comparison.fileId === comparisonFileId
) {
const previous = lastWorkbenchDataRef.current;
- const baseLocalFile =
- (baseFileId ? selectors.getFile(baseFileId) : null) ??
- previous?.baseLocalFile ??
- null;
- const comparisonLocalFile =
- (comparisonFileId ? selectors.getFile(comparisonFileId) : null) ??
- previous?.comparisonLocalFile ??
- null;
updateWorkbenchData({
result,
baseFileId,
comparisonFileId,
- baseLocalFile,
- comparisonLocalFile,
+ baseLocalFile:
+ baseSlot?.stirlingFile ?? previous?.baseLocalFile ?? null,
+ comparisonLocalFile:
+ compSlot?.stirlingFile ?? previous?.comparisonLocalFile ?? null,
isLoading: false,
});
lastProcessedAtRef.current = processedAt;
@@ -347,207 +218,129 @@ const Compare = (props: BaseToolProps) => {
if (base.operation.isLoading) {
const previous = lastWorkbenchDataRef.current;
- const baseLocalFile =
- (baseFileId ? selectors.getFile(baseFileId) : null) ??
- previous?.baseLocalFile ??
- null;
- const comparisonLocalFile =
- (comparisonFileId ? selectors.getFile(comparisonFileId) : null) ??
- previous?.comparisonLocalFile ??
- null;
updateWorkbenchData({
result: null,
baseFileId,
comparisonFileId,
- baseLocalFile,
- comparisonLocalFile,
+ baseLocalFile:
+ baseSlot?.stirlingFile ?? previous?.baseLocalFile ?? null,
+ comparisonLocalFile:
+ compSlot?.stirlingFile ?? previous?.comparisonLocalFile ?? null,
isLoading: true,
});
return;
}
}, [
base.operation.isLoading,
+ baseSlot,
clearCustomWorkbenchViewData,
+ compSlot,
operation.result,
params.baseFileId,
params.comparisonFileId,
- selectors,
updateWorkbenchData,
]);
const handleExecuteCompare = useCallback(async () => {
- const baseId = params.baseFileId as FileId | null;
- const compId = params.comparisonFileId as FileId | null;
- const baseSel =
- base.selectedFiles.find((file) => file.fileId === baseId) ??
- (baseId ? selectors.getFile(baseId) : null);
- const compSel =
- base.selectedFiles.find((file) => file.fileId === compId) ??
- (compId ? selectors.getFile(compId) : null);
- const selected: StirlingFile[] = [];
- if (baseSel) selected.push(baseSel);
- if (compSel) selected.push(compSel);
-
- prepareWorkbenchForRun(baseId, compId, {
- baseFile: baseSel ?? null,
- comparisonFile: compSel ?? null,
+ if (!baseSlot || !compSlot) return;
+ const baseId = baseSlot.stirlingFile.fileId;
+ const compId = compSlot.stirlingFile.fileId;
+ const selected: StirlingFile[] = [
+ baseSlot.stirlingFile,
+ compSlot.stirlingFile,
+ ];
+
+ prepareWorkbenchForRun(
+ baseId,
+ compId,
+ baseSlot.stirlingFile,
+ compSlot.stirlingFile,
+ );
+ requestAnimationFrame(() => {
+ navigationActions.setWorkbench(CUSTOM_WORKBENCH_ID);
});
- if (baseId && compId) {
- requestAnimationFrame(() => {
- navigationActions.setWorkbench(CUSTOM_WORKBENCH_ID);
- });
- }
- await operation.executeOperation({ ...params }, selected);
+ await operation.executeOperation(
+ { ...params, baseFileId: baseId, comparisonFileId: compId },
+ selected,
+ );
}, [
- base.selectedFiles,
+ baseSlot,
+ compSlot,
navigationActions,
operation,
params,
prepareWorkbenchForRun,
- selectors,
]);
- // Run compare with explicit ids (used after swap so we don't depend on async state propagation)
- const runCompareWithIds = useCallback(
- async (baseId: FileId | null, compId: FileId | null) => {
- const nextParams = {
- ...params,
- baseFileId: baseId,
- comparisonFileId: compId,
- };
- const selected: StirlingFile[] = [];
- const baseSel =
- base.selectedFiles.find((file) => file.fileId === baseId) ??
- (baseId ? selectors.getFile(baseId) : null);
- const compSel =
- base.selectedFiles.find((file) => file.fileId === compId) ??
- (compId ? selectors.getFile(compId) : null);
- if (baseSel) selected.push(baseSel);
- if (compSel) selected.push(compSel);
- prepareWorkbenchForRun(baseId, compId, {
- baseFile: baseSel ?? null,
- comparisonFile: compSel ?? null,
- });
- await operation.executeOperation(nextParams, selected);
- },
- [base.selectedFiles, operation, params, prepareWorkbenchForRun, selectors],
- );
-
const performSwap = useCallback(() => {
- const baseId = params.baseFileId as FileId | null;
- const compId = params.comparisonFileId as FileId | null;
- if (!baseId || !compId) return;
- base.params.setParameters((prev) => ({
- ...prev,
- baseFileId: compId,
- comparisonFileId: baseId,
- }));
+ if (!baseSlot || !compSlot) return;
+ const newBase = compSlot;
+ const newComp = baseSlot;
+ setBaseSlot(newBase);
+ setCompSlot(newComp);
if (operation.result) {
- runCompareWithIds(compId, baseId);
+ const baseId = newBase.stirlingFile.fileId;
+ const compId = newComp.stirlingFile.fileId;
+ const selected: StirlingFile[] = [
+ newBase.stirlingFile,
+ newComp.stirlingFile,
+ ];
+ prepareWorkbenchForRun(
+ baseId,
+ compId,
+ newBase.stirlingFile,
+ newComp.stirlingFile,
+ );
+ requestAnimationFrame(() => {
+ navigationActions.setWorkbench(CUSTOM_WORKBENCH_ID);
+ });
+ void operation.executeOperation(
+ { ...params, baseFileId: baseId, comparisonFileId: compId },
+ selected,
+ );
}
}, [
- base.params,
- operation.result,
- params.baseFileId,
- params.comparisonFileId,
- runCompareWithIds,
+ baseSlot,
+ compSlot,
+ navigationActions,
+ operation,
+ params,
+ prepareWorkbenchForRun,
]);
- // No custom handler; rely on global add flow which auto-selects added files
-
const handleSwap = useCallback(() => {
- const baseId = params.baseFileId as FileId | null;
- const compId = params.comparisonFileId as FileId | null;
- if (!baseId || !compId) return;
+ if (!baseSlot || !compSlot) return;
if (operation.result) {
setSwapConfirmOpen(true);
return;
}
performSwap();
- }, [
- operation.result,
- params.baseFileId,
- params.comparisonFileId,
- performSwap,
- ]);
+ }, [baseSlot, compSlot, operation.result, performSwap]);
- const renderSelectedFile = useCallback(
+ const clearSlot = useCallback((role: "base" | "comparison") => {
+ if (role === "base") setBaseSlot(null);
+ else setCompSlot(null);
+ }, []);
+
+ const renderSlot = useCallback(
(role: "base" | "comparison") => {
- const fileId =
- role === "base" ? params.baseFileId : params.comparisonFileId;
- const stub = fileId ? selectors.getStirlingFileStub(fileId) : undefined;
-
- // Show add button in base if no base file, or in comparison if base exists but no comparison
- const shouldShowAddButton =
- (role === "base" && !params.baseFileId) ||
- (role === "comparison" &&
- params.baseFileId &&
- !params.comparisonFileId);
-
- if (!stub) {
- return (
- <Stack gap={6}>
- <Box
- data-testid={`compare-slot-${role}`}
- data-slot-state="empty"
- style={{
- border: "1px solid var(--border-default)",
- borderRadius: "var(--radius-md)",
- padding: "0.75rem 1rem",
- background: "var(--bg-surface)",
- width: "100%",
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
- cursor: shouldShowAddButton ? "pointer" : "default",
- }}
- onClick={
- shouldShowAddButton ? () => openFilesModal({}) : undefined
- }
- >
- <Text size="sm" c="dimmed">
- {t(
- role === "base"
- ? "compare.original.placeholder"
- : "compare.edited.placeholder",
- role === "base"
- ? "Select the original PDF"
- : "Select the edited PDF",
- )}
- </Text>
- {shouldShowAddButton && (
- <ActionIcon
- data-testid={`compare-slot-${role}-add`}
- variant="filled"
- color="blue"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- openFilesModal({});
- }}
- style={{ flexShrink: 0 }}
- >
- <AddIcon fontSize="small" />
- </ActionIcon>
- )}
- </Box>
- </Stack>
- );
- }
- // Build compact meta line for pages and date
- const dateMs = (stub?.lastModified || stub?.createdAt) ?? null;
- const dateText = dateMs
- ? new Date(dateMs).toLocaleDateString(undefined, {
- month: "short",
- day: "2-digit",
- year: "numeric",
- })
- : "";
- const pageCount = stub?.processedFile?.totalPages || null;
+ const slot = role === "base" ? baseSlot : compSlot;
+ const otherSlot = role === "base" ? compSlot : baseSlot;
+ const stub = slot?.stub;
+
+ if (stub) {
+ const dateMs = (stub.lastModified || stub.createdAt) ?? null;
+ const dateText = dateMs
+ ? new Date(dateMs).toLocaleDateString(undefined, {
+ month: "short",
+ day: "2-digit",
+ year: "numeric",
+ })
+ : "";
+ const pageCount = stub.processedFile?.totalPages || null;
- return (
- <Stack gap={6}>
+ return (
<Box
data-testid={`compare-slot-${role}`}
data-slot-state="filled"
@@ -559,69 +352,99 @@ const Compare = (props: BaseToolProps) => {
background: "var(--bg-surface)",
width: "100%",
minHeight: "9rem",
+ position: "relative",
}}
>
+ <ActionIcon
+ variant="subtle"
+ size="xs"
+ style={{ position: "absolute", top: "0.5rem", right: "0.5rem" }}
+ onClick={() => clearSlot(role)}
+ aria-label={t("compare.clearSlot", "Remove file")}
+ >
+ <CloseIcon fontSize="small" />
+ </ActionIcon>
<Group align="flex-start" wrap="nowrap" gap="md">
- <Box
- className="compare-tool__thumbnail"
- style={{ alignSelf: "center" }}
- >
+ <Box style={{ alignSelf: "center" }}>
<DocumentThumbnail
- file={stub ?? null}
- thumbnail={stub?.thumbnailUrl || null}
+ file={stub}
+ thumbnail={stub.thumbnailUrl || null}
/>
</Box>
- <Stack
- className="compare-tool__details"
- style={{ minWidth: 0, overflow: "hidden", flex: 1 }}
- >
- <Text fw={600} title={stub?.name}>
- {truncateCenter(stub?.name || "", 50)}
+ <Stack style={{ minWidth: 0, overflow: "hidden", flex: 1 }}>
+ <Text fw={600} title={stub.name}>
+ {truncateCenter(stub.name || "", 50)}
</Text>
{pageCount && dateText && (
- <>
- <Text
- size="xs"
- c="dimmed"
- style={{
- whiteSpace: "nowrap",
- overflow: "hidden",
- textOverflow: "ellipsis",
- }}
- >
- {pageCount} {t("compare.pages", "pages")}
- <br />
- {dateText}
- </Text>
- </>
+ <Text
+ size="xs"
+ c="dimmed"
+ style={{
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ }}
+ >
+ {pageCount} {t("compare.pages", "pages")}
+ <br />
+ {dateText}
+ </Text>
)}
</Stack>
</Group>
</Box>
- </Stack>
+ );
+ }
+
+ const isDisabled = role === "comparison" && !baseSlot;
+
+ return (
+ <div
+ data-testid={`compare-slot-${role}`}
+ data-slot-state="empty"
+ style={{ width: "100%" }}
+ >
+ <FileSelectorPicker
+ testId={`compare-slot-${role}-add`}
+ placeholder={
+ isDisabled
+ ? t(
+ "compare.edited.selectBaseFirst",
+ "Select original PDF first",
+ )
+ : t(
+ role === "base"
+ ? "compare.original.placeholder"
+ : "compare.edited.placeholder",
+ role === "base"
+ ? "Select the original PDF"
+ : "Select the edited PDF",
+ )
+ }
+ excludeIds={
+ otherSlot ? [otherSlot.stirlingFile.fileId as string] : []
+ }
+ disabled={isDisabled}
+ onSelect={(result: FileSelectorResult) => {
+ if (role === "base") setBaseSlot(result);
+ else setCompSlot(result);
+ }}
+ />
+ </div>
);
},
- [params.baseFileId, params.comparisonFileId, selectors, t, openFilesModal],
+ [baseSlot, compSlot, clearSlot, t],
);
-
- const baseStub = params.baseFileId
- ? selectors.getStirlingFileStub(params.baseFileId)
- : undefined;
- const compStub = params.comparisonFileId
- ? selectors.getStirlingFileStub(params.comparisonFileId)
- : undefined;
const canExecute = Boolean(
- params.baseFileId &&
- params.comparisonFileId &&
- params.baseFileId !== params.comparisonFileId &&
- baseStub &&
- compStub &&
+ baseSlot &&
+ compSlot &&
+ baseSlot.stirlingFile.fileId !== compSlot.stirlingFile.fileId &&
!base.operation.isLoading &&
base.endpointEnabled !== false,
);
- const hasBothSelected = Boolean(params.baseFileId && params.comparisonFileId);
- const hasAnyFiles = selectors.getFiles().length > 0;
+ const hasBothSelected = Boolean(baseSlot && compSlot);
+ const hasAnySelected = Boolean(baseSlot || compSlot);
return createToolFlow({
files: {
@@ -636,122 +459,57 @@ const Compare = (props: BaseToolProps) => {
),
isVisible: true,
content: (
- <Box
- style={{
- display: "grid",
- gridTemplateColumns: hasBothSelected ? "1fr 2.25rem" : "1fr",
- gap: "1rem",
- alignItems: "stretch",
- width: "100%",
- }}
- >
- {/* Mode toggle */}
- <Box
- style={{
- gridColumn: hasBothSelected ? "1 / span 2" : "1",
- marginTop: "0.25rem",
- }}
- >
- <SegmentedControl
- fullWidth
- size="xs"
- value={params.mode}
- onChange={(value) =>
- base.params.setParameters((prev) => ({
- ...prev,
- mode: value as "text" | "pixel",
- }))
- }
- data={[
- {
- value: "text",
- label: t("compare.mode.text", "Text Comparison"),
- },
- {
- value: "pixel",
- label: t("compare.mode.pixel", "Pixel Comparison"),
- },
- ]}
- />
- </Box>
- {/* Header row: Original PDF + Clear selected aligned to swap column */}
- <Box
- style={{
- gridColumn: hasBothSelected ? "1 / span 2" : "1",
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
- marginTop: "0.5rem",
- }}
- >
- <Text fw={700} size="sm">
- {t("compare.original.label", "Original PDF")}
- </Text>
+ <Stack gap="sm" className="compare-step-selection">
+ <div className="compare-step-selection__clear-row">
<Button
variant="subtle"
size="compact-xs"
onClick={() => setClearConfirmOpen(true)}
- disabled={!hasAnyFiles}
+ disabled={!hasAnySelected}
styles={{ root: { textDecoration: "underline" } }}
style={{
- background: !hasAnyFiles ? "transparent" : undefined,
- color: !hasAnyFiles
+ background: !hasAnySelected ? "transparent" : undefined,
+ color: !hasAnySelected
? "var(--spdf-clear-disabled-text)"
: undefined,
}}
>
{t("compare.clearSelected", "Clear selected")}
</Button>
- </Box>
- <Box
- style={{
- gridColumn: "1",
- minWidth: 0,
- }}
- >
- {renderSelectedFile("base")}
- <div style={{ height: "0.75rem" }} />
- {/* Edited PDF section header */}
- <Text
- fw={700}
- size="sm"
- style={{ marginBottom: "1rem", marginTop: "0.5rem" }}
- >
- {t("compare.edited.label", "Edited PDF")}
- </Text>
- {renderSelectedFile("comparison")}
- </Box>
- {hasBothSelected && (
- <Box
- style={{
- gridColumn: "2",
- gridRow: "2",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- alignSelf: "stretch",
- }}
- >
- <Button
- variant="subtle"
+ </div>
+
+ <Text fw={700} size="sm" style={{ margin: 0 }}>
+ {t("compare.original.label", "Original PDF")}
+ </Text>
+
+ <div className="compare-step-selection__thumbs-row">
+ <Stack gap="sm" className="compare-step-selection__thumbs-col">
+ {renderSlot("base")}
+ <Text fw={700} size="sm" style={{ margin: 0 }}>
+ {t("compare.edited.label", "Edited PDF")}
+ </Text>
+ {renderSlot("comparison")}
+ </Stack>
+
+ {hasBothSelected && (
+ <button
+ type="button"
+ className="compare-step-selection__swap"
onClick={handleSwap}
- disabled={!hasBothSelected || base.operation.isLoading}
- style={{
- width: "2.25rem",
- height: "100%",
- padding: 0,
- borderRadius: "0.5rem",
- background: "var(--bg-surface)",
- border: "1px solid var(--border-default)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
+ disabled={base.operation.isLoading}
+ aria-label={t("compare.swap.label", "Swap")}
>
- <SwapVertRoundedIcon fontSize="medium" />
- </Button>
- </Box>
- )}
+ <SwapVertRoundedIcon
+ className="compare-step-selection__swap-icon"
+ fontSize="inherit"
+ />
+ <span className="compare-step-selection__swap-label">
+ {t("compare.swap.label", "Swap")}
+ </span>
+ </button>
+ )}
+ </div>
+
<Modal
opened={swapConfirmOpen}
onClose={() => setSwapConfirmOpen(false)}
@@ -785,6 +543,7 @@ const Compare = (props: BaseToolProps) => {
</Group>
</Stack>
</Modal>
+
<Modal
opened={clearConfirmOpen}
onClose={() => setClearConfirmOpen(false)}
@@ -796,7 +555,7 @@ const Compare = (props: BaseToolProps) => {
<Text>
{t(
"compare.clear.confirmBody",
- "This will close the current comparison and take you back to Active Files.",
+ "This will clear the current file selections.",
)}
</Text>
<Group justify="flex-end" gap="sm">
@@ -813,12 +572,12 @@ const Compare = (props: BaseToolProps) => {
performClearSelected();
}}
>
- {t("compare.clear.confirm", "Clear and return")}
+ {t("compare.clear.confirm", "Clear")}
</Button>
</Group>
</Stack>
</Modal>
- </Box>
+ </Stack>
),
},
],
@@ -827,6 +586,9 @@ const Compare = (props: BaseToolProps) => {
loadingText: t("compare.loading", "Comparing..."),
onClick: handleExecuteCompare,
disabled: !canExecute,
+ // Explicitly null so the noFiles gate is bypassed — Compare manages its own slot state
+ disabledReason:
+ base.endpointEnabled === false ? "endpointUnavailable" : null,
testId: "compare-execute",
disableScopeHints: true,
},
diff --git a/frontend/src/core/tools/Merge.tsx b/frontend/src/core/tools/Merge.tsx
index de1c423a04..9138dfa4f0 100644
--- a/frontend/src/core/tools/Merge.tsx
+++ b/frontend/src/core/tools/Merge.tsx
@@ -9,11 +9,7 @@ import { useMergeOperation } from "@app/hooks/tools/merge/useMergeOperation";
import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
import { BaseToolProps, ToolComponent } from "@app/types/tool";
import { useMergeTips } from "@app/components/tooltips/useMergeTips";
-import {
- useFileManagement,
- useSelectedFiles,
- useAllFiles,
-} from "@app/contexts/FileContext";
+import { useFileManagement, useAllFiles } from "@app/contexts/FileContext";
import {
useNavigationState,
useNavigationActions,
@@ -24,8 +20,7 @@ const Merge = (props: BaseToolProps) => {
const mergeTips = useMergeTips();
// File selection hooks for custom sorting
- const { fileIds } = useAllFiles();
- const { selectedFileStubs } = useSelectedFiles();
+ const { fileIds, fileStubs } = useAllFiles();
const { reorderFiles } = useFileManagement();
const base = useBaseTool(
@@ -114,7 +109,7 @@ const Merge = (props: BaseToolProps) => {
// Custom file sorting logic for merge tool
const sortFiles = useCallback(
(sortType: "filename" | "dateModified", ascending: boolean = true) => {
- const sortedStubs = [...selectedFileStubs].sort((stubA, stubB) => {
+ const sortedStubs = [...fileStubs].sort((stubA, stubB) => {
let comparison = 0;
switch (sortType) {
case "filename":
@@ -131,7 +126,7 @@ const Merge = (props: BaseToolProps) => {
const deselectedIds = fileIds.filter((id) => !selectedIds.includes(id));
reorderFiles([...selectedIds, ...deselectedIds]);
},
- [selectedFileStubs, fileIds, reorderFiles, naturalCompare],
+ [fileStubs, fileIds, reorderFiles, naturalCompare],
);
return createToolFlow({
diff --git a/frontend/src/core/types/sidebar.ts b/frontend/src/core/types/sidebar.ts
index 98a7fae9a3..0db86088b9 100644
--- a/frontend/src/core/types/sidebar.ts
+++ b/frontend/src/core/types/sidebar.ts
@@ -7,7 +7,6 @@ export interface SidebarState {
export interface SidebarRefs {
quickAccessRef: React.RefObject<HTMLDivElement | null>;
toolPanelRef: React.RefObject<HTMLDivElement | null>;
- rightRailRef: React.RefObject<HTMLDivElement | null>;
}
export interface SidebarInfo {
diff --git a/frontend/src/core/types/rightRail.ts b/frontend/src/core/types/workbenchBar.ts
similarity index 74%
rename from frontend/src/core/types/rightRail.ts
rename to frontend/src/core/types/workbenchBar.ts
index 8d36a7a8b5..523aaab681 100644
--- a/frontend/src/core/types/rightRail.ts
+++ b/frontend/src/core/types/workbenchBar.ts
@@ -1,19 +1,19 @@
import React from "react";
-export type RightRailSection = "top" | "middle" | "bottom";
+export type WorkbenchBarSection = "top" | "middle" | "bottom" | "tool-panel";
-export type RightRailAction = () => void;
+export type WorkbenchBarAction = () => void;
-export interface RightRailRenderContext {
+export interface WorkbenchBarRenderContext {
id: string;
disabled: boolean;
allButtonsDisabled: boolean;
- action?: RightRailAction;
+ action?: WorkbenchBarAction;
triggerAction: () => void;
active: boolean;
}
-export interface RightRailButtonConfig {
+export interface WorkbenchBarButtonConfig {
/** Unique id for the button, also used to bind action callbacks */
id: string;
/** Icon element to render when using default renderer */
@@ -25,7 +25,7 @@ export interface RightRailButtonConfig {
/** Optional i18n key carried by config */
templateKey?: string;
/** Visual grouping lane */
- section?: RightRailSection;
+ section?: WorkbenchBarSection;
/** Sorting within a section (lower first); ties broken by id */
order?: number;
/** Initial disabled state */
@@ -33,7 +33,7 @@ export interface RightRailButtonConfig {
/** Initial visibility */
visible?: boolean;
/** Optional custom renderer for advanced layouts */
- render?: (ctx: RightRailRenderContext) => React.ReactNode;
+ render?: (ctx: WorkbenchBarRenderContext) => React.ReactNode;
/** Optional className applied to wrapper when using default renderer */
className?: string;
/** Optional active state to highlight the control */
diff --git a/frontend/src/core/utils/fileUtils.ts b/frontend/src/core/utils/fileUtils.ts
index 57a09d7bb8..6a256a9073 100644
--- a/frontend/src/core/utils/fileUtils.ts
+++ b/frontend/src/core/utils/fileUtils.ts
@@ -107,7 +107,7 @@ export type NonPdfFileType =
| "html"
| "unknown";
-const IMAGE_EXTENSIONS = new Set([
+export const IMAGE_EXTENSIONS = new Set([
"png",
"jpg",
"jpeg",
@@ -124,6 +124,17 @@ const TEXT_EXTENSIONS = new Set(["txt"]);
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown"]);
const HTML_EXTENSIONS = new Set(["html", "htm"]);
+/** All file extensions that the built-in viewer can render. */
+export const VIEWER_SUPPORTED_EXTENSIONS: string[] = [
+ "pdf",
+ ...IMAGE_EXTENSIONS,
+ ...CSV_EXTENSIONS,
+ ...JSON_EXTENSIONS,
+ ...TEXT_EXTENSIONS,
+ ...MARKDOWN_EXTENSIONS,
+ ...HTML_EXTENSIONS,
+];
+
/**
* Detects the non-PDF file type category for viewer routing.
* Returns 'unknown' for PDFs or unrecognized formats.
diff --git a/frontend/src/core/utils/homePageNavigation.test.ts b/frontend/src/core/utils/homePageNavigation.test.ts
index 96ec01d6a7..862e48c3ae 100644
--- a/frontend/src/core/utils/homePageNavigation.test.ts
+++ b/frontend/src/core/utils/homePageNavigation.test.ts
@@ -26,7 +26,7 @@ describe("getStartupNavigationAction", () => {
});
});
- it("does not force navigation for pdfTextEditor", () => {
+ it("does not force navigation for pdfTextEditor or multiTool", () => {
expect(
getStartupNavigationAction(
0,
@@ -43,6 +43,22 @@ describe("getStartupNavigationAction", () => {
"viewer" as WorkbenchType,
),
).toBeNull();
+ expect(
+ getStartupNavigationAction(
+ 0,
+ 1,
+ "multiTool",
+ "pageEditor" as WorkbenchType,
+ ),
+ ).toBeNull();
+ expect(
+ getStartupNavigationAction(
+ 0,
+ 3,
+ "multiTool",
+ "pageEditor" as WorkbenchType,
+ ),
+ ).toBeNull();
});
it("does not navigate when file count decreases", () => {
diff --git a/frontend/src/core/utils/homePageNavigation.ts b/frontend/src/core/utils/homePageNavigation.ts
index 9986e3609f..722e025bdc 100644
--- a/frontend/src/core/utils/homePageNavigation.ts
+++ b/frontend/src/core/utils/homePageNavigation.ts
@@ -13,8 +13,9 @@ export function getStartupNavigationAction(
selectedToolKey: string | null,
currentWorkbench: WorkbenchType,
): StartupNavigationAction | null {
- // pdfTextEditor handles its own empty state
- if (selectedToolKey === "pdfTextEditor") {
+ // These tools manage their own state when files are added and should not be
+ // auto-navigated away from their workbench.
+ if (selectedToolKey === "pdfTextEditor" || selectedToolKey === "multiTool") {
return null;
}
diff --git a/frontend/src/core/utils/pdfiumPageRender.ts b/frontend/src/core/utils/pdfiumPageRender.ts
index 0577245c98..1235653405 100644
--- a/frontend/src/core/utils/pdfiumPageRender.ts
+++ b/frontend/src/core/utils/pdfiumPageRender.ts
@@ -39,21 +39,25 @@ export async function renderPdfiumPageDataUrl(
if (!pagePtr) return null;
try {
+ // Effective dims already account for /Rotate; PDFium auto-applies it during render.
const rawW = m.FPDF_GetPageWidthF(pagePtr);
const rawH = m.FPDF_GetPageHeightF(pagePtr);
- // FPDFPage_GetRotation returns 0..3 for 0°/90°/180°/270° CW.
+ // Returns 0–3 for 0°/90°/180°/270° CW.
const pageRotQuarters = (m as any).FPDFPage_GetRotation(pagePtr) | 0;
const isQuarterTurn = pageRotQuarters === 1 || pageRotQuarters === 3;
- const outW = applyRotation && isQuarterTurn ? rawH : rawW;
- const outH = applyRotation && isQuarterTurn ? rawW : rawH;
+
+ // false: swap dims back to raw + counter-rotate to cancel PDFium's auto /Rotate.
+ const outW = applyRotation ? rawW : isQuarterTurn ? rawH : rawW;
+ const outH = applyRotation ? rawH : isQuarterTurn ? rawW : rawH;
+ const renderRotate = applyRotation ? 0 : (4 - pageRotQuarters) % 4;
+
const w = Math.max(1, Math.round(outW * scale));
const h = Math.max(1, Math.round(outH * scale));
const bitmapPtr = m.FPDFBitmap_Create(w, h, 1);
try {
- // White background — PDF content doesn't encode paper colour, so
- // unpainted regions would otherwise be transparent.
+ // White background; PDF content doesn't encode paper colour.
m.FPDFBitmap_FillRect(bitmapPtr, 0, 0, w, h, 0xffffffff);
m.FPDF_RenderPageBitmap(
bitmapPtr,
@@ -62,7 +66,7 @@ export async function renderPdfiumPageDataUrl(
0,
w,
h,
- applyRotation ? pageRotQuarters : 0,
+ renderRotate,
PDFIUM_RENDER_FLAGS,
);
@@ -71,19 +75,11 @@ export async function renderPdfiumPageDataUrl(
const heap = new Uint8Array((m.pdfium.wasmExports as any).memory.buffer);
const pixels = new Uint8ClampedArray(w * h * 4);
- // BGRA → RGBA. Direct HEAPU8 indexing is ~100× faster than
- // per-pixel m.pdfium.getValue() calls for large bitmaps.
+ // @embedpdf/pdfium WASM stores pixels in RGBA byte order (not BGRA),
+ // so copy rows directly without channel swapping.
for (let y = 0; y < h; y++) {
const srcRow = bufferPtr + y * stride;
- const dstRow = y * w * 4;
- for (let x = 0; x < w; x++) {
- const so = srcRow + x * 4;
- const dst = dstRow + x * 4;
- pixels[dst] = heap[so + 2];
- pixels[dst + 1] = heap[so + 1];
- pixels[dst + 2] = heap[so];
- pixels[dst + 3] = heap[so + 3];
- }
+ pixels.set(heap.subarray(srcRow, srcRow + w * 4), y * w * 4);
}
const canvas = document.createElement("canvas");
diff --git a/frontend/src/core/utils/thumbnailUtils.ts b/frontend/src/core/utils/thumbnailUtils.ts
index 36ec904521..a4efafbff5 100644
--- a/frontend/src/core/utils/thumbnailUtils.ts
+++ b/frontend/src/core/utils/thumbnailUtils.ts
@@ -16,16 +16,6 @@ export interface ThumbnailWithMetadata {
isEncrypted?: boolean;
}
-interface ColorScheme {
- bgTop: string;
- bgBottom: string;
- border: string;
- icon: string;
- badge: string;
- textPrimary: string;
- textSecondary: string;
-}
-
/**
* Calculate thumbnail scale based on file size (modern 2024 scaling)
*/
@@ -38,495 +28,6 @@ export function calculateScaleFromFileSize(fileSize: number): number {
return 0.3; // Still usable quality, not tiny
}
-/**
- * Generate encrypted PDF thumbnail with lock icon
- */
-function generateEncryptedPDFThumbnail(file: File): string {
- const canvas = document.createElement("canvas");
- canvas.width = 120;
- canvas.height = 150;
- const ctx = canvas.getContext("2d")!;
-
- // Use PDF color scheme but with encrypted styling
- const colorScheme = getFileTypeColorScheme("PDF");
-
- // Create gradient background
- const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
- gradient.addColorStop(0, colorScheme.bgTop);
- gradient.addColorStop(1, colorScheme.bgBottom);
-
- // Rounded rectangle background
- drawRoundedRect(ctx, 8, 8, canvas.width - 16, canvas.height - 16, 8);
- ctx.fillStyle = gradient;
- ctx.fill();
-
- // Border with dashed pattern for encrypted indicator
- ctx.strokeStyle = colorScheme.border;
- ctx.lineWidth = 2;
- ctx.setLineDash([4, 4]);
- ctx.stroke();
- ctx.setLineDash([]); // Reset dash pattern
-
- // Large lock icon as main element
- drawLargeLockIcon(ctx, canvas.width / 2, canvas.height / 2 - 10, colorScheme);
-
- // "PDF" text under the lock
- ctx.font =
- 'bold 14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
- ctx.fillStyle = colorScheme.icon;
- ctx.textAlign = "center";
- ctx.fillText("PDF", canvas.width / 2, canvas.height / 2 + 35);
-
- // File size with subtle styling
- const sizeText = formatFileSize(file.size);
- ctx.font =
- '11px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
- ctx.fillStyle = colorScheme.textSecondary;
- ctx.textAlign = "center";
- ctx.fillText(sizeText, canvas.width / 2, canvas.height - 15);
-
- return canvas.toDataURL();
-}
-
-/**
- * Generate modern placeholder thumbnail with file extension
- */
-function generatePlaceholderThumbnail(file: File): string {
- const canvas = document.createElement("canvas");
- canvas.width = 120;
- canvas.height = 150;
- const ctx = canvas.getContext("2d")!;
-
- // Get file extension for color theming
- const extension = file.name.split(".").pop()?.toUpperCase() || "FILE";
- const colorScheme = getFileTypeColorScheme(extension);
-
- // Create gradient background
- const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
- gradient.addColorStop(0, colorScheme.bgTop);
- gradient.addColorStop(1, colorScheme.bgBottom);
-
- // Rounded rectangle background
- drawRoundedRect(ctx, 8, 8, canvas.width - 16, canvas.height - 16, 8);
- ctx.fillStyle = gradient;
- ctx.fill();
-
- // Subtle shadow/border
- ctx.strokeStyle = colorScheme.border;
- ctx.lineWidth = 1.5;
- ctx.stroke();
-
- // Modern document icon
- drawModernDocumentIcon(ctx, canvas.width / 2, 45, colorScheme.icon);
-
- // Extension badge
- drawExtensionBadge(
- ctx,
- canvas.width / 2,
- canvas.height / 2 + 15,
- extension,
- colorScheme,
- );
-
- // File size with subtle styling
- const sizeText = formatFileSize(file.size);
- ctx.font =
- '11px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
- ctx.fillStyle = colorScheme.textSecondary;
- ctx.textAlign = "center";
- ctx.fillText(sizeText, canvas.width / 2, canvas.height - 15);
-
- return canvas.toDataURL();
-}
-
-/**
- * Get color scheme based on file extension
- */
-function getFileTypeColorScheme(extension: string): ColorScheme {
- const schemes: Record<string, ColorScheme> = {
- // Documents
- PDF: {
- bgTop: "#FF6B6B20",
- bgBottom: "#FF6B6B10",
- border: "#FF6B6B40",
- icon: "#FF6B6B",
- badge: "#FF6B6B",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- DOC: {
- bgTop: "#4ECDC420",
- bgBottom: "#4ECDC410",
- border: "#4ECDC440",
- icon: "#4ECDC4",
- badge: "#4ECDC4",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- DOCX: {
- bgTop: "#4ECDC420",
- bgBottom: "#4ECDC410",
- border: "#4ECDC440",
- icon: "#4ECDC4",
- badge: "#4ECDC4",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- ODT: {
- bgTop: "#4ECDC420",
- bgBottom: "#4ECDC410",
- border: "#4ECDC440",
- icon: "#4ECDC4",
- badge: "#4ECDC4",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- TXT: {
- bgTop: "#95A5A620",
- bgBottom: "#95A5A610",
- border: "#95A5A640",
- icon: "#95A5A6",
- badge: "#95A5A6",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- RTF: {
- bgTop: "#95A5A620",
- bgBottom: "#95A5A610",
- border: "#95A5A640",
- icon: "#95A5A6",
- badge: "#95A5A6",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Spreadsheets
- XLS: {
- bgTop: "#2ECC7120",
- bgBottom: "#2ECC7110",
- border: "#2ECC7140",
- icon: "#2ECC71",
- badge: "#2ECC71",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- XLSX: {
- bgTop: "#2ECC7120",
- bgBottom: "#2ECC7110",
- border: "#2ECC7140",
- icon: "#2ECC71",
- badge: "#2ECC71",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- ODS: {
- bgTop: "#2ECC7120",
- bgBottom: "#2ECC7110",
- border: "#2ECC7140",
- icon: "#2ECC71",
- badge: "#2ECC71",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- CSV: {
- bgTop: "#2ECC7120",
- bgBottom: "#2ECC7110",
- border: "#2ECC7140",
- icon: "#2ECC71",
- badge: "#2ECC71",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Presentations
- PPT: {
- bgTop: "#E67E2220",
- bgBottom: "#E67E2210",
- border: "#E67E2240",
- icon: "#E67E22",
- badge: "#E67E22",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- PPTX: {
- bgTop: "#E67E2220",
- bgBottom: "#E67E2210",
- border: "#E67E2240",
- icon: "#E67E22",
- badge: "#E67E22",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- ODP: {
- bgTop: "#E67E2220",
- bgBottom: "#E67E2210",
- border: "#E67E2240",
- icon: "#E67E22",
- badge: "#E67E22",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Images
- JPG: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- JPEG: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- PNG: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- GIF: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- BMP: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- TIFF: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- WEBP: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- SVG: {
- bgTop: "#FF9F4320",
- bgBottom: "#FF9F4310",
- border: "#FF9F4340",
- icon: "#FF9F43",
- badge: "#FF9F43",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Web
- HTML: {
- bgTop: "#FD79A820",
- bgBottom: "#FD79A810",
- border: "#FD79A840",
- icon: "#FD79A8",
- badge: "#FD79A8",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- XML: {
- bgTop: "#FD79A820",
- bgBottom: "#FD79A810",
- border: "#FD79A840",
- icon: "#FD79A8",
- badge: "#FD79A8",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Text/Markup
- MD: {
- bgTop: "#6C5CE720",
- bgBottom: "#6C5CE710",
- border: "#6C5CE740",
- icon: "#6C5CE7",
- badge: "#6C5CE7",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Email
- EML: {
- bgTop: "#A29BFE20",
- bgBottom: "#A29BFE10",
- border: "#A29BFE40",
- icon: "#A29BFE",
- badge: "#A29BFE",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Archives
- ZIP: {
- bgTop: "#9B59B620",
- bgBottom: "#9B59B610",
- border: "#9B59B640",
- icon: "#9B59B6",
- badge: "#9B59B6",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- RAR: {
- bgTop: "#9B59B620",
- bgBottom: "#9B59B610",
- border: "#9B59B640",
- icon: "#9B59B6",
- badge: "#9B59B6",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- "7Z": {
- bgTop: "#9B59B620",
- bgBottom: "#9B59B610",
- border: "#9B59B640",
- icon: "#9B59B6",
- badge: "#9B59B6",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
-
- // Default
- DEFAULT: {
- bgTop: "#74B9FF20",
- bgBottom: "#74B9FF10",
- border: "#74B9FF40",
- icon: "#74B9FF",
- badge: "#74B9FF",
- textPrimary: "#FFFFFF",
- textSecondary: "#666666",
- },
- };
-
- return schemes[extension] || schemes["DEFAULT"];
-}
-
-/**
- * Draw rounded rectangle
- */
-function drawRoundedRect(
- ctx: CanvasRenderingContext2D,
- x: number,
- y: number,
- width: number,
- height: number,
- radius: number,
-) {
- ctx.beginPath();
- ctx.moveTo(x + radius, y);
- ctx.lineTo(x + width - radius, y);
- ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
- ctx.lineTo(x + width, y + height - radius);
- ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
- ctx.lineTo(x + radius, y + height);
- ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
- ctx.lineTo(x, y + radius);
- ctx.quadraticCurveTo(x, y, x + radius, y);
- ctx.closePath();
-}
-
-/**
- * Draw modern document icon
- */
-function drawModernDocumentIcon(
- ctx: CanvasRenderingContext2D,
- centerX: number,
- centerY: number,
- color: string,
-) {
- const size = 24;
- ctx.fillStyle = color;
- ctx.strokeStyle = color;
- ctx.lineWidth = 2;
-
- // Document body
- drawRoundedRect(
- ctx,
- centerX - size / 2,
- centerY - size / 2,
- size,
- size * 1.2,
- 3,
- );
- ctx.fill();
-
- // Folded corner
- ctx.beginPath();
- ctx.moveTo(centerX + size / 2 - 6, centerY - size / 2);
- ctx.lineTo(centerX + size / 2, centerY - size / 2 + 6);
- ctx.lineTo(centerX + size / 2 - 6, centerY - size / 2 + 6);
- ctx.closePath();
- ctx.fillStyle = "#FFFFFF40";
- ctx.fill();
-}
-
-/**
- * Draw large lock icon for encrypted PDFs
- */
-function drawLargeLockIcon(
- ctx: CanvasRenderingContext2D,
- centerX: number,
- centerY: number,
- colorScheme: ColorScheme,
-) {
- const size = 48;
- ctx.fillStyle = colorScheme.icon;
- ctx.strokeStyle = colorScheme.icon;
- ctx.lineWidth = 3;
-
- // Lock body (rectangle)
- const bodyWidth = size;
- const bodyHeight = size * 0.75;
- const bodyX = centerX - bodyWidth / 2;
- const bodyY = centerY - bodyHeight / 4;
-
- drawRoundedRect(ctx, bodyX, bodyY, bodyWidth, bodyHeight, 4);
- ctx.fill();
-
- // Lock shackle (semicircle)
- const shackleRadius = size * 0.32;
- const shackleY = centerY - size * 0.25;
-
- ctx.beginPath();
- ctx.arc(centerX, shackleY, shackleRadius, Math.PI, 2 * Math.PI);
- ctx.stroke();
-
- // Keyhole
- const keyholeX = centerX;
- const keyholeY = bodyY + bodyHeight * 0.4;
- ctx.fillStyle = colorScheme.textPrimary;
- ctx.beginPath();
- ctx.arc(keyholeX, keyholeY, 4, 0, 2 * Math.PI);
- ctx.fill();
- ctx.fillRect(keyholeX - 2, keyholeY, 4, 8);
-}
-
/** PDFium error code 4 = password required (encrypted PDF). */
const PDFIUM_ERR_PASSWORD = 4;
@@ -611,53 +112,8 @@ async function renderPdfThumbnailPdfium(
}
}
-/**
- * Draw extension badge
- */
-function drawExtensionBadge(
- ctx: CanvasRenderingContext2D,
- centerX: number,
- centerY: number,
- extension: string,
- colorScheme: ColorScheme,
-) {
- const badgeWidth = Math.max(extension.length * 8 + 16, 40);
- const badgeHeight = 22;
-
- // Badge background
- drawRoundedRect(
- ctx,
- centerX - badgeWidth / 2,
- centerY - badgeHeight / 2,
- badgeWidth,
- badgeHeight,
- 11,
- );
- ctx.fillStyle = colorScheme.badge;
- ctx.fill();
-
- // Badge text
- ctx.font =
- 'bold 11px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
- ctx.fillStyle = colorScheme.textPrimary;
- ctx.textAlign = "center";
- ctx.fillText(extension, centerX, centerY + 4);
-}
-
-/**
- * Format file size for display
- */
-function formatFileSize(bytes: number): string {
- if (bytes === 0) return "0 B";
- const k = 1024;
- const sizes = ["B", "KB", "MB", "GB"];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
-}
-
async function generatePDFThumbnail(
arrayBuffer: ArrayBuffer,
- file: File,
scale: number,
): Promise<string> {
const result = await renderPdfThumbnailPdfium(
@@ -667,7 +123,7 @@ async function generatePDFThumbnail(
false,
);
if (result.isEncrypted) {
- return generateEncryptedPDFThumbnail(file);
+ return "";
}
return result.thumbnail;
}
@@ -676,9 +132,9 @@ async function generatePDFThumbnail(
* Generate thumbnail for any file type - always returns a thumbnail (placeholder if needed)
*/
export async function generateThumbnailForFile(file: File): Promise<string> {
- // Skip very large files
+ // Very large PDFs skip thumbnail generation — SVG icon shown in UI instead
if (file.size >= 100 * 1024 * 1024) {
- return generatePlaceholderThumbnail(file);
+ return "";
}
// Handle image files - convert to data URL for persistence
@@ -701,26 +157,23 @@ export async function generateThumbnailForFile(file: File): Promise<string> {
const arrayBuffer = await chunk.arrayBuffer();
try {
- return await generatePDFThumbnail(arrayBuffer, file, scale);
+ return await generatePDFThumbnail(arrayBuffer, scale);
} catch {
// PDFium needs the xref table at the end of the file, so the 2MB
// chunk can fail to open for PDFs larger than that. Retry with the
- // full buffer before falling back to a placeholder.
+ // full buffer before falling back to an empty thumbnail.
try {
const fullArrayBuffer = await file.arrayBuffer();
- return await generatePDFThumbnail(fullArrayBuffer, file, scale);
+ return await generatePDFThumbnail(fullArrayBuffer, scale);
} catch (error) {
- console.warn(
- `PDF processing failed for ${file.name} - using placeholder:`,
- error,
- );
- return generatePlaceholderThumbnail(file);
+ console.warn(`PDF processing failed for ${file.name}:`, error);
+ return "";
}
}
}
- // All other files get placeholder
- return generatePlaceholderThumbnail(file);
+ // Non-PDF, non-image files use scalable SVG icons in the UI — no raster thumbnail needed
+ return "";
}
/**
@@ -752,7 +205,7 @@ export async function generateThumbnailWithMetadata(
if (result.isEncrypted) {
return {
- thumbnail: generateEncryptedPDFThumbnail(file),
+ thumbnail: "",
pageCount: 1,
isEncrypted: true,
};
@@ -765,7 +218,6 @@ export async function generateThumbnailWithMetadata(
pageDimensions: result.pageDimensions,
};
} catch {
- const thumbnail = generatePlaceholderThumbnail(file);
- return { thumbnail, pageCount: 1 };
+ return { thumbnail: "", pageCount: 1 };
}
}
diff --git a/frontend/src/desktop/components/fileEditor/FileEditorFileName.test.tsx b/frontend/src/desktop/components/fileEditor/FileEditorFileName.test.tsx
deleted file mode 100644
index 10bd62488f..0000000000
--- a/frontend/src/desktop/components/fileEditor/FileEditorFileName.test.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import React from "react";
-import { describe, expect, test } from "vitest";
-import { render, screen } from "@testing-library/react";
-import { MantineProvider } from "@mantine/core";
-import FileEditorFileName from "@app/components/fileEditor/FileEditorFileName";
-import type { StirlingFileStub } from "@app/types/fileContext";
-import type { FileId } from "@app/types/file";
-
-const buildFileStub = (
- overrides: Partial<StirlingFileStub> = {},
-): StirlingFileStub => ({
- id: "file-1" as FileId,
- name: "report.pdf",
- type: "application/pdf",
- size: 1024,
- lastModified: 0,
- isLeaf: true,
- originalFileId: "file-1",
- versionNumber: 1,
- ...overrides,
-});
-
-const renderName = (file: StirlingFileStub) =>
- render(
- <MantineProvider>
- <FileEditorFileName file={file} />
- </MantineProvider>,
- );
-
-describe("FileEditorFileName (desktop)", () => {
- test("renders red 'not saved' indicator when file has no local path", () => {
- renderName(buildFileStub());
-
- const indicator = screen.getByLabelText("fileNotSavedToDisk");
- expect(indicator).toBeInTheDocument();
- expect(indicator).toHaveStyle({
- backgroundColor: "var(--mantine-color-red-6)",
- });
- expect(screen.queryByLabelText("unsavedChanges")).toBeNull();
- expect(screen.queryByLabelText("fileSavedToDisk")).toBeNull();
- });
-
- test("renders yellow 'unsaved changes' indicator when file is dirty", () => {
- renderName(
- buildFileStub({ localFilePath: "/tmp/report.pdf", isDirty: true }),
- );
-
- const indicator = screen.getByLabelText("unsavedChanges");
- expect(indicator).toBeInTheDocument();
- expect(indicator).toHaveStyle({
- backgroundColor: "var(--mantine-color-yellow-6)",
- });
- expect(screen.queryByLabelText("fileNotSavedToDisk")).toBeNull();
- expect(screen.queryByLabelText("fileSavedToDisk")).toBeNull();
- });
-
- test("renders green 'saved' indicator when file is persisted and clean", () => {
- renderName(
- buildFileStub({ localFilePath: "/tmp/report.pdf", isDirty: false }),
- );
-
- const indicator = screen.getByLabelText("fileSavedToDisk");
- expect(indicator).toBeInTheDocument();
- expect(indicator).toHaveStyle({
- backgroundColor: "var(--mantine-color-green-6)",
- });
- expect(screen.queryByLabelText("fileNotSavedToDisk")).toBeNull();
- expect(screen.queryByLabelText("unsavedChanges")).toBeNull();
- });
-
- test("renders the filename alongside the indicator", () => {
- renderName(buildFileStub({ name: "invoice.pdf" }));
- expect(screen.getByText("invoice.pdf")).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/desktop/components/fileEditor/FileEditorFileName.tsx b/frontend/src/desktop/components/fileEditor/FileEditorFileName.tsx
deleted file mode 100644
index 46349fd31a..0000000000
--- a/frontend/src/desktop/components/fileEditor/FileEditorFileName.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import React from "react";
-import { Tooltip } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { StirlingFileStub } from "@app/types/fileContext";
-import { PrivateContent } from "@app/components/shared/PrivateContent";
-import { truncateCenter } from "@app/utils/textUtils";
-
-interface FileEditorFileNameProps {
- file: StirlingFileStub;
- maxLength?: number;
-}
-
-const FileEditorFileName = ({
- file,
- maxLength = 40,
-}: FileEditorFileNameProps) => {
- const { t } = useTranslation();
-
- return (
- <>
- <PrivateContent>{truncateCenter(file.name, maxLength)}</PrivateContent>
- {!file.localFilePath && (
- <Tooltip label={t("fileNotSavedToDisk", "Not saved to disk")}>
- <span
- style={{
- display: "inline-block",
- width: "6px",
- height: "6px",
- borderRadius: "50%",
- backgroundColor: "var(--mantine-color-red-6)",
- flexShrink: 0,
- }}
- aria-label={t("fileNotSavedToDisk", "Not saved to disk")}
- />
- </Tooltip>
- )}
- {file.localFilePath && file.isDirty && (
- <Tooltip label={t("unsavedChanges", "Unsaved changes")}>
- <span
- style={{
- display: "inline-block",
- width: "6px",
- height: "6px",
- borderRadius: "50%",
- backgroundColor: "var(--mantine-color-yellow-6)",
- flexShrink: 0,
- }}
- aria-label={t("unsavedChanges", "Unsaved changes")}
- />
- </Tooltip>
- )}
- {file.localFilePath && !file.isDirty && (
- <Tooltip label={t("fileSavedToDisk", "File saved to disk")}>
- <span
- style={{
- display: "inline-block",
- width: "6px",
- height: "6px",
- borderRadius: "50%",
- backgroundColor: "var(--mantine-color-green-6)",
- flexShrink: 0,
- }}
- aria-label={t("fileSavedToDisk", "File saved to disk")}
- />
- </Tooltip>
- )}
- </>
- );
-};
-
-export default FileEditorFileName;
diff --git a/frontend/src/desktop/components/fileEditor/FileEditorStatusDot.tsx b/frontend/src/desktop/components/fileEditor/FileEditorStatusDot.tsx
new file mode 100644
index 0000000000..e27b50dadc
--- /dev/null
+++ b/frontend/src/desktop/components/fileEditor/FileEditorStatusDot.tsx
@@ -0,0 +1,36 @@
+import { Tooltip } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { StirlingFileStub } from "@app/types/fileContext";
+import styles from "@app/components/fileEditor/FileEditorThumbnail.module.css";
+
+interface FileEditorStatusDotProps {
+ file: StirlingFileStub;
+}
+
+export function FileEditorStatusDot({ file }: FileEditorStatusDotProps) {
+ const { t } = useTranslation();
+
+ const label = !file.localFilePath
+ ? t("fileNotSavedToDisk", "Not saved to disk")
+ : file.isDirty
+ ? t("unsavedChanges", "Unsaved changes")
+ : t("fileSavedToDisk", "Saved to disk");
+
+ const color = !file.localFilePath
+ ? "var(--mantine-color-red-6)"
+ : file.isDirty
+ ? "var(--mantine-color-yellow-6)"
+ : "var(--mantine-color-green-6)";
+
+ return (
+ <div className={styles.thumbBadgesRight}>
+ <Tooltip label={label}>
+ <span
+ className={styles.statusDot}
+ style={{ backgroundColor: color }}
+ aria-label={label}
+ />
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/frontend/src/desktop/components/rightRail/RightRailFooterExtensions.tsx b/frontend/src/desktop/components/rightRail/RightRailFooterExtensions.tsx
deleted file mode 100644
index 96c4e106db..0000000000
--- a/frontend/src/desktop/components/rightRail/RightRailFooterExtensions.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { useState, useEffect, useMemo } from "react";
-import { Box, Tooltip, rem } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import {
- connectionModeService,
- type ConnectionMode,
-} from "@app/services/connectionModeService";
-import {
- selfHostedServerMonitor,
- type SelfHostedServerState,
-} from "@app/services/selfHostedServerMonitor";
-import { useBackendHealth } from "@app/hooks/useBackendHealth";
-import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";
-
-interface RightRailFooterExtensionsProps {
- className?: string;
-}
-
-function ConnectionStatusDot() {
- const { t } = useTranslation();
- const [connectionMode, setConnectionMode] = useState<ConnectionMode | null>(
- null,
- );
- const [selfHostedState, setSelfHostedState] = useState<SelfHostedServerState>(
- () => selfHostedServerMonitor.getSnapshot(),
- );
- const { isOnline, checkHealth } = useBackendHealth();
-
- useEffect(() => {
- void connectionModeService.getCurrentMode().then(setConnectionMode);
- const unsubscribe = connectionModeService.subscribeToModeChanges(
- (config) => {
- setConnectionMode(config.mode);
- },
- );
- return unsubscribe;
- }, []);
-
- useEffect(() => {
- return selfHostedServerMonitor.subscribe(setSelfHostedState);
- }, []);
-
- const { label, color } = useMemo(() => {
- if (connectionMode === "saas") {
- return {
- label: t("connectionMode.status.saas", "Connected to Stirling Cloud"),
- color: "#3b82f6",
- };
- }
- if (connectionMode === "selfhosted") {
- const serverOnline = selfHostedState.isOnline;
- const serverChecking = selfHostedState.status === "checking";
- const backendLabel = serverChecking
- ? t(
- "connectionMode.status.selfhostedChecking",
- "Connected to self-hosted server (checking...)",
- )
- : serverOnline
- ? t(
- "connectionMode.status.selfhostedOnline",
- "Connected to self-hosted server",
- )
- : t(
- "connectionMode.status.selfhostedOffline",
- "Self-hosted server unreachable",
- );
- return {
- label: backendLabel,
- color: serverChecking
- ? "#fcc419"
- : serverOnline
- ? "#37b24d"
- : "#e03131",
- };
- }
- // local
- return {
- label: isOnline
- ? t("connectionMode.status.localOnline", "Offline mode running")
- : t("connectionMode.status.localOffline", "Offline mode running"),
- color: "#868e96",
- };
- }, [connectionMode, selfHostedState, isOnline, t]);
-
- return (
- <Tooltip label={label} position="left" offset={12} withArrow withinPortal>
- <Box
- component="span"
- role="status"
- aria-label={label}
- tabIndex={0}
- onClick={() => {
- if (connectionMode === "local") {
- window.dispatchEvent(new CustomEvent(OPEN_SIGN_IN_EVENT));
- } else {
- void checkHealth();
- }
- }}
- style={{
- width: rem(10),
- height: rem(10),
- borderRadius: "50%",
- backgroundColor: color,
- boxShadow: "var(--status-dot-ring)",
- display: "inline-block",
- cursor: "pointer",
- outline: "none",
- }}
- />
- </Tooltip>
- );
-}
-
-export function RightRailFooterExtensions({
- className,
-}: RightRailFooterExtensionsProps) {
- return (
- <Box
- className={className}
- style={{
- width: "100%",
- display: "flex",
- justifyContent: "center",
- alignItems: "center",
- paddingBottom: rem(12),
- }}
- >
- <ConnectionStatusDot />
- </Box>
- );
-}
diff --git a/frontend/src/desktop/components/shared/config/configNavSections.tsx b/frontend/src/desktop/components/shared/config/configNavSections.tsx
index d95a356099..e0c4da6e9e 100644
--- a/frontend/src/desktop/components/shared/config/configNavSections.tsx
+++ b/frontend/src/desktop/components/shared/config/configNavSections.tsx
@@ -23,6 +23,7 @@ export const useConfigNavSections = (
isAdmin: boolean = false,
runningEE: boolean = false,
loginEnabled: boolean = false,
+ onRequestClose: () => void = () => {},
): ConfigNavSection[] => {
const { t } = useTranslation();
@@ -52,6 +53,7 @@ export const useConfigNavSections = (
isAdmin,
runningEE,
loginEnabled,
+ onRequestClose,
);
const connectionModeSection: ConfigNavSection = {
diff --git a/frontend/src/desktop/hooks/useFileActionIcons.ts b/frontend/src/desktop/hooks/useFileActionIcons.ts
index 35bd74cb71..771aee757f 100644
--- a/frontend/src/desktop/hooks/useFileActionIcons.ts
+++ b/frontend/src/desktop/hooks/useFileActionIcons.ts
@@ -4,7 +4,7 @@ import SaveOutlinedIcon from "@mui/icons-material/SaveOutlined";
/**
* File action icons for desktop builds.
* Overrides the core implementation with desktop-appropriate icons.
- * The presence of `saveAsIconName` signals RightRail to show the Save As button.
+ * The presence of `saveAsIconName` signals the WorkbenchBar to show the Save As button.
*/
export function useFileActionIcons() {
return {
@@ -12,7 +12,7 @@ export function useFileActionIcons() {
download: SaveOutlinedIcon,
uploadIconName: "folder-rounded" as const,
downloadIconName: "save-rounded" as const,
- // Returning this icon name causes RightRail to render the Save As button.
+ // Returning this icon name causes WorkbenchBar to render the Save As button.
// On desktop, downloadFile() without a localPath shows a native save dialog.
saveAsIconName: "save-as-rounded" as string | undefined,
};
diff --git a/frontend/src/desktop/hooks/useFileActionTerminology.ts b/frontend/src/desktop/hooks/useFileActionTerminology.ts
index 05439c8c2d..fdd3ead22c 100644
--- a/frontend/src/desktop/hooks/useFileActionTerminology.ts
+++ b/frontend/src/desktop/hooks/useFileActionTerminology.ts
@@ -19,7 +19,7 @@ export function useFileActionTerminology() {
mobileUpload: t("landing.mobileUpload", "Upload from Mobile"),
uploadFromComputer: t("landing.openFromComputer", "Open from computer"),
download: t("save", "Save"),
- downloadAll: t("rightRail.saveAll", "Save All"),
+ downloadAll: t("workbenchBar.saveAll", "Save All"),
downloadSelected: t("fileManager.saveSelected", "Save Selected"),
downloadUnavailable: t("saveUnavailable", "Save unavailable for this item"),
noFilesInStorage: t(
diff --git a/frontend/src/desktop/hooks/useSaveShortcut.ts b/frontend/src/desktop/hooks/useSaveShortcut.ts
index 4902549f0d..3e20b7f15c 100644
--- a/frontend/src/desktop/hooks/useSaveShortcut.ts
+++ b/frontend/src/desktop/hooks/useSaveShortcut.ts
@@ -5,7 +5,7 @@ import { downloadFile } from "@app/services/downloadService";
/**
* Desktop-only keyboard shortcut: Ctrl/Cmd+S to save selected files
* Only saves files that have a localFilePath (came from disk)
- * Matches Right Rail button behavior: saves selected files if any, otherwise all files
+ * Matches WorkbenchBar button behavior: saves selected files if any, otherwise all files
*/
export function useSaveShortcut() {
const { selectors, state } = useFileState();
diff --git a/frontend/src/proprietary/components/shared/UpgradeBanner.tsx b/frontend/src/proprietary/components/shared/UpgradeBanner.tsx
index d0ee1612e2..649416f205 100644
--- a/frontend/src/proprietary/components/shared/UpgradeBanner.tsx
+++ b/frontend/src/proprietary/components/shared/UpgradeBanner.tsx
@@ -360,7 +360,8 @@ const UpgradeBanner: React.FC = () => {
closeIconColor="#fff"
buttonVariant="white"
buttonColor="blue"
- minHeight={64}
+ minHeight={48}
+ compact
/>
)}
{renderUrgentBanner()}
diff --git a/frontend/src/proprietary/components/shared/config/configNavSections.tsx b/frontend/src/proprietary/components/shared/config/configNavSections.tsx
index b21ac08c81..1ccfea9e7b 100644
--- a/frontend/src/proprietary/components/shared/config/configNavSections.tsx
+++ b/frontend/src/proprietary/components/shared/config/configNavSections.tsx
@@ -31,11 +31,17 @@ export const useConfigNavSections = (
isAdmin: boolean = false,
runningEE: boolean = false,
loginEnabled: boolean = false,
+ onRequestClose: () => void = () => {},
): ConfigNavSection[] => {
const { t } = useTranslation();
- // Get the core sections (just Preferences)
- const sections = useCoreConfigNavSections(isAdmin, runningEE, loginEnabled);
+ // Get the core sections (Preferences + Help)
+ const sections = useCoreConfigNavSections(
+ isAdmin,
+ runningEE,
+ loginEnabled,
+ onRequestClose,
+ );
// Add account management under Preferences
const preferencesSection = sections.find((section) =>
diff --git a/frontend/src/saas/components/auth/GuestUserBanner.tsx b/frontend/src/saas/components/auth/GuestUserBanner.tsx
index c40586c554..3550042b74 100644
--- a/frontend/src/saas/components/auth/GuestUserBanner.tsx
+++ b/frontend/src/saas/components/auth/GuestUserBanner.tsx
@@ -16,7 +16,7 @@ let hasShownThisLoad = false;
/**
* Guest user toast encouraging account creation.
- * Appears 2s after load, top-right of the viewport, offset by right rail.
+ * Appears 2s after load, top-right of the viewport.
*/
export function GuestUserBanner({ className = "" }: GuestUserBannerProps) {
const { t } = useTranslation();
diff --git a/frontend/src/saas/components/shared/InfoBanner.tsx b/frontend/src/saas/components/shared/InfoBanner.tsx
index 7b2cfde0e7..2f00919998 100644
--- a/frontend/src/saas/components/shared/InfoBanner.tsx
+++ b/frontend/src/saas/components/shared/InfoBanner.tsx
@@ -51,6 +51,7 @@ interface InfoBannerProps {
buttonTextColor?: string; // SaaS-specific for dark theme buttons
minHeight?: number | string;
closeIconColor?: string; // SaaS-specific for dark theme
+ compact?: boolean;
}
/**
@@ -78,6 +79,7 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
buttonTextColor,
minHeight = 56,
closeIconColor,
+ compact = false,
}) => {
if (!show) {
return null;
@@ -90,7 +92,7 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
return (
<Paper
- p="sm"
+ p={compact ? "xs" : "sm"}
radius={0}
style={{
background: background ?? toneStyle.background,
diff --git a/frontend/src/saas/components/shared/config/types.ts b/frontend/src/saas/components/shared/config/types.ts
index 51a309fc45..a17a809477 100644
--- a/frontend/src/saas/components/shared/config/types.ts
+++ b/frontend/src/saas/components/shared/config/types.ts
@@ -30,6 +30,7 @@ export const VALID_NAV_KEYS = [
"adminAudit",
"adminUsage",
"adminEndpoints",
+ "help",
] as const;
// Extend NavKey to include saas-specific keys
@@ -62,6 +63,7 @@ export type NavKey =
| "adminPlan"
| "adminAudit"
| "adminUsage"
- | "adminEndpoints";
+ | "adminEndpoints"
+ | "help";
// some of these are not used yet, but appear in figma designs