#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add limit to max depth for JSX (#8180)
James Bruntonff8772252655
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 9641bf1cf3..7b5dc50552 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -1146,7 +1146,6 @@ refresh = "Refresh"selectFile = "Please select a .sql file to import"size = "Size"title = "Database"-unavailable = "Backup list unavailable for the current database configuration."uploadTitle = "Upload & import"version = "H2 Version"diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsxindex 40da26485a..85df0f4ec1 100644--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx@@ -5,12 +5,13 @@ import React, {useRef,useEffect,forwardRef,+ type RefCallback,} from "react";import { Loader, Tooltip } from "@mantine/core";import { ActionIcon } from "@app/ui/ActionIcon";import { NavSurface } from "@app/ui/NavSurface";import { Button } from "@app/ui/Button";-import { Icon } from "@app/ui/Icon";+import { Icon, type IconName } from "@app/ui/Icon";import { useTranslation } from "react-i18next";import { useFileState, useFileActions } from "@app/contexts/file/fileHooks";import { useAppConfig } from "@app/contexts/AppConfigContext";@@ -40,6 +41,7 @@ import { useClassificationEnabled } from "@app/hooks/useClassificationEnabled";import {FileSidebarGroupControls,useFileSidebarGroups,+ type FileSidebarGroup,} from "@app/components/shared/fileSidebarGrouping";import BulkUploadToServerModal from "@app/components/shared/BulkUploadToServerModal";import { getFileOrigin } from "@app/components/filesPage/fileOrigin";@@ -150,6 +152,343 @@ function FolderTreeSection() {);}+type SidebarAction = NonNullable<FileSidebarProps["extraActions"]>[number];++function SidebarActionRow({ action }: { action: SidebarAction }) {+ if (action.render) return <>{action.render()}</>;+ const explainsDisabled = Boolean(action.disabled && action.disabledTooltip);+ return (+ <Tooltip+ label={action.disabledTooltip ?? action.label}+ position="right"+ withinPortal+ multiline={explainsDisabled}+ w={explainsDisabled ? 220 : undefined}+ // The tooltip explains why an already-labelled action is disabled.+ disabled={!explainsDisabled}+ >+ <div+ className={`file-sidebar-action-row${action.disabled ? " disabled" : ""}`}+ data-testid={action.testId}+ onClick={() => {+ if (action.disabled) return;+ action.onClick();+ }}+ role="button"+ tabIndex={action.disabled ? -1 : 0}+ aria-disabled={action.disabled}+ aria-label={action.label}+ onKeyDown={(e) => {+ if (action.disabled) return;+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ action.onClick();+ }+ }}+ >+ <span className="file-sidebar-action-icon">{action.icon}</span>+ <span className="file-sidebar-action-label sidebar-content-fade">+ {action.label}+ </span>+ </div>+ </Tooltip>+ );+}++function FileDropOverlay({ show }: { show: boolean }) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <div className="file-sidebar-drop-overlay" aria-hidden="true">+ <Icon name="file-up" className="file-sidebar-drop-overlay-icon" />+ <span className="file-sidebar-drop-overlay-text">+ {t("fileSidebar.dropToAdd", "Drop files to add")}+ </span>+ </div>+ );+}++interface LibraryHeaderProps {+ stubs: StirlingFileStub[];+ scrolled: boolean;+ isGoogleDriveEnabled: boolean;+ onGoogleDrive: () => void;+ onAddFiles: () => void;+ onOpenFilesPage: () => void;+}++function LibraryHeader({+ stubs,+ scrolled,+ isGoogleDriveEnabled,+ onGoogleDrive,+ onAddFiles,+ onOpenFilesPage,+}: LibraryHeaderProps) {+ const { t } = useTranslation();+ return (+ <div+ className="file-sidebar-section-header"+ data-scrolled={scrolled || undefined}+ >+ <span className="file-sidebar-section-label">+ {t("fileSidebar.library", "PDF Library")}+ </span>+ <FileSidebarGroupControls stubs={stubs} />+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-external"+ onClick={onOpenFilesPage}+ title={t("fileSidebar.openFileManager", "Browse all files & folders")}+ aria-label={t(+ "fileSidebar.openFileManager",+ "Browse all files & folders",+ )}+ data-testid="open-files-page"+ >+ <Icon name="maximize-2" size={"1rem"} />+ </ActionIcon>+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-search"+ onClick={() => openSuperSearch(["files"])}+ title={t("fileSidebar.searchFiles", "Search files")}+ aria-label={t("fileSidebar.searchFiles", "Search files")}+ data-testid="file-sidebar-search"+ >+ <Icon name="search" size={"1rem"} />+ </ActionIcon>+ {isGoogleDriveEnabled && (+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-drive"+ onClick={onGoogleDrive}+ title={t("fileSidebar.googleDrive", "Open from Google Drive")}+ aria-label={t("fileSidebar.googleDrive", "Open from Google Drive")}+ data-testid="google-drive-button"+ >+ <Icon name="googledrive" size={16} />+ </ActionIcon>+ )}+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-add"+ data-testid="pdf-library-add-files"+ onClick={onAddFiles}+ title={t("fileSidebar.addFiles", "Add files")}+ aria-label={t("fileSidebar.addFiles", "Add files")}+ >+ <Icon name="plus" size={"1rem"} />+ </ActionIcon>+ </div>+ );+}++interface FileGroupSymbolProps {+ icon?: IconName;+ color?: string;+ isOpen: boolean;+}++function FileGroupSymbol({ icon, color, isOpen }: FileGroupSymbolProps) {+ return (+ <span+ className="file-sidebar-group-symbol"+ data-has-icon={!!icon}+ aria-hidden="true"+ >+ {icon && (+ <Icon+ name={icon}+ size="1.05rem"+ className="file-sidebar-group-icon"+ style={color ? { color } : undefined}+ />+ )}+ <Icon+ name={isOpen ? "chevron-down" : "chevron-right"}+ size="1.1rem"+ className="file-sidebar-group-disclosure"+ />+ </span>+ );+}++type RenderFileRow = (stub: StirlingFileStub) => React.ReactNode;++interface FileGroupProps {+ group: FileSidebarGroup;+ isOpen: boolean;+ onToggle: () => void;+ renderFileRow: RenderFileRow;+}++function FileGroup({ group, isOpen, onToggle, renderFileRow }: FileGroupProps) {+ return (+ <div className="file-sidebar-group">+ <Button+ variant="quiet"+ fullWidth+ justify="between"+ className="file-sidebar-group-header"+ onClick={onToggle}+ aria-expanded={isOpen}+ leftSection={+ <FileGroupSymbol+ icon={group.icon}+ color={group.color}+ isOpen={isOpen}+ />+ }+ rightSection={+ <span className="file-sidebar-group-count">{group.stubs.length}</span>+ }+ >+ <span className="file-sidebar-group-label">{group.label}</span>+ </Button>+ <div className="file-sidebar-group-items">+ {isOpen && group.stubs.map(renderFileRow)}+ </div>+ </div>+ );+}++interface GroupedFileListProps {+ groups: FileSidebarGroup[];+ /** Owned by the sidebar so collapse state survives visits to the files page. */+ groupOpen: Record<string, boolean>;+ onGroupOpenChange: (id: string, open: boolean) => void;+ renderFileRow: RenderFileRow;+ total: number;+ onViewAll: () => void;+}++function GroupedFileList({+ groups,+ groupOpen,+ onGroupOpenChange,+ renderFileRow,+ total,+ onViewAll,+}: GroupedFileListProps) {+ const { t } = useTranslation();+ return (+ <>+ {groups.map((group) => {+ const isOpen = groupOpen[group.id] ?? group.defaultExpanded;+ return (+ <FileGroup+ key={group.id}+ group={group}+ isOpen={isOpen}+ onToggle={() => onGroupOpenChange(group.id, !isOpen)}+ renderFileRow={renderFileRow}+ />+ );+ })}+ <Button+ variant="quiet"+ fullWidth+ justify="between"+ className="file-sidebar-view-all"+ onClick={onViewAll}+ rightSection={<Icon name="chevron-right" size={"1rem"} />}+ >+ {t("fileSidebar.viewAll", "View all {{count}} files", {+ count: total,+ })}+ </Button>+ </>+ );+}++interface LibraryFileListProps extends Omit<+ GroupedFileListProps,+ "groups" | "total" | "onViewAll"+> {+ loaded: boolean;+ stubs: StirlingFileStub[];+ groups: FileSidebarGroup[] | null;+ scrollRef: RefCallback<HTMLElement>;+ onOpenFilesPage: () => void;+}++function LibraryFileList({+ loaded,+ stubs,+ groups,+ scrollRef,+ onOpenFilesPage,+ ...grouping+}: LibraryFileListProps) {+ const { t } = useTranslation();+ if (!loaded) {+ return (+ <div className="file-sidebar-loading">+ <Loader size="sm" color="var(--c-text-subtle)" />+ </div>+ );+ }+ if (stubs.length === 0) {+ return (+ <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>+ );+ }+ return (+ <div className="file-sidebar-file-list" ref={scrollRef}>+ {groups ? (+ <GroupedFileList+ groups={groups}+ total={stubs.length}+ onViewAll={onOpenFilesPage}+ {...grouping}+ />+ ) : (+ stubs.map(grouping.renderFileRow)+ )}+ </div>+ );+}++interface FileLibrarySectionProps extends Omit<+ LibraryFileListProps,+ "scrollRef"+> {+ isGoogleDriveEnabled: boolean;+ onGoogleDrive: () => void;+ onAddFiles: () => void;+}++function FileLibrarySection({+ isGoogleDriveEnabled,+ onGoogleDrive,+ onAddFiles,+ ...list+}: FileLibrarySectionProps) {+ const { scrolled, scrollRef } = useIsScrolled();+ return (+ <div className="file-sidebar-files-section sidebar-content-fade">+ <LibraryHeader+ stubs={list.stubs}+ scrolled={scrolled}+ isGoogleDriveEnabled={isGoogleDriveEnabled}+ onGoogleDrive={onGoogleDrive}+ onAddFiles={onAddFiles}+ onOpenFilesPage={list.onOpenFilesPage}+ />+ <BulkAddProgressRow />+ <LibraryFileList scrollRef={scrollRef} {...list} />+ </div>+ );+}+const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(function FileSidebar({@@ -172,8 +511,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const [pendingViewFileId, setPendingViewFileId] = useState<string | null>(null,);- const { scrolled: fileListScrolled, scrollRef: fileListScrollRef } =- useIsScrolled();const { config } = useAppConfig();const {@@ -844,33 +1181,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(...(extraActions ?? []),];- const importActions = (- <>- {isGoogleDriveEnabled && (- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-drive"- onClick={handleGoogleDriveClick}- title={t("fileSidebar.googleDrive", "Open from Google Drive")}- aria-label={t("fileSidebar.googleDrive", "Open from Google Drive")}- data-testid="google-drive-button"- >- <Icon name="googledrive" size={16} />- </ActionIcon>- )}- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-add"- data-testid="pdf-library-add-files"- onClick={openNativeFilePicker}- title={t("fileSidebar.addFiles", "Add files")}- aria-label={t("fileSidebar.addFiles", "Add files")}- >- <Icon name="plus" size={"1rem"} />- </ActionIcon>- </>- );-return (<divref={ref}@@ -888,14 +1198,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(onDragLeave={handleDragLeave}onDrop={handleDrop}>- {isFileDragOver && (- <div className="file-sidebar-drop-overlay" aria-hidden="true">- <Icon name="file-up" className="file-sidebar-drop-overlay-icon" />- <span className="file-sidebar-drop-overlay-text">- {t("fileSidebar.dropToAdd", "Drop files to add")}- </span>- </div>- )}+ <FileDropOverlay show={isFileDragOver} /><div className="file-sidebar-inner"><SidebarHeader />@@ -914,209 +1217,27 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(hidden={sidebarActions.length === 0}>{sidebarActions.map((action) => (- <React.Fragment key={action.label}>- {action.render ? (- action.render()- ) : (- <Tooltip- label={action.disabledTooltip ?? action.label}- position="right"- withinPortal- multiline={Boolean(- action.disabled && action.disabledTooltip,- )}- w={- action.disabled && action.disabledTooltip- ? 220- : undefined- }- // The tooltip explains why an already-labelled action is disabled.- disabled={!(action.disabled && action.disabledTooltip)}- >- <div- className={`file-sidebar-action-row${action.disabled ? " disabled" : ""}`}- data-testid={action.testId}- onClick={() => {- if (action.disabled) return;- action.onClick();- }}- role="button"- tabIndex={action.disabled ? -1 : 0}- aria-disabled={action.disabled}- aria-label={action.label}- onKeyDown={(e) => {- if (action.disabled) return;- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- action.onClick();- }- }}- >- <span className="file-sidebar-action-icon">- {action.icon}- </span>- <span className="file-sidebar-action-label sidebar-content-fade">- {action.label}- </span>- </div>- </Tooltip>- )}- </React.Fragment>+ <SidebarActionRow key={action.label} action={action} />))}</NavSurface><NavSurface className="file-sidebar-files-box"><div className="file-sidebar-scroll">- {currentWorkbench === "myFiles" && <FolderTreeSection />}-- {currentWorkbench !== "myFiles" && (- <div className="file-sidebar-files-section sidebar-content-fade">- <div- className="file-sidebar-section-header"- data-scrolled={fileListScrolled || undefined}- >- <span className="file-sidebar-section-label">- {t("fileSidebar.library", "PDF Library")}- </span>- <FileSidebarGroupControls stubs={allFileStubs} />- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-external"- onClick={() => navActions.setWorkbench("myFiles")}- title={t(- "fileSidebar.openFileManager",- "Browse all files & folders",- )}- aria-label={t(- "fileSidebar.openFileManager",- "Browse all files & folders",- )}- data-testid="open-files-page"- >- <Icon name="maximize-2" size={"1rem"} />- </ActionIcon>- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-search"- onClick={() => openSuperSearch(["files"])}- title={t("fileSidebar.searchFiles", "Search files")}- aria-label={t("fileSidebar.searchFiles", "Search files")}- data-testid="file-sidebar-search"- >- <Icon name="search" size={"1rem"} />- </ActionIcon>- {importActions}- </div>-- <BulkAddProgressRow />-- {!stubsLoaded ? (- <div className="file-sidebar-loading">- <Loader size="sm" color="var(--c-text-subtle)" />- </div>- ) : allFileStubs.length > 0 ? (- <div- className="file-sidebar-file-list"- ref={fileListScrollRef}- >- {fileGroups ? (- <>- {fileGroups.map((group) => {- const isOpen =- groupOpen[group.id] ?? group.defaultExpanded;- return (- <div- className="file-sidebar-group"- key={group.id}- >- <Button- variant="quiet"- fullWidth- justify="between"- className="file-sidebar-group-header"- onClick={() =>- setGroupOpenState(group.id, !isOpen)- }- aria-expanded={isOpen}- leftSection={- <span- className="file-sidebar-group-symbol"- data-has-icon={!!group.icon}- aria-hidden="true"- >- {group.icon && (- <Icon- name={group.icon}- size="1.05rem"- className="file-sidebar-group-icon"- style={- group.color- ? { color: group.color }- : undefined- }- />- )}- <Icon- name={- isOpen- ? "chevron-down"- : "chevron-right"- }- size="1.1rem"- className="file-sidebar-group-disclosure"- />- </span>- }- rightSection={- <span className="file-sidebar-group-count">- {group.stubs.length}- </span>- }- >- <span className="file-sidebar-group-label">- {group.label}- </span>- </Button>- <div className="file-sidebar-group-items">- {isOpen && group.stubs.map(renderFileRow)}- </div>- </div>- );- })}- <Button- variant="quiet"- fullWidth- justify="between"- className="file-sidebar-view-all"- onClick={() => navActions.setWorkbench("myFiles")}- rightSection={- <Icon name="chevron-right" size={"1rem"} />- }- >- {t(- "fileSidebar.viewAll",- "View all {{count}} files",- {- count: allFileStubs.length,- },- )}- </Button>- </>- ) : (- allFileStubs.map(renderFileRow)- )}- </div>- ) : (- <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>+ {currentWorkbench === "myFiles" ? (+ <FolderTreeSection />+ ) : (+ <FileLibrarySection+ loaded={stubsLoaded}+ stubs={allFileStubs}+ groups={fileGroups}+ groupOpen={groupOpen}+ onGroupOpenChange={setGroupOpenState}+ renderFileRow={renderFileRow}+ isGoogleDriveEnabled={isGoogleDriveEnabled}+ onGoogleDrive={handleGoogleDriveClick}+ onAddFiles={openNativeFilePicker}+ onOpenFilesPage={() => navActions.setWorkbench("myFiles")}+ />)}</div></NavSurface>diff --git a/frontend/editor/src/core/components/shared/ShareManagementModal.tsx b/frontend/editor/src/core/components/shared/ShareManagementModal.tsxindex 2a46dfff95..23f5f38fc9 100644--- a/frontend/editor/src/core/components/shared/ShareManagementModal.tsx+++ b/frontend/editor/src/core/components/shared/ShareManagementModal.tsx@@ -1,4 +1,10 @@-import React, { useCallback, useEffect, useMemo, useState } from "react";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";import {Modal,Stack,@@ -15,6 +21,7 @@ import {import { Button } from "@app/ui/Button";import { Icon } from "@app/ui/Icon";import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";import apiClient from "@app/services/apiClient";import { absoluteWithBasePath } from "@app/constants/app";@@ -37,19 +44,712 @@ interface ShareLinkAccessResponse {accessedAt?: string | null;}+interface SharedUser {+ username: string;+ accessRole?: string | null;+}+interface StoredFileResponse {shareLinks?: ShareLinkResponse[];ownedByCurrentUser?: boolean;sharedWithUsers?: string[];- sharedUsers?: Array<{ username: string; accessRole?: string | null }>;+ sharedUsers?: SharedUser[];}+type ShareRole = "editor" | "commenter" | "viewer";++const SHARE_ROLES: ShareRole[] = ["editor", "commenter", "viewer"];+interface ShareManagementModalProps {opened: boolean;onClose: () => void;file: StirlingFileStub;}+function roleLabel(t: TFunction, role: string): string {+ if (role === "editor") return t("storageShare.roleEditor", "Editor");+ if (role === "commenter") return t("storageShare.roleCommenter", "Commenter");+ return t("storageShare.roleViewer", "Viewer");+}++function accessTypeLabel(+ t: TFunction,+ accessType: string | null | undefined,+): string {+ if (accessType === "VIEW") return t("storageShare.viewed", "Viewed");+ if (accessType === "DOWNLOAD") {+ return t("storageShare.downloaded", "Downloaded");+ }+ return t("storageShare.accessed", "Accessed");+}++interface RoleSelectProps {+ label?: string;+ value: string;+ onChange: (role: ShareRole) => void;+ size?: "xs";+}++function RoleSelect({ label, value, onChange, size }: RoleSelectProps) {+ const { t } = useTranslation();+ return (+ <Select+ label={label}+ value={value}+ onChange={(next) => onChange((next as ShareRole) || "editor")}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_FILE_MANAGER_MODAL + 10,+ }}+ data={SHARE_ROLES.map((role) => ({+ value: role,+ label: roleLabel(t, role),+ }))}+ size={size}+ />+ );+}++function RoleBadge({ role }: { role: string | null | undefined }) {+ const { t } = useTranslation();+ if (!role) return null;+ return (+ <Badge variant="light" color="gray">+ {roleLabel(t, role)}+ </Badge>+ );+}++function CommenterHint({ role }: { role: string | null | undefined }) {+ const { t } = useTranslation();+ if (role !== "commenter") return null;+ return (+ <Text size="xs" c="dimmed">+ {t("storageShare.commenterHint", "Commenting is coming soon.")}+ </Text>+ );+}++interface ConfirmRemoveButtonProps {+ label: string;+ confirming: boolean;+ loading: boolean;+ onRequest: () => void;+ onCancel: () => void;+ onConfirm: () => void;+}++function ConfirmRemoveButton({+ label,+ confirming,+ loading,+ onRequest,+ onCancel,+ onConfirm,+}: ConfirmRemoveButtonProps) {+ const { t } = useTranslation();+ if (confirming) {+ return (+ <Group gap="xs">+ <Button accent="danger" size="sm" onClick={onConfirm} loading={loading}>+ {t("confirm", "Confirm")}+ </Button>+ <Button variant="secondary" size="sm" onClick={onCancel}>+ {t("cancel", "Cancel")}+ </Button>+ </Group>+ );+ }+ return (+ <Button+ variant="secondary"+ accent="danger"+ size="sm"+ leftSection={<Icon name="trash" size={16} />}+ onClick={onRequest}+ disabled={loading}+ >+ {label}+ </Button>+ );+}++function ShareModalIntro({ fileName }: { fileName: string }) {+ const { t } = useTranslation();+ return (+ <Group justify="space-between" align="center" gap="md" mt="md">+ <Text size="sm" c="dimmed">+ {t(+ "storageShare.manageDescription",+ "Create and manage links to share this file.",+ )}+ </Text>+ <Text size="sm">+ {t("storageShare.fileLabel", "File")}:{" "}+ <Text span fw={600}>+ {fileName}+ </Text>+ </Text>+ </Group>+ );+}++function SharingErrorAlert({ message }: { message: string | null }) {+ const { t } = useTranslation();+ if (!message) return null;+ return (+ <Alert color="red" title={t("storageShare.errorTitle", "Sharing error")}>+ {message}+ </Alert>+ );+}++function SharingDisabledAlert({ show }: { show: boolean }) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Alert+ color="yellow"+ title={t("storageShare.sharingDisabled", "Sharing is disabled.")}+ >+ {t(+ "storageShare.sharingDisabledBody",+ "Sharing has been disabled by your server settings.",+ )}+ </Alert>+ );+}++interface LinkAccessCardProps {+ show: boolean;+ role: ShareRole;+ loading: boolean;+ onRoleChange: (role: ShareRole) => void;+ onGenerate: () => void;+}++function LinkAccessCard({+ show,+ role,+ loading,+ onRoleChange,+ onGenerate,+}: LinkAccessCardProps) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Paper withBorder radius="md" p="md">+ <Stack gap="sm">+ <Group justify="space-between">+ <Text size="sm" fw={600}>+ {t("storageShare.linkAccessTitle", "Share link access")}+ </Text>+ </Group>+ <RoleSelect+ label={t("storageShare.roleLabel", "Role")}+ value={role}+ onChange={onRoleChange}+ />+ <CommenterHint role={role} />+ <Group justify="flex-end" gap="sm">+ <Button+ leftSection={<Icon name="link" size={18} />}+ onClick={onGenerate}+ loading={loading}+ >+ {t("storageShare.generate", "Generate Link")}+ </Button>+ </Group>+ </Stack>+ </Paper>+ );+}++function SharedUsersCard({ children }: { children: ReactNode }) {+ const { t } = useTranslation();+ return (+ <Paper withBorder radius="md" p="md">+ <Stack gap="sm">+ <Text size="sm" fw={600}>+ {t("storageShare.sharedUsersTitle", "Shared users")}+ </Text>+ {children}+ </Stack>+ </Paper>+ );+}++interface AddUserFormProps {+ value: string;+ error: string | null;+ disabled: boolean;+ canSubmit: boolean;+ onChange: (value: string) => void;+ onSubmit: () => void;+}++function AddUserForm({+ value,+ error,+ disabled,+ canSubmit,+ onChange,+ onSubmit,+}: AddUserFormProps) {+ const { t } = useTranslation();+ return (+ <Group align="flex-end" gap="sm" wrap="nowrap">+ <TextInput+ style={{ flex: 1 }}+ label={t("storageShare.usernameLabel", "Username or email")}+ placeholder={t(+ "storageShare.usernamePlaceholder",+ "Enter a username or email",+ )}+ value={value}+ onChange={(event) => onChange(event.currentTarget.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ onSubmit();+ }+ }}+ disabled={disabled}+ error={error}+ />+ <Button onClick={onSubmit} disabled={!canSubmit}>+ {t("storageShare.addUser", "Add")}+ </Button>+ </Group>+ );+}++interface EmailWarningAlertProps {+ show: boolean;+ loading: boolean;+ onCancel: () => void;+ onConfirm: () => void;+}++function EmailWarningAlert({+ show,+ loading,+ onCancel,+ onConfirm,+}: EmailWarningAlertProps) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Alert+ color="yellow"+ title={t("storageShare.emailWarningTitle", "Email address")}+ variant="light"+ >+ <Stack gap="xs">+ <Text size="sm">+ {t(+ "storageShare.emailWarningBody",+ "This looks like an email address. If this person is not already a Stirling PDF user, they will not be able to access the file.",+ )}+ </Text>+ <Group justify="flex-end" gap="sm">+ <Button variant="secondary" onClick={onCancel} disabled={loading}>+ {t("cancel", "Cancel")}+ </Button>+ <Button onClick={onConfirm} loading={loading}>+ {t("storageShare.emailWarningConfirm", "Share anyway")}+ </Button>+ </Group>+ </Stack>+ </Alert>+ );+}++interface SharedUserRowProps {+ user: SharedUser;+ confirmingRemove: boolean;+ loading: boolean;+ onRoleChange: (role: ShareRole) => void;+ onRequestRemove: () => void;+ onCancelRemove: () => void;+ onRemove: () => void;+}++function SharedUserRow({+ user,+ confirmingRemove,+ loading,+ onRoleChange,+ onRequestRemove,+ onCancelRemove,+ onRemove,+}: SharedUserRowProps) {+ const { t } = useTranslation();+ return (+ <Group justify="space-between" align="flex-start">+ <Stack gap={2}>+ <Text size="sm">{user.username}</Text>+ <CommenterHint role={user.accessRole} />+ </Stack>+ <Group gap="xs" align="center">+ <RoleSelect+ value={user.accessRole ?? "editor"}+ onChange={onRoleChange}+ size="xs"+ />+ <ConfirmRemoveButton+ label={t("storageShare.removeUser", "Remove")}+ confirming={confirmingRemove}+ loading={loading}+ onRequest={onRequestRemove}+ onCancel={onCancelRemove}+ onConfirm={onRemove}+ />+ </Group>+ </Group>+ );+}++interface SharedUserListProps {+ users: SharedUser[];+ confirmRemoveUser: string | null;+ loading: boolean;+ onRoleChange: (username: string, role: ShareRole) => void;+ onRequestRemove: (username: string) => void;+ onCancelRemove: () => void;+ onRemove: (username: string) => void;+}++function SharedUserList({+ users,+ confirmRemoveUser,+ loading,+ onRoleChange,+ onRequestRemove,+ onCancelRemove,+ onRemove,+}: SharedUserListProps) {+ const { t } = useTranslation();+ if (users.length === 0) {+ return (+ <Text size="sm" c="dimmed">+ {t("storageShare.noSharedUsers", "No users have access yet.")}+ </Text>+ );+ }+ return (+ <Stack gap="xs">+ {users.map((user) => (+ <SharedUserRow+ key={user.username}+ user={user}+ confirmingRemove={confirmRemoveUser === user.username}+ loading={loading}+ onRoleChange={(role) => onRoleChange(user.username, role)}+ onRequestRemove={() => onRequestRemove(user.username)}+ onCancelRemove={onCancelRemove}+ onRemove={() => onRemove(user.username)}+ />+ ))}+ </Stack>+ );+}++interface ShareLinksCardProps {+ show: boolean;+ count: number;+ children: ReactNode;+}++function ShareLinksCard({ show, count, children }: ShareLinksCardProps) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Paper withBorder radius="md" p="md">+ <Stack gap="sm">+ <Group justify="space-between">+ <Text size="sm" fw={600}>+ {t("storageShare.linkLabel", "Share link")}+ </Text>+ {count > 0 && (+ <Badge variant="light" color="blue">+ {count}+ </Badge>+ )}+ </Group>+ {children}+ </Stack>+ </Paper>+ );+}++interface ShareLinkStatsProps {+ role: string | null | undefined;+ activity: ShareLinkAccessResponse[] | undefined;+}++function ShareLinkStats({ role, activity }: ShareLinkStatsProps) {+ const { t } = useTranslation();+ const viewCount =+ activity?.filter((entry) => entry.accessType === "VIEW").length ?? 0;+ const downloadCount =+ activity?.filter((entry) => entry.accessType === "DOWNLOAD").length ?? 0;+ const lastAccessedAt = activity?.[0]?.accessedAt;+ return (+ <Stack gap={4}>+ <Group gap="xs">+ <RoleBadge role={role} />+ </Group>+ <Group gap="sm" align="center">+ <Text size="xs" c="dimmed">+ {t("storageShare.viewsCount", "Views: {{count}}", {+ count: viewCount,+ })}+ </Text>+ <Text size="xs" c="dimmed">+ {t("storageShare.downloadsCount", "Downloads: {{count}}", {+ count: downloadCount,+ })}+ </Text>+ {lastAccessedAt && (+ <Text size="xs" c="dimmed">+ {t("storageShare.lastAccessed", "Last accessed")}:{" "}+ {new Date(lastAccessedAt).toLocaleString()}+ </Text>+ )}+ </Group>+ </Stack>+ );+}++interface ShareLinkItemProps {+ link: ShareLinkResponse;+ url: string;+ activity: ShareLinkAccessResponse[] | undefined;+ isSelected: boolean;+ confirmingRevoke: boolean;+ loading: boolean;+ onCopy: () => void;+ onToggleActivity: () => void;+ onRequestRevoke: () => void;+ onCancelRevoke: () => void;+ onRevoke: () => void;+}++function ShareLinkItem({+ link,+ url,+ activity,+ isSelected,+ confirmingRevoke,+ loading,+ onCopy,+ onToggleActivity,+ onRequestRevoke,+ onCancelRevoke,+ onRevoke,+}: ShareLinkItemProps) {+ const { t } = useTranslation();+ return (+ <Paper withBorder radius="md" p="sm">+ <Stack gap="xs">+ <TextInput+ readOnly+ value={url}+ label={t("storageShare.linkLabel", "Share link")}+ rightSection={+ <Button+ variant="tertiary"+ size="sm"+ leftSection={<Icon name="copy" size={16} />}+ onClick={onCopy}+ >+ {t("storageShare.copy", "Copy")}+ </Button>+ }+ />+ <Group justify="space-between" align="center">+ <ShareLinkStats role={link.accessRole} activity={activity} />+ <Group gap="xs">+ <Button+ variant={isSelected ? "secondary" : "primary"}+ size="sm"+ leftSection={<Icon name="rotate-ccw-clock" size={16} />}+ onClick={onToggleActivity}+ >+ {isSelected+ ? t("storageShare.hideActivity", "Hide activity")+ : t("storageShare.viewActivity", "View activity")}+ </Button>+ <ConfirmRemoveButton+ label={t("storageShare.removeLink", "Remove link")}+ confirming={confirmingRevoke}+ loading={loading}+ onRequest={onRequestRevoke}+ onCancel={onCancelRevoke}+ onConfirm={onRevoke}+ />+ </Group>+ </Group>+ </Stack>+ </Paper>+ );+}++interface ShareLinkListProps {+ links: ShareLinkResponse[];+ loading: boolean;+ baseUrl: string;+ activityMap: Record<string, ShareLinkAccessResponse[]>;+ selectedToken: string | null;+ confirmRevokeToken: string | null;+ onCopy: (token: string) => void;+ onToggleActivity: (token: string) => void;+ onRequestRevoke: (token: string) => void;+ onCancelRevoke: () => void;+ onRevoke: (token: string) => void;+}++function ShareLinkList({+ links,+ loading,+ baseUrl,+ activityMap,+ selectedToken,+ confirmRevokeToken,+ onCopy,+ onToggleActivity,+ onRequestRevoke,+ onCancelRevoke,+ onRevoke,+}: ShareLinkListProps) {+ const { t } = useTranslation();+ if (links.length === 0 && loading) return null;+ if (links.length === 0) {+ return (+ <Text size="sm" c="dimmed">+ {t("storageShare.noLinks", "No active share links yet.")}+ </Text>+ );+ }+ return (+ <>+ {links.map((link) => (+ <ShareLinkItem+ key={link.token}+ link={link}+ url={`${baseUrl}${link.token}`}+ activity={activityMap[link.token]}+ isSelected={selectedToken === link.token}+ confirmingRevoke={confirmRevokeToken === link.token}+ loading={loading}+ onCopy={() => onCopy(link.token)}+ onToggleActivity={() => onToggleActivity(link.token)}+ onRequestRevoke={() => onRequestRevoke(link.token)}+ onCancelRevoke={onCancelRevoke}+ onRevoke={() => onRevoke(link.token)}+ />+ ))}+ </>+ );+}++function NoActivityText() {+ const { t } = useTranslation();+ return (+ <Text size="sm" c="dimmed">+ {t("storageShare.noActivity", "No activity yet.")}+ </Text>+ );+}++function ShareActivityEntry({ entry }: { entry: ShareLinkAccessResponse }) {+ const { t } = useTranslation();+ return (+ <Paper radius="md" p="xs" withBorder>+ <Group justify="space-between">+ <Stack gap={2}>+ <Text size="xs" c="dimmed">+ {entry.accessedAt+ ? new Date(entry.accessedAt).toLocaleString()+ : t("unknown", "Unknown")}+ </Text>+ <Text size="sm">+ {entry.username || t("storageShare.unknownUser", "Unknown user")}+ </Text>+ </Stack>+ <Badge size="sm" variant="light">+ {accessTypeLabel(t, entry.accessType)}+ </Badge>+ </Group>+ </Paper>+ );+}++function ShareActivityEntries({+ token,+ entries,+}: {+ token: string;+ entries: ShareLinkAccessResponse[];+}) {+ if (entries.length === 0) return <NoActivityText />;+ return (+ <>+ {entries.map((entry, index) => (+ <ShareActivityEntry key={`${token}-${index}`} entry={entry} />+ ))}+ </>+ );+}++function ShareActivityLog({+ token,+ activity,+}: {+ token: string | null;+ activity: ShareLinkAccessResponse[] | undefined;+}) {+ if (!token) return <NoActivityText />;+ return (+ <ScrollArea h={360} offsetScrollbars>+ <Stack gap="xs">+ <ShareActivityEntries token={token} entries={activity ?? []} />+ </Stack>+ </ScrollArea>+ );+}++interface ShareActivityCardProps {+ show: boolean;+ token: string | null;+ link: ShareLinkResponse | undefined;+ activity: ShareLinkAccessResponse[] | undefined;+}++function ShareActivityCard({+ show,+ token,+ link,+ activity,+}: ShareActivityCardProps) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Paper withBorder radius="md" p="md">+ <Stack gap="sm">+ <Group justify="space-between">+ <Text size="sm" fw={600}>+ {t("storageShare.viewActivity", "View activity")}+ </Text>+ <RoleBadge role={link?.accessRole} />+ </Group>+ <ShareActivityLog token={token} activity={activity} />+ </Stack>+ </Paper>+ );+}+const ShareManagementModal: React.FC<ShareManagementModalProps> = ({opened,onClose,@@ -66,13 +766,9 @@ const ShareManagementModal: React.FC<ShareManagementModalProps> = ({const [activityMap, setActivityMap] = useState<Record<string, ShareLinkAccessResponse[]>>({});- const [sharedUsers, setSharedUsers] = useState<- Array<{ username: string; accessRole?: string | null }>- >([]);+ const [sharedUsers, setSharedUsers] = useState<SharedUser[]>([]);const [shareUsername, setShareUsername] = useState("");- const [shareRole, setShareRole] = useState<"editor" | "commenter" | "viewer">(- "editor",- );+ const [shareRole, setShareRole] = useState<ShareRole>("editor");const [showEmailWarning, setShowEmailWarning] = useState(false);const [selectedActivityToken, setSelectedActivityToken] = useState<string | null@@ -395,7 +1091,7 @@ const ShareManagementModal: React.FC<ShareManagementModalProps> = ({);const handleUpdateUserRole = useCallback(- async (username: string, nextRole: "editor" | "commenter" | "viewer") => {+ async (username: string, nextRole: ShareRole) => {if (!file.remoteStorageId) return;setIsLoading(true);setErrorMessage(null);@@ -496,510 +1192,86 @@ const ShareManagementModal: React.FC<ShareManagementModalProps> = ({overlayProps={{ blur: 8 }}><Stack gap="lg">- <Group justify="space-between" align="center" gap="md" mt="md">- <Text size="sm" c="dimmed">- {t(- "storageShare.manageDescription",- "Create and manage links to share this file.",- )}- </Text>- <Text size="sm">- {t("storageShare.fileLabel", "File")}:{" "}- <Text span fw={600}>- {file.name}- </Text>- </Text>- </Group>-- {errorMessage && (- <Alert- color="red"- title={t("storageShare.errorTitle", "Sharing error")}- >- {errorMessage}- </Alert>- )}- {!sharingEnabled && (- <Alert- color="yellow"- title={t("storageShare.sharingDisabled", "Sharing is disabled.")}- >- {t(- "storageShare.sharingDisabledBody",- "Sharing has been disabled by your server settings.",- )}- </Alert>- )}+ <ShareModalIntro fileName={file.name} />+ <SharingErrorAlert message={errorMessage} />+ <SharingDisabledAlert show={!sharingEnabled} /><SimpleGridcols={{ base: 1, md: shareLinksEnabled ? 2 : 1 }}spacing="lg"><Stack gap="lg">- {shareLinksEnabled && (- <Paper withBorder radius="md" p="md">- <Stack gap="sm">- <Group justify="space-between">- <Text size="sm" fw={600}>- {t("storageShare.linkAccessTitle", "Share link access")}- </Text>- </Group>- <Select- label={t("storageShare.roleLabel", "Role")}- value={shareRole}- onChange={(value) =>- setShareRole((value as typeof shareRole) || "editor")- }- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_FILE_MANAGER_MODAL + 10,- }}- data={[- {- value: "editor",- label: t("storageShare.roleEditor", "Editor"),- },- {- value: "commenter",- label: t("storageShare.roleCommenter", "Commenter"),- },- {- value: "viewer",- label: t("storageShare.roleViewer", "Viewer"),- },- ]}- />- {shareRole === "commenter" && (- <Text size="xs" c="dimmed">- {t(- "storageShare.commenterHint",- "Commenting is coming soon.",- )}- </Text>- )}- <Group justify="flex-end" gap="sm">- <Button- leftSection={<Icon name="link" size={18} />}- onClick={() => createShareLink()}- loading={isLoading}- >- {t("storageShare.generate", "Generate Link")}- </Button>- </Group>- </Stack>- </Paper>- )}-- <Paper withBorder radius="md" p="md">- <Stack gap="sm">- <Text size="sm" fw={600}>- {t("storageShare.sharedUsersTitle", "Shared users")}- </Text>- <Group align="flex-end" gap="sm" wrap="nowrap">- <TextInput- style={{ flex: 1 }}- label={t("storageShare.usernameLabel", "Username or email")}- placeholder={t(- "storageShare.usernamePlaceholder",- "Enter a username or email",- )}- value={shareUsername}- onChange={(event) => {- setShareUsername(event.currentTarget.value);- setShowEmailWarning(false);- }}- onKeyDown={(event) => {- if (event.key === "Enter") {- event.preventDefault();- void handleAddUser();- }- }}- disabled={!sharingEnabled || isLoading}- error={shareUsernameError}- />- <Button- onClick={() => handleAddUser()}- disabled={- !sharingEnabled ||- isLoading ||- !normalizedShareUsername ||- !!shareUsernameError- }- >- {t("storageShare.addUser", "Add")}- </Button>- </Group>- {showEmailWarning && (- <Alert- color="yellow"- title={t("storageShare.emailWarningTitle", "Email address")}- variant="light"- >- <Stack gap="xs">- <Text size="sm">- {t(- "storageShare.emailWarningBody",- "This looks like an email address. If this person is not already a Stirling PDF user, they will not be able to access the file.",- )}- </Text>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={() => setShowEmailWarning(false)}- disabled={isLoading}- >- {t("cancel", "Cancel")}- </Button>- <Button- onClick={() => handleAddUser(true)}- loading={isLoading}- >- {t(- "storageShare.emailWarningConfirm",- "Share anyway",- )}- </Button>- </Group>- </Stack>- </Alert>- )}- {sharedUsers.length === 0 ? (- <Text size="sm" c="dimmed">- {t(- "storageShare.noSharedUsers",- "No users have access yet.",- )}- </Text>- ) : (- <Stack gap="xs">- {sharedUsers.map((user) => (- <Group- key={user.username}- justify="space-between"- align="flex-start"- >- <Stack gap={2}>- <Text size="sm">{user.username}</Text>- {user.accessRole === "commenter" && (- <Text size="xs" c="dimmed">- {t(- "storageShare.commenterHint",- "Commenting is coming soon.",- )}- </Text>- )}- </Stack>- <Group gap="xs" align="center">- <Select- value={user.accessRole ?? "editor"}- onChange={(value) => {- const nextRole =- (value as "editor" | "commenter" | "viewer") ||- "editor";- void handleUpdateUserRole(- user.username,- nextRole,- );- }}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_FILE_MANAGER_MODAL + 10,- }}- data={[- {- value: "editor",- label: t("storageShare.roleEditor", "Editor"),- },- {- value: "commenter",- label: t(- "storageShare.roleCommenter",- "Commenter",- ),- },- {- value: "viewer",- label: t("storageShare.roleViewer", "Viewer"),- },- ]}- size="xs"- />- {confirmRemoveUser === user.username ? (- <Group gap="xs">- <Button- accent="danger"- size="sm"- onClick={() => {- void handleRemoveUser(user.username);- }}- loading={isLoading}- >- {t("confirm", "Confirm")}- </Button>- <Button- variant="secondary"- size="sm"- onClick={() => setConfirmRemoveUser(null)}- >- {t("cancel", "Cancel")}- </Button>- </Group>- ) : (- <Button- variant="secondary"- accent="danger"- size="sm"- leftSection={<Icon name="trash" size={16} />}- onClick={() =>- setConfirmRemoveUser(user.username)- }- disabled={isLoading}- >- {t("storageShare.removeUser", "Remove")}- </Button>- )}- </Group>- </Group>- ))}- </Stack>- )}- </Stack>- </Paper>-- {shareLinksEnabled && (- <Paper withBorder radius="md" p="md">- <Stack gap="sm">- <Group justify="space-between">- <Text size="sm" fw={600}>- {t("storageShare.linkLabel", "Share link")}- </Text>- {shareLinks.length > 0 && (- <Badge variant="light" color="blue">- {shareLinks.length}- </Badge>- )}- </Group>-- {shareLinks.length === 0 && !isLoading && (- <Text size="sm" c="dimmed">- {t("storageShare.noLinks", "No active share links yet.")}- </Text>- )}-- {shareLinks.map((link) => {- const activity = activityMap[link.token];- const viewCount =- activity?.filter((entry) => entry.accessType === "VIEW")- .length ?? 0;- const downloadCount =- activity?.filter(- (entry) => entry.accessType === "DOWNLOAD",- ).length ?? 0;- const lastAccessedAt = activity?.[0]?.accessedAt;- const isSelected = selectedActivityToken === link.token;- return (- <Paper key={link.token} withBorder radius="md" p="sm">- <Stack gap="xs">- <TextInput- readOnly- value={`${shareBaseUrl}${link.token}`}- label={t("storageShare.linkLabel", "Share link")}- rightSection={- <Button- variant="tertiary"- size="sm"- leftSection={<Icon name="copy" size={16} />}- onClick={() => handleCopyLink(link.token)}- >- {t("storageShare.copy", "Copy")}- </Button>- }- />- <Group justify="space-between" align="center">- <Stack gap={4}>- <Group gap="xs">- {link.accessRole && (- <Badge variant="light" color="gray">- {link.accessRole === "editor"- ? t("storageShare.roleEditor", "Editor")- : link.accessRole === "commenter"- ? t(- "storageShare.roleCommenter",- "Commenter",- )- : t(- "storageShare.roleViewer",- "Viewer",- )}- </Badge>- )}- </Group>- <Group gap="sm" align="center">- <Text size="xs" c="dimmed">- {t(- "storageShare.viewsCount",- "Views: {{count}}",- { count: viewCount },- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "storageShare.downloadsCount",- "Downloads: {{count}}",- { count: downloadCount },- )}- </Text>- {lastAccessedAt && (- <Text size="xs" c="dimmed">- {t(- "storageShare.lastAccessed",- "Last accessed",- )}- :{" "}- {new Date(lastAccessedAt).toLocaleString()}- </Text>- )}- </Group>- </Stack>- <Group gap="xs">- <Button- variant={isSelected ? "secondary" : "primary"}- size="sm"- leftSection={- <Icon name="rotate-ccw-clock" size={16} />- }- onClick={() =>- setSelectedActivityToken((prev) =>- prev === link.token ? null : link.token,- )- }- >- {isSelected- ? t(- "storageShare.hideActivity",- "Hide activity",- )- : t(- "storageShare.viewActivity",- "View activity",- )}- </Button>- {confirmRevokeToken === link.token ? (- <Group gap="xs">- <Button- accent="danger"- size="sm"- onClick={() => {- void handleRevokeLink(link.token);- }}- loading={isLoading}- >- {t("confirm", "Confirm")}- </Button>- <Button- variant="secondary"- size="sm"- onClick={() => setConfirmRevokeToken(null)}- >- {t("cancel", "Cancel")}- </Button>- </Group>- ) : (- <Button- variant="secondary"- accent="danger"- size="sm"- leftSection={<Icon name="trash" size={16} />}- onClick={() =>- setConfirmRevokeToken(link.token)- }- disabled={isLoading}- >- {t("storageShare.removeLink", "Remove link")}- </Button>- )}- </Group>- </Group>- </Stack>- </Paper>- );- })}- </Stack>- </Paper>- )}+ <LinkAccessCard+ show={shareLinksEnabled}+ role={shareRole}+ loading={isLoading}+ onRoleChange={setShareRole}+ onGenerate={() => createShareLink()}+ />++ <SharedUsersCard>+ <AddUserForm+ value={shareUsername}+ error={shareUsernameError}+ disabled={!sharingEnabled || isLoading}+ canSubmit={+ sharingEnabled &&+ !isLoading &&+ !!normalizedShareUsername &&+ !shareUsernameError+ }+ onChange={(value) => {+ setShareUsername(value);+ setShowEmailWarning(false);+ }}+ onSubmit={() => void handleAddUser()}+ />+ <EmailWarningAlert+ show={showEmailWarning}+ loading={isLoading}+ onCancel={() => setShowEmailWarning(false)}+ onConfirm={() => handleAddUser(true)}+ />+ <SharedUserList+ users={sharedUsers}+ confirmRemoveUser={confirmRemoveUser}+ loading={isLoading}+ onRoleChange={(username, role) =>+ void handleUpdateUserRole(username, role)+ }+ onRequestRemove={setConfirmRemoveUser}+ onCancelRemove={() => setConfirmRemoveUser(null)}+ onRemove={(username) => void handleRemoveUser(username)}+ />+ </SharedUsersCard>++ <ShareLinksCard show={shareLinksEnabled} count={shareLinks.length}>+ <ShareLinkList+ links={shareLinks}+ loading={isLoading}+ baseUrl={shareBaseUrl}+ activityMap={activityMap}+ selectedToken={selectedActivityToken}+ confirmRevokeToken={confirmRevokeToken}+ onCopy={handleCopyLink}+ onToggleActivity={(token) =>+ setSelectedActivityToken((prev) =>+ prev === token ? null : token,+ )+ }+ onRequestRevoke={setConfirmRevokeToken}+ onCancelRevoke={() => setConfirmRevokeToken(null)}+ onRevoke={(token) => void handleRevokeLink(token)}+ />+ </ShareLinksCard></Stack>- {shareLinksEnabled && (- <Paper withBorder radius="md" p="md">- <Stack gap="sm">- <Group justify="space-between">- <Text size="sm" fw={600}>- {t("storageShare.viewActivity", "View activity")}- </Text>- {selectedLink && selectedLink.accessRole && (- <Badge variant="light" color="gray">- {selectedLink.accessRole === "editor"- ? t("storageShare.roleEditor", "Editor")- : selectedLink.accessRole === "commenter"- ? t("storageShare.roleCommenter", "Commenter")- : t("storageShare.roleViewer", "Viewer")}- </Badge>- )}- </Group>- {!selectedActivityToken && (- <Text size="sm" c="dimmed">- {t("storageShare.noActivity", "No activity yet.")}- </Text>- )}- {selectedActivityToken && (- <ScrollArea h={360} offsetScrollbars>- <Stack gap="xs">- {(selectedActivity ?? []).length > 0 ? (- selectedActivity?.map((entry, index) => (- <Paper- key={`${selectedActivityToken}-${index}`}- radius="md"- p="xs"- withBorder- >- <Group justify="space-between">- <Stack gap={2}>- <Text size="xs" c="dimmed">- {entry.accessedAt- ? new Date(- entry.accessedAt,- ).toLocaleString()- : t("unknown", "Unknown")}- </Text>- <Text size="sm">- {entry.username ||- t(- "storageShare.unknownUser",- "Unknown user",- )}- </Text>- </Stack>- <Badge size="sm" variant="light">- {entry.accessType === "VIEW"- ? t("storageShare.viewed", "Viewed")- : entry.accessType === "DOWNLOAD"- ? t("storageShare.downloaded", "Downloaded")- : t("storageShare.accessed", "Accessed")}- </Badge>- </Group>- </Paper>- ))- ) : (- <Text size="sm" c="dimmed">- {t("storageShare.noActivity", "No activity yet.")}- </Text>- )}- </Stack>- </ScrollArea>- )}- </Stack>- </Paper>- )}+ <ShareActivityCard+ show={shareLinksEnabled}+ token={selectedActivityToken}+ link={selectedLink}+ activity={selectedActivity}+ /></SimpleGrid></Stack></Modal>diff --git a/frontend/editor/src/core/components/shared/UpdateModal.tsx b/frontend/editor/src/core/components/shared/UpdateModal.tsxindex 1721e4b93e..61fe724050 100644--- a/frontend/editor/src/core/components/shared/UpdateModal.tsx+++ b/frontend/editor/src/core/components/shared/UpdateModal.tsx@@ -1,4 +1,4 @@-import React, { useState, useEffect } from "react";+import React, { useState, useEffect, type ReactNode } from "react";import {Modal,Stack,@@ -18,11 +18,13 @@ import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";import {updateService,UpdateSummary,FullUpdateInfo,MachineInfo,+ VersionUpdate,} from "@app/services/updateService";import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";import { handleExternalLinkClick } from "@app/platform/externalLinkClick";@@ -100,6 +102,903 @@ function formatSize(bytes: number | null | undefined): string {return `~${formatBytes(bytes)}`;}+type DesktopInstall = NonNullable<UpdateModalProps["desktopInstall"]>;+type MigrationGuide = NonNullable<UpdateSummary["migration_guides"]>[number];++const RELEASES_URL = "https://github.com/Stirling-Tools/Stirling-PDF/releases";++// Show max 10 initially to keep the modal manageable+const INITIAL_VERSION_COUNT = 10;++function releaseTagUrl(version: string | null): string {+ return `${RELEASES_URL}/tag/v${version}`;+}++function getPriorityColor(priority: string): string {+ switch (priority?.toLowerCase()) {+ case "urgent":+ return "red";+ case "normal":+ return "blue";+ case "minor":+ return "cyan";+ case "low":+ return "gray";+ default:+ return "gray";+ }+}++function getPriorityLabel(t: TFunction, priority: string): string {+ const key = priority?.toLowerCase();+ return t(`update.priority.${key}`, priority || "Normal");+}++const handleExternalLink =+ (url: string) => (e: React.MouseEvent<HTMLElement>) => {+ e.stopPropagation();+ handleExternalLinkClick(url, e);+ };++interface UpdateModalHeaderProps {+ canClose: boolean;+ onClose: () => void;+}++function UpdateModalHeader({ canClose, onClose }: UpdateModalHeaderProps) {+ const { t } = useTranslation();+ return (+ <Box style={{ padding: "24px 28px 16px", flexShrink: 0 }}>+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <Group gap="md" align="flex-start" wrap="nowrap">+ <Box+ style={{+ width: 48,+ height: 48,+ borderRadius: "50%",+ background: "var(--mantine-color-blue-filled)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ flexShrink: 0,+ }}+ >+ <Icon+ name="square-arrow-down"+ size={26}+ style={{ color: "white" }}+ />+ </Box>+ <Box>+ <Text fw={700} size="xl" lh={1.3}>+ {t("update.modalTitle", "Update Available")}+ </Text>+ <Text size="sm" c="dimmed" mt={2}>+ {t(+ "update.modalSubtitle",+ "A new version of Stirling-PDF is ready to install.",+ )}+ </Text>+ </Box>+ </Group>+ {canClose && (+ <ActionIcon+ onClick={onClose}+ size="lg"+ variant="tertiary"+ aria-label={t("update.closeModal", "Close update modal")}+ >+ <Icon name="x" size={20} />+ </ActionIcon>+ )}+ </Group>+ </Box>+ );+}++function VersionColumn({+ label,+ children,+}: {+ label: string;+ children: ReactNode;+}) {+ return (+ <Stack gap={2} align="center">+ <Text size="xs" c="dimmed" tt="uppercase" fw={600} lh={1}>+ {label}+ </Text>+ {children}+ </Stack>+ );+}++function StableBadge({ show }: { show: boolean }) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ // `variant="filled" color="green"` produced an acid-green+ // pill that was noisy in light mode and oddly washed out+ // in dark mode. `light` gives a soft teal-ish chip that+ // reads well in both themes.+ <Badge+ color="teal"+ variant="light"+ size="sm"+ radius="sm"+ style={{ marginTop: 4 }}+ >+ {t("update.stable", "STABLE")}+ </Badge>+ );+}++interface VersionComparisonProps {+ currentVersion: string;+ updateSummary: UpdateSummary;+}++function VersionComparison({+ currentVersion,+ updateSummary,+}: VersionComparisonProps) {+ const { t } = useTranslation();+ const isStable =+ updateSummary.latest_stable_version === updateSummary.latest_version;+ return (+ <Box+ style={{+ border:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ borderRadius: 12,+ padding: "24px 28px",+ background:+ "color-mix(in srgb, var(--mantine-color-body) 100%, transparent)",+ }}+ >+ <Group justify="center" align="center" wrap="nowrap" gap="xl">+ <VersionColumn label={t("update.current", "Current Version")}>+ <Text fw={800} fz={32} lh={1.1}>+ {currentVersion}+ </Text>+ </VersionColumn>+ <Icon+ name="arrow-right"+ size={28}+ style={{+ color: "var(--mantine-color-dimmed)",+ flexShrink: 0,+ }}+ />+ <VersionColumn label={t("update.latest", "Latest Version")}>+ <Group gap="sm" align="center">+ <Text fw={800} fz={32} c="var(--c-accent-text)" lh={1.1}>+ {updateSummary.latest_version}+ </Text>+ <StableBadge+ show={Boolean(isStable || updateSummary.latest_stable_version)}+ />+ </Group>+ </VersionColumn>+ </Group>+ </Box>+ );+}++/**+ * Breaking changes show here as a compact chip rather than a full-width+ * banner; the per-version detail lives in the version history.+ */+function UpdatePriority({ updateSummary }: { updateSummary: UpdateSummary }) {+ const { t } = useTranslation();+ return (+ <Group gap="sm" align="center" px={4}>+ <Badge+ color={getPriorityColor(updateSummary.max_priority)}+ variant="filled"+ size="lg"+ radius="sm"+ >+ {getPriorityLabel(t, updateSummary.max_priority)}+ </Badge>+ {updateSummary.any_breaking && (+ <Badge+ color="orange"+ variant="light"+ size="lg"+ radius="sm"+ leftSection={<Icon name="triangle-alert" size={14} />}+ >+ {t("update.breaking", "Breaking")}+ </Badge>+ )}+ <Text size="sm" c="dimmed" style={{ flex: 1 }}>+ {updateSummary.recommended_action ||+ t(+ "update.defaultRecommendation",+ "This update contains important fixes and improvements.",+ )}+ </Text>+ </Group>+ );+}++/**+ * Shown when can_install_updates reported that msiexec would need UAC+ * elevation this user can't satisfy.+ */+function InstallBlockedAlert({ show }: { show: boolean }) {+ const { t } = useTranslation();+ if (!show) return null;+ return (+ <Alert+ variant="light"+ color="orange"+ radius="md"+ icon={<Icon name="triangle-alert" size={18} />}+ title={t(+ "desktopUpdate.blocked.title",+ "Administrator permissions required",+ )}+ >+ <Text size="sm">+ {t(+ "desktopUpdate.blocked.message",+ "Stirling-PDF does not have permission to update itself on this machine.",+ )}{" "}+ <Anchor+ href={WINDOWS_INSTALL_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ onClick={handleExternalLink(WINDOWS_INSTALL_DOCS_URL)}+ // Sits inside a sentence, so the accent alone does not+ // separate it from the surrounding copy.+ underline="always"+ >+ {t(+ "desktopUpdate.blocked.docsLink",+ "View installation documentation",+ )}+ </Anchor>+ </Text>+ </Alert>+ );+}++interface ExternalTextLinkProps {+ href: string;+ color: string;+ children: ReactNode;+}++function ExternalTextLink({ href, color, children }: ExternalTextLinkProps) {+ return (+ <Text+ size="sm"+ component="a"+ href={href}+ target="_blank"+ onClick={handleExternalLink(href)}+ c={color}+ style={{+ textDecoration: "none",+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ }}+ >+ {children} <Icon name="external-link" size={14} />+ </Text>+ );+}++function WhatsNewCard({ version }: { version: string | null }) {+ const { t } = useTranslation();+ return (+ <Box+ style={{+ background:+ "color-mix(in srgb, var(--mantine-color-blue-filled) 8%, transparent)",+ borderRadius: 12,+ padding: "16px 20px",+ border:+ "1px solid color-mix(in srgb, var(--mantine-color-blue-filled) 15%, transparent)",+ }}+ >+ <Group justify="space-between" align="center">+ <Group gap={8}>+ <Icon+ name="star"+ size={18}+ filled+ style={{ color: "var(--c-accent-text)" }}+ />+ <Text fw={600} size="sm">+ {t("update.whatsNewIn", "What's new in")} {version}+ </Text>+ </Group>+ <Group gap="sm">+ <ExternalTextLink+ href={releaseTagUrl(version)}+ color="var(--c-accent-text)"+ >+ {t("update.releaseNotes", "Release Notes")}+ </ExternalTextLink>+ <ExternalTextLink href={RELEASES_URL} color="dimmed">+ {t("update.allReleases", "All Releases")}+ </ExternalTextLink>+ </Group>+ </Group>+ </Box>+ );+}++function MigrationGuideRow({+ guide,+ isFirst,+}: {+ guide: MigrationGuide;+ isFirst: boolean;+}) {+ const { t } = useTranslation();+ return (+ <Box+ style={{+ borderTop: isFirst+ ? "1px solid var(--c-border-subtle, var(--mantine-color-default-border))"+ : undefined,+ borderBottom:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ padding: "10px 12px",+ }}+ >+ <Group justify="space-between" align="center" wrap="nowrap">+ <Group gap="sm" style={{ flex: 1 }}>+ <Box+ style={{+ width: 8,+ height: 8,+ borderRadius: "50%",+ background: "var(--mantine-color-green-filled)",+ flexShrink: 0,+ }}+ />+ <Text fw={600} size="sm">+ {guide.version}+ </Text>+ <Text size="xs" c="dimmed" lineClamp={1}>+ {guide.notes}+ </Text>+ </Group>+ <Button+ as="a"+ href={guide.url}+ target="_blank"+ onClick={handleExternalLink(guide.url)}+ variant="secondary"+ size="sm"+ rightSection={<Icon name="external-link" size={12} />}+ >+ {t("update.viewGuide", "View Guide")}+ </Button>+ </Group>+ </Box>+ );+}++function MigrationGuides({ guides }: { guides: MigrationGuide[] | undefined }) {+ const { t } = useTranslation();+ if (!guides || guides.length === 0) return null;+ return (+ <Box>+ <Text fw={600} size="sm" mb={4}>+ {t("update.migrationGuides", "Migration Guides")}+ </Text>+ <Text size="xs" c="dimmed" mb="sm">+ {t(+ "update.migrationGuidesDesc",+ "Review important changes before updating.",+ )}+ </Text>+ <Stack gap={0}>+ {guides.map((guide, idx) => (+ <MigrationGuideRow key={idx} guide={guide} isFirst={idx === 0} />+ ))}+ </Stack>+ </Box>+ );+}++interface VersionSummaryProps {+ version: VersionUpdate;+ isExpanded: boolean;+ onToggle: () => void;+}++function VersionSummary({+ version,+ isExpanded,+ onToggle,+}: VersionSummaryProps) {+ const { t } = useTranslation();+ return (+ <Group+ justify="space-between"+ align="center"+ p="xs"+ px="sm"+ style={{ cursor: "pointer" }}+ onClick={onToggle}+ >+ <Group gap="sm" style={{ flex: 1 }}>+ <Text fw={700} size="sm" style={{ minWidth: 50 }}>+ {version.version}+ </Text>+ <Badge+ color={getPriorityColor(version.priority)}+ size="xs"+ variant="light"+ >+ {getPriorityLabel(t, version.priority)}+ </Badge>+ {version.compatibility.breaking_changes && (+ <Badge color="orange" size="xs" variant="light">+ {t("update.breaking", "Breaking")}+ </Badge>+ )}+ {!isExpanded && version.announcement?.title && (+ <Text size="xs" c="dimmed" lineClamp={1} style={{ flex: 1 }}>+ {version.announcement.title}+ </Text>+ )}+ </Group>+ <Group gap={4}>+ <Button+ as="a"+ href={releaseTagUrl(version.version)}+ target="_blank"+ variant="tertiary"+ size="sm"+ onClick={handleExternalLink(releaseTagUrl(version.version))}+ rightSection={<Icon name="external-link" size={11} />}+ >+ {t("update.notes", "Notes")}+ </Button>+ <Icon+ name={isExpanded ? "chevron-up" : "chevron-down"}+ size={18}+ style={{ color: "var(--mantine-color-dimmed)" }}+ />+ </Group>+ </Group>+ );+}++function BreakingChangesAlert({+ compatibility,+}: {+ compatibility: VersionUpdate["compatibility"];+}) {+ const { t } = useTranslation();+ if (!compatibility.breaking_changes) return null;+ const guideUrl = compatibility.migration_guide_url;+ return (+ <Alert+ variant="light"+ color="orange"+ radius="sm"+ icon={<Icon name="triangle-alert" size={16} />}+ title={t("update.breakingChanges", "Breaking Changes")}+ >+ <Text size="sm">+ {compatibility.breaking_description ||+ t(+ "update.breakingChangesDefault",+ "This version contains breaking changes.",+ )}+ </Text>+ {guideUrl && (+ <Button+ as="a"+ href={guideUrl}+ target="_blank"+ onClick={handleExternalLink(guideUrl)}+ variant="secondary"+ accent="warning"+ size="sm"+ style={{ marginTop: "var(--mantine-spacing-xs)" }}+ rightSection={<Icon name="external-link" size={14} />}+ >+ {t("update.migrationGuide", "Migration Guide")}+ </Button>+ )}+ </Alert>+ );+}++function VersionDetails({ version }: { version: VersionUpdate }) {+ return (+ <Box+ px="sm"+ pb="sm"+ style={{+ borderTop:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ }}+ >+ <Stack gap="sm" mt="sm">+ {version.announcement?.message && (+ <Text size="sm" c="dimmed" style={{ lineHeight: 1.6 }}>+ {version.announcement.message}+ </Text>+ )}+ <BreakingChangesAlert compatibility={version.compatibility} />+ </Stack>+ </Box>+ );+}++interface VersionHistoryItemProps {+ version: VersionUpdate;+ isFirst: boolean;+ isExpanded: boolean;+ onToggle: () => void;+}++function VersionHistoryItem({+ version,+ isFirst,+ isExpanded,+ onToggle,+}: VersionHistoryItemProps) {+ return (+ <Box+ style={{+ borderTop: isFirst+ ? "1px solid var(--c-border-subtle, var(--mantine-color-default-border))"+ : undefined,+ borderBottom:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ }}+ >+ <VersionSummary+ version={version}+ isExpanded={isExpanded}+ onToggle={onToggle}+ />+ <Collapse in={isExpanded}>+ <VersionDetails version={version} />+ </Collapse>+ </Box>+ );+}++interface ShowAllVersionsButtonProps {+ total: number;+ showAll: boolean;+ onToggle: () => void;+}++function ShowAllVersionsButton({+ total,+ showAll,+ onToggle,+}: ShowAllVersionsButtonProps) {+ const { t } = useTranslation();+ if (total <= INITIAL_VERSION_COUNT) return null;+ return (+ <Center mt="sm">+ <Button variant="tertiary" size="sm" onClick={onToggle}>+ {showAll+ ? t("update.showLess", "Show fewer versions")+ : t("update.showMore", {+ defaultValue: "Show all {{count}} versions",+ count: total,+ })}+ </Button>+ </Center>+ );+}++interface VersionHistoryProps {+ loading: boolean;+ versions: VersionUpdate[];+ expandedVersions: Set<number>;+ onToggleVersion: (index: number) => void;+ showAll: boolean;+ onToggleShowAll: () => void;+}++function VersionHistory({+ loading,+ versions,+ expandedVersions,+ onToggleVersion,+ showAll,+ onToggleShowAll,+}: VersionHistoryProps) {+ const { t } = useTranslation();+ if (loading) {+ return (+ <Center py="lg">+ <Group gap="sm">+ <Loader size="sm" />+ <Text size="sm" c="dimmed">+ {t("update.loadingDetailedInfo", "Loading version details...")}+ </Text>+ </Group>+ </Center>+ );+ }+ const visibleVersions = showAll+ ? versions+ : versions.slice(0, INITIAL_VERSION_COUNT);+ if (visibleVersions.length === 0) return null;+ return (+ <Box>+ <Group justify="space-between" align="center" mb="sm">+ <Text fw={600} size="sm">+ {t("update.versionHistory", "Version History")}+ </Text>+ <Text size="xs" c="dimmed">+ {versions.length} {versions.length === 1 ? "version" : "versions"}+ </Text>+ </Group>+ <Stack gap={0}>+ {visibleVersions.map((version, index) => (+ <VersionHistoryItem+ key={index}+ version={version}+ isFirst={index === 0}+ isExpanded={expandedVersions.has(index)}+ onToggle={() => onToggleVersion(index)}+ />+ ))}+ </Stack>+ <ShowAllVersionsButton+ total={versions.length}+ showAll={showAll}+ onToggle={onToggleShowAll}+ />+ </Box>+ );+}++interface InstallProgressProps {+ state: "downloading" | "installing";+ progress: DesktopInstallProgress | null;+}++function InstallProgress({ state, progress }: InstallProgressProps) {+ const { t } = useTranslation();+ return (+ <Stack gap="sm">+ <Group justify="space-between" align="center">+ <Text size="sm" fw={600}>+ {state === "downloading"+ ? t("desktopUpdate.downloading", "Downloading update...")+ : t("desktopUpdate.installing", "Installing update...")}+ </Text>+ {progress && progress.total !== null && (+ <Text size="xs" c="dimmed">+ {formatBytes(progress.downloaded)} / {formatBytes(progress.total)}+ </Text>+ )}+ </Group>+ <Progress+ value={state === "installing" ? 100 : (progress?.percent ?? 0)}+ size="lg"+ animated+ radius="xl"+ />+ {state === "installing" && (+ <Alert variant="light" color="blue" radius="sm" py="xs">+ <Text size="xs">+ {t(+ "desktopUpdate.installingWarning",+ "The app will close automatically to complete the installation.",+ )}+ </Text>+ </Alert>+ )}+ </Stack>+ );+}++function DesktopInstallMessage({+ desktopInstall,+}: {+ desktopInstall: DesktopInstall;+}) {+ const { t } = useTranslation();+ switch (desktopInstall.state) {+ case "downloading":+ case "installing":+ return (+ <InstallProgress+ state={desktopInstall.state}+ progress={desktopInstall.progress}+ />+ );+ case "ready-to-restart":+ return (+ <Alert+ icon={<Icon name="circle-check" />}+ color="green"+ variant="light"+ radius="md"+ title={t("desktopUpdate.readyToRestart", "Update Ready")}+ >+ {t(+ "desktopUpdate.restartMessage",+ "The update has been installed. Restart the app to finish.",+ )}+ </Alert>+ );+ case "error":+ return (+ <Alert+ icon={<Icon name="circle-alert" />}+ color="red"+ variant="light"+ radius="md"+ title={t("desktopUpdate.updateFailed", "Update Failed")}+ >+ {desktopInstall.errorMessage ??+ t(+ "desktopUpdate.updateFailedMessage",+ "Failed to download or install the update.",+ )}+ </Alert>+ );+ default:+ return null;+ }+}++function DesktopInstallStatus({+ desktopInstall,+}: {+ desktopInstall: DesktopInstall | undefined;+}) {+ if (!desktopInstall || desktopInstall.state === "idle") return null;+ return (+ <Box+ style={{+ border:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ borderRadius: 12,+ padding: "16px 20px",+ }}+ >+ <DesktopInstallMessage desktopInstall={desktopInstall} />+ </Box>+ );+}++/** Link to the release download page; renders nothing without a URL. */+function DownloadLatestButton({+ url,+ secondary = false,+}: {+ url: string | null;+ secondary?: boolean;+}) {+ const { t } = useTranslation();+ if (!url) return null;+ return (+ <Button+ as="a"+ href={url}+ target="_blank"+ onClick={handleExternalLink(url)}+ variant={secondary ? "secondary" : undefined}+ size="md"+ leftSection={<Icon name="download" size={secondary ? 16 : 20} />}+ >+ {t("update.downloadLatest", "Download Latest")}+ </Button>+ );+}++interface UpdateActionsProps {+ desktopInstall: DesktopInstall | undefined;+ installBlocked: boolean;+ downloadUrl: string | null;+ downloadSizeBytes: number | null | undefined;+}++function UpdateActions({+ desktopInstall,+ installBlocked,+ downloadUrl,+ downloadSizeBytes,+}: UpdateActionsProps) {+ const { t } = useTranslation();+ if (!desktopInstall) {+ // Tauri updater not available at all: only show the external download+ // link. This is the fallback when latest.json is unreachable, the pubkey+ // is wrong, signatures don't match, etc.+ return <DownloadLatestButton url={downloadUrl} />;+ }+ if (desktopInstall.state === "ready-to-restart") {+ return (+ <Button+ size="md"+ leftSection={<Icon name="rotate-ccw" size={20} />}+ onClick={() => void desktopInstall.actions.restartApp()}+ >+ {t("desktopUpdate.restartNow", "Restart Now")}+ </Button>+ );+ }+ if (desktopInstall.state !== "idle" && desktopInstall.state !== "error") {+ return null;+ }+ // When install is blocked (non-admin) or the tauri updater failed, the user+ // still needs a way forward: offer the GitHub release page alongside the+ // disabled Install Now button.+ const offerDownload = installBlocked || desktopInstall.state === "error";+ return (+ <>+ <DownloadLatestButton+ url={offerDownload ? downloadUrl : null}+ secondary+ />+ <Button+ size="md"+ leftSection={<Icon name="download" size={20} />}+ onClick={() => void desktopInstall.actions.startInstall()}+ disabled={installBlocked}+ >+ <Box>+ <Text size="sm" fw={700} lh={1.2}>+ {t("desktopUpdate.installNow", "Install Now")}+ </Text>+ <Text size="xs" lh={1.2} style={{ opacity: 0.7 }}>+ {formatSize(downloadSizeBytes)}+ </Text>+ </Box>+ </Button>+ </>+ );+}++interface UpdateModalFooterProps extends UpdateActionsProps {+ canClose: boolean;+ onLater: () => void;+}++function UpdateModalFooter({+ canClose,+ onLater,+ ...actions+}: UpdateModalFooterProps) {+ const { t } = useTranslation();+ return (+ <Box+ style={{+ borderTop:+ "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",+ padding: "16px 28px",+ flexShrink: 0,+ }}+ >+ <Group justify="flex-end" gap="sm">+ <Button+ variant="secondary"+ onClick={onLater}+ disabled={!canClose}+ size="md"+ >+ {t("update.later", "Later")}+ </Button>+ <UpdateActions {...actions} />+ </Group>+ </Box>+ );+}+const UpdateModal: React.FC<UpdateModalProps> = ({opened,onClose,@@ -118,6 +1017,7 @@ const UpdateModal: React.FC<UpdateModalProps> = ({const [expandedVersions, setExpandedVersions] = useState<Set<number>>(new Set([0]),);+ const [showAllVersions, setShowAllVersions] = useState(false);const { machineType, activeSecurity, licenseType } = machineInfo;useEffect(() => {@@ -150,26 +1050,6 @@ const UpdateModal: React.FC<UpdateModalProps> = ({});};- const getPriorityColor = (priority: string): string => {- switch (priority?.toLowerCase()) {- case "urgent":- return "red";- case "normal":- return "blue";- case "minor":- return "cyan";- case "low":- return "gray";- default:- return "gray";- }- };-- const getPriorityLabel = (priority: string): string => {- const key = priority?.toLowerCase();- return t(`update.priority.${key}`, priority || "Normal");- };-const downloadUrl = updateService.getDownloadUrl(machineInfo);const canClose =!desktopInstall ||@@ -187,32 +1067,18 @@ const UpdateModal: React.FC<UpdateModalProps> = ({desktopInstall.canInstall &&desktopInstall.canInstall.canInstall === false,);- const isStable =- updateSummary.latest_stable_version === updateSummary.latest_version;- const priorityColor = getPriorityColor(updateSummary.max_priority);const handleLater = () => {if (onRemindLater) onRemindLater();onClose();};- const handleExternalLink =- (url: string) => (e: React.MouseEvent<HTMLElement>) => {- e.stopPropagation();- handleExternalLinkClick(url, e);- };-// Sort versions newest first, skip the latest (already shown in header)const sortedVersions = fullUpdateInfo?.new_versions? [...fullUpdateInfo.new_versions].sort((a, b) =>updateService.compareVersions(b.version, a.version),): [];- // Show max 10 initially to keep the modal manageable- const [showAllVersions, setShowAllVersions] = useState(false);- const visibleVersions = showAllVersions- ? sortedVersions- : sortedVersions.slice(0, 10);return (// Composed rather than the plain <Modal>, because only Modal.Content lands@@ -237,705 +1103,42 @@ const UpdateModal: React.FC<UpdateModalProps> = ({aria-label={t("update.modalTitle", "Update Available")}><Modal.Body>- {/* ── Header ─────────────────────────────────────────────────────────── */}- <Box style={{ padding: "24px 28px 16px", flexShrink: 0 }}>- <Group justify="space-between" align="flex-start" wrap="nowrap">- <Group gap="md" align="flex-start" wrap="nowrap">- <Box- style={{- width: 48,- height: 48,- borderRadius: "50%",- background: "var(--mantine-color-blue-filled)",- display: "flex",- alignItems: "center",- justifyContent: "center",- flexShrink: 0,- }}- >- <Icon- name="square-arrow-down"- size={26}- style={{ color: "white" }}- />- </Box>- <Box>- <Text fw={700} size="xl" lh={1.3}>- {t("update.modalTitle", "Update Available")}- </Text>- <Text size="sm" c="dimmed" mt={2}>- {t(- "update.modalSubtitle",- "A new version of Stirling-PDF is ready to install.",- )}- </Text>- </Box>- </Group>- {canClose && (- <ActionIcon- onClick={onClose}- size="lg"- variant="tertiary"- aria-label={t("update.closeModal", "Close update modal")}- >- <Icon name="x" size={20} />- </ActionIcon>- )}- </Group>- </Box>+ <UpdateModalHeader canClose={canClose} onClose={onClose} />- {/* ── Scrollable content ─────────────────────────────────────────────── */}<Box style={{ flex: 1, overflowY: "auto", padding: "0 28px 16px" }}><Stack gap="lg">- {/* Version comparison */}- <Box- style={{- border:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- borderRadius: 12,- padding: "24px 28px",- background:- "color-mix(in srgb, var(--mantine-color-body) 100%, transparent)",- }}- >- <Group justify="center" align="center" wrap="nowrap" gap="xl">- <Stack gap={2} align="center">- <Text size="xs" c="dimmed" tt="uppercase" fw={600} lh={1}>- {t("update.current", "Current Version")}- </Text>- <Text fw={800} fz={32} lh={1.1}>- {currentVersion}- </Text>- </Stack>- <Icon- name="arrow-right"- size={28}- style={{- color: "var(--mantine-color-dimmed)",- flexShrink: 0,- }}- />- <Stack gap={2} align="center">- <Text size="xs" c="dimmed" tt="uppercase" fw={600} lh={1}>- {t("update.latest", "Latest Version")}- </Text>- <Group gap="sm" align="center">- <Text fw={800} fz={32} c="var(--c-accent-text)" lh={1.1}>- {updateSummary.latest_version}- </Text>- {(isStable || updateSummary.latest_stable_version) && (- // `variant="filled" color="green"` produced an acid-green- // pill that was noisy in light mode and oddly washed out- // in dark mode. `light` gives a soft teal-ish chip that- // reads well in both themes.- <Badge- color="teal"- variant="light"- size="sm"- radius="sm"- style={{ marginTop: 4 }}- >- {t("update.stable", "STABLE")}- </Badge>- )}- </Group>- </Stack>- </Group>- </Box>-- {/* Priority badge + recommendation — compact single line. When the- update contains breaking changes we surface a compact inline- chip here rather than a separate full-width orange banner; the- specific per-version detail lives in Version History below. */}- <Group gap="sm" align="center" px={4}>- <Badge- color={priorityColor}- variant="filled"- size="lg"- radius="sm"- >- {getPriorityLabel(updateSummary.max_priority)}- </Badge>- {updateSummary.any_breaking && (- <Badge- color="orange"- variant="light"- size="lg"- radius="sm"- leftSection={<Icon name="triangle-alert" size={14} />}- >- {t("update.breaking", "Breaking")}- </Badge>- )}- <Text size="sm" c="dimmed" style={{ flex: 1 }}>- {updateSummary.recommended_action ||- t(- "update.defaultRecommendation",- "This update contains important fixes and improvements.",- )}- </Text>- </Group>-- {/* Admin permissions required — shown when can_install_updates- reported that msiexec would need UAC elevation this user- can't satisfy. Placed right after the priority row so it's- the first thing users see when they open the modal and the- Install Now button (below) is disabled as a result. */}- {desktopInstall && installBlocked && (- <Alert- variant="light"- color="orange"- radius="md"- icon={<Icon name="triangle-alert" size={18} />}- title={t(- "desktopUpdate.blocked.title",- "Administrator permissions required",- )}- >- <Text size="sm">- {t(- "desktopUpdate.blocked.message",- "Stirling-PDF does not have permission to update itself on this machine.",- )}{" "}- <Anchor- href={WINDOWS_INSTALL_DOCS_URL}- target="_blank"- rel="noopener noreferrer"- onClick={handleExternalLink(WINDOWS_INSTALL_DOCS_URL)}- // Sits inside a sentence, so the accent alone does not- // separate it from the surrounding copy.- underline="always"- >- {t(- "desktopUpdate.blocked.docsLink",- "View installation documentation",- )}- </Anchor>- </Text>- </Alert>- )}-- {/* What's New card */}- <Box- style={{- background:- "color-mix(in srgb, var(--mantine-color-blue-filled) 8%, transparent)",- borderRadius: 12,- padding: "16px 20px",- border:- "1px solid color-mix(in srgb, var(--mantine-color-blue-filled) 15%, transparent)",- }}- >- <Group justify="space-between" align="center">- <Group gap={8}>- <Icon- name="star"- size={18}- filled- style={{ color: "var(--c-accent-text)" }}- />- <Text fw={600} size="sm">- {t("update.whatsNewIn", "What's new in")}{" "}- {updateSummary.latest_version}- </Text>- </Group>- <Group gap="sm">- <Text- size="sm"- component="a"- href={`https://github.com/Stirling-Tools/Stirling-PDF/releases/tag/v${updateSummary.latest_version}`}- target="_blank"- onClick={handleExternalLink(- `https://github.com/Stirling-Tools/Stirling-PDF/releases/tag/v${updateSummary.latest_version}`,- )}- c="var(--c-accent-text)"- style={{- textDecoration: "none",- display: "inline-flex",- alignItems: "center",- gap: 4,- }}- >- {t("update.releaseNotes", "Release Notes")}{" "}- <Icon name="external-link" size={14} />- </Text>- <Text- size="sm"- component="a"- href="https://github.com/Stirling-Tools/Stirling-PDF/releases"- target="_blank"- onClick={handleExternalLink(- "https://github.com/Stirling-Tools/Stirling-PDF/releases",- )}- c="dimmed"- style={{- textDecoration: "none",- display: "inline-flex",- alignItems: "center",- gap: 4,- }}- >- {t("update.allReleases", "All Releases")}{" "}- <Icon name="external-link" size={14} />- </Text>- </Group>- </Group>- </Box>-- {/* Migration guides */}- {updateSummary.migration_guides &&- updateSummary.migration_guides.length > 0 && (- <Box>- <Text fw={600} size="sm" mb={4}>- {t("update.migrationGuides", "Migration Guides")}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t(- "update.migrationGuidesDesc",- "Review important changes before updating.",- )}- </Text>- <Stack gap={0}>- {updateSummary.migration_guides.map((guide, idx) => (- <Box- key={idx}- style={{- borderTop:- idx === 0- ? "1px solid var(--c-border-subtle, var(--mantine-color-default-border))"- : undefined,- borderBottom:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- padding: "10px 12px",- }}- >- <Group- justify="space-between"- align="center"- wrap="nowrap"- >- <Group gap="sm" style={{ flex: 1 }}>- <Box- style={{- width: 8,- height: 8,- borderRadius: "50%",- background:- "var(--mantine-color-green-filled)",- flexShrink: 0,- }}- />- <Text fw={600} size="sm">- {guide.version}- </Text>- <Text size="xs" c="dimmed" lineClamp={1}>- {guide.notes}- </Text>- </Group>- <Button- as="a"- href={guide.url}- target="_blank"- onClick={handleExternalLink(guide.url)}- variant="secondary"- size="sm"- rightSection={- <Icon name="external-link" size={12} />- }- >- {t("update.viewGuide", "View Guide")}- </Button>- </Group>- </Box>- ))}- </Stack>- </Box>- )}-- {/* ── Version history ─────────────────────────────────────────────── */}+ <VersionComparison+ currentVersion={currentVersion}+ updateSummary={updateSummary}+ />+ <UpdatePriority updateSummary={updateSummary} />+ {/* Right after the priority row so it's the first thing users+ see when they open the modal and the Install Now button+ (below) is disabled as a result. */}+ <InstallBlockedAlert show={installBlocked} />+ <WhatsNewCard version={updateSummary.latest_version} />+ <MigrationGuides guides={updateSummary.migration_guides} /><Divider />- {loading ? (- <Center py="lg">- <Group gap="sm">- <Loader size="sm" />- <Text size="sm" c="dimmed">- {t(- "update.loadingDetailedInfo",- "Loading version details...",- )}- </Text>- </Group>- </Center>- ) : visibleVersions.length > 0 ? (- <Box>- <Group justify="space-between" align="center" mb="sm">- <Text fw={600} size="sm">- {t("update.versionHistory", "Version History")}- </Text>- <Text size="xs" c="dimmed">- {sortedVersions.length}{" "}- {sortedVersions.length === 1 ? "version" : "versions"}- </Text>- </Group>- <Stack gap={0}>- {visibleVersions.map((version, index) => {- const isExpanded = expandedVersions.has(index);- return (- <Box- key={index}- style={{- borderTop:- index === 0- ? "1px solid var(--c-border-subtle, var(--mantine-color-default-border))"- : undefined,- borderBottom:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- }}- >- <Group- justify="space-between"- align="center"- p="xs"- px="sm"- style={{ cursor: "pointer" }}- onClick={() => toggleVersion(index)}- >- <Group gap="sm" style={{ flex: 1 }}>- <Text fw={700} size="sm" style={{ minWidth: 50 }}>- {version.version}- </Text>- <Badge- color={getPriorityColor(version.priority)}- size="xs"- variant="light"- >- {getPriorityLabel(version.priority)}- </Badge>- {version.compatibility.breaking_changes && (- <Badge color="orange" size="xs" variant="light">- {t("update.breaking", "Breaking")}- </Badge>- )}- {!isExpanded && version.announcement?.title && (- <Text- size="xs"- c="dimmed"- lineClamp={1}- style={{ flex: 1 }}- >- {version.announcement.title}- </Text>- )}- </Group>- <Group gap={4}>- <Button- as="a"- href={`https://github.com/Stirling-Tools/Stirling-PDF/releases/tag/v${version.version}`}- target="_blank"- variant="tertiary"- size="sm"- onClick={handleExternalLink(- `https://github.com/Stirling-Tools/Stirling-PDF/releases/tag/v${version.version}`,- )}- rightSection={- <Icon name="external-link" size={11} />- }- >- {t("update.notes", "Notes")}- </Button>- {isExpanded ? (- <Icon- name="chevron-up"- size={18}- style={{- color: "var(--mantine-color-dimmed)",- }}- />- ) : (- <Icon- name="chevron-down"- size={18}- style={{- color: "var(--mantine-color-dimmed)",- }}- />- )}- </Group>- </Group>- <Collapse in={isExpanded}>- <Box- px="sm"- pb="sm"- style={{- borderTop:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- }}- >- <Stack gap="sm" mt="sm">- {version.announcement?.message && (- <Text- size="sm"- c="dimmed"- style={{ lineHeight: 1.6 }}- >- {version.announcement.message}- </Text>- )}- {version.compatibility.breaking_changes && (- <Alert- variant="light"- color="orange"- radius="sm"- icon={- <Icon name="triangle-alert" size={16} />- }- title={t(- "update.breakingChanges",- "Breaking Changes",- )}- >- <Text size="sm">- {version.compatibility- .breaking_description ||- t(- "update.breakingChangesDefault",- "This version contains breaking changes.",- )}- </Text>- {version.compatibility- .migration_guide_url && (- <Button- as="a"- href={- version.compatibility- .migration_guide_url- }- target="_blank"- onClick={handleExternalLink(- version.compatibility- .migration_guide_url ?? "",- )}- variant="secondary"- accent="warning"- size="sm"- style={{- marginTop:- "var(--mantine-spacing-xs)",- }}- rightSection={- <Icon- name="external-link"- size={14}- />- }- >- {t(- "update.migrationGuide",- "Migration Guide",- )}- </Button>- )}- </Alert>- )}- </Stack>- </Box>- </Collapse>- </Box>- );- })}- </Stack>- {sortedVersions.length > 10 && (- <Center mt="sm">- <Button- variant="tertiary"- size="sm"- onClick={() => setShowAllVersions(!showAllVersions)}- >- {showAllVersions- ? t("update.showLess", "Show fewer versions")- : t("update.showMore", {- defaultValue: "Show all {{count}} versions",- count: sortedVersions.length,- })}- </Button>- </Center>- )}- </Box>- ) : null}-- {/* Desktop install progress */}- {desktopInstall && desktopInstall.state !== "idle" && (- <Box- style={{- border:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- borderRadius: 12,- padding: "16px 20px",- }}- >- {(desktopInstall.state === "downloading" ||- desktopInstall.state === "installing") && (- <Stack gap="sm">- <Group justify="space-between" align="center">- <Text size="sm" fw={600}>- {desktopInstall.state === "downloading"- ? t(- "desktopUpdate.downloading",- "Downloading update...",- )- : t(- "desktopUpdate.installing",- "Installing update...",- )}- </Text>- {desktopInstall.progress &&- desktopInstall.progress.total !== null && (- <Text size="xs" c="dimmed">- {formatBytes(desktopInstall.progress.downloaded)}{" "}- / {formatBytes(desktopInstall.progress.total)}- </Text>- )}- </Group>- <Progress- value={- desktopInstall.state === "installing"- ? 100- : (desktopInstall.progress?.percent ?? 0)- }- size="lg"- animated- radius="xl"- />- {desktopInstall.state === "installing" && (- <Alert variant="light" color="blue" radius="sm" py="xs">- <Text size="xs">- {t(- "desktopUpdate.installingWarning",- "The app will close automatically to complete the installation.",- )}- </Text>- </Alert>- )}- </Stack>- )}- {desktopInstall.state === "ready-to-restart" && (- <Alert- icon={<Icon name="circle-check" />}- color="green"- variant="light"- radius="md"- title={t("desktopUpdate.readyToRestart", "Update Ready")}- >- {t(- "desktopUpdate.restartMessage",- "The update has been installed. Restart the app to finish.",- )}- </Alert>- )}- {desktopInstall.state === "error" && (- <Alert- icon={<Icon name="circle-alert" />}- color="red"- variant="light"- radius="md"- title={t("desktopUpdate.updateFailed", "Update Failed")}- >- {desktopInstall.errorMessage ??- t(- "desktopUpdate.updateFailedMessage",- "Failed to download or install the update.",- )}- </Alert>- )}- </Box>- )}+ <VersionHistory+ loading={loading}+ versions={sortedVersions}+ expandedVersions={expandedVersions}+ onToggleVersion={toggleVersion}+ showAll={showAllVersions}+ onToggleShowAll={() => setShowAllVersions(!showAllVersions)}+ />+ <DesktopInstallStatus desktopInstall={desktopInstall} /></Stack></Box>- {/* ── Sticky footer ──────────────────────────────────────────────────── */}- <Box- style={{- borderTop:- "1px solid var(--c-border-subtle, var(--mantine-color-default-border))",- padding: "16px 28px",- flexShrink: 0,- }}- >- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={handleLater}- disabled={!canClose}- size="md"- >- {t("update.later", "Later")}- </Button>- {desktopInstall ? (- desktopInstall.state === "ready-to-restart" ? (- <Button- size="md"- leftSection={<Icon name="rotate-ccw" size={20} />}- onClick={() => void desktopInstall.actions.restartApp()}- >- {t("desktopUpdate.restartNow", "Restart Now")}- </Button>- ) : desktopInstall.state === "idle" ||- desktopInstall.state === "error" ? (- <>- {/* When install is blocked (non-admin) or the tauri updater- failed, the user still needs a way forward — show a- "Download Latest" link to the GitHub release page as a- fallback alongside the disabled Install Now button. */}- {(installBlocked || desktopInstall.state === "error") &&- downloadUrl && (- <Button- as="a"- href={downloadUrl}- target="_blank"- onClick={handleExternalLink(downloadUrl)}- variant="secondary"- size="md"- leftSection={<Icon name="download" size={16} />}- >- {t("update.downloadLatest", "Download Latest")}- </Button>- )}- <Button- size="md"- leftSection={<Icon name="download" size={20} />}- onClick={() => void desktopInstall.actions.startInstall()}- disabled={installBlocked}- >- <Box>- <Text size="sm" fw={700} lh={1.2}>- {t("desktopUpdate.installNow", "Install Now")}- </Text>- <Text size="xs" lh={1.2} style={{ opacity: 0.7 }}>- {formatSize(downloadSizeBytes)}- </Text>- </Box>- </Button>- </>- ) : null- ) : (- // Tauri updater not available at all — only show the external- // download link. This is the fallback when latest.json is- // unreachable, the pubkey is wrong, signatures don't match, etc.- downloadUrl && (- <Button- as="a"- href={downloadUrl}- target="_blank"- onClick={handleExternalLink(downloadUrl)}- size="md"- leftSection={<Icon name="download" size={20} />}- >- {t("update.downloadLatest", "Download Latest")}- </Button>- )- )}- </Group>- </Box>+ <UpdateModalFooter+ canClose={canClose}+ onLater={handleLater}+ desktopInstall={desktopInstall}+ installBlocked={installBlocked}+ downloadUrl={downloadUrl}+ downloadSizeBytes={downloadSizeBytes}+ /></Modal.Body></Modal.Content></Modal.Root>diff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsxindex d0a80e5111..9ba984521c 100644--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx@@ -1,4 +1,11 @@-import { useMemo, useState, useCallback, useEffect, useRef } from "react";+import {+ useMemo,+ useState,+ useCallback,+ useEffect,+ useRef,+ type ReactNode,+} from "react";import {Box,Text,@@ -285,6 +292,748 @@ function AnnotationTypeIcon({ ann }: { ann: PdfAnnotationObject }) {);}+function MoreActionsMenu({ children }: { children: ReactNode }) {+ const { t } = useTranslation();+ return (+ <Menu position="bottom-end" withArrow>+ <Menu.Target>+ <Tooltip label={t("viewer.comments.moreActions", "More actions")}>+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ size="sm"+ aria-label={t("viewer.comments.moreActions", "More actions")}+ >+ <Icon name="ellipsis" size={20} />+ </ActionIcon>+ </Tooltip>+ </Menu.Target>+ <Menu.Dropdown>{children}</Menu.Dropdown>+ </Menu>+ );+}++interface CommentsHeaderActionsProps {+ readerMode: boolean;+ onAdd: () => void;+ onClearAll: () => void;+}++function CommentsHeaderActions({+ readerMode,+ onAdd,+ onClearAll,+}: CommentsHeaderActionsProps) {+ const { t } = useTranslation();+ return (+ <Group gap={2} wrap="nowrap" style={{ flexShrink: 0 }}>+ {/* Placing a comment arms the annotate tool, which only exists in the+ editor: offering it here would take the reader there mid-sentence.+ Reading shows the comments that are there and leaves it at that. */}+ {!readerMode && (+ <Tooltip label={t("viewer.comments.addComment", "Add comment")}>+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ size="sm"+ aria-label={t("viewer.comments.addComment", "Add comment")}+ onClick={onAdd}+ >+ <Icon name="plus" size="1.25rem" />+ </ActionIcon>+ </Tooltip>+ )}+ <MoreActionsMenu>+ <Menu.Item+ leftSection={<Icon name="trash" size={18} />}+ color="red"+ onClick={onClearAll}+ >+ {t("viewer.comments.clearAll", "Clear all comments")}+ </Menu.Item>+ </MoreActionsMenu>+ </Group>+ );+}++interface AddCommentButtonProps {+ isPlacing: boolean;+ readerMode: boolean;+ onAdd: () => void;+ onCancel: () => void;+ /** Full width and left-aligned, for the top of the comment list. */+ block?: boolean;+}++function AddCommentButton({+ isPlacing,+ readerMode,+ onAdd,+ onCancel,+ block = false,+}: AddCommentButtonProps) {+ const { t } = useTranslation();+ const iconSize = block ? "0.9rem" : "1rem";+ const layout = block ? ({ fullWidth: true, justify: "start" } as const) : {};++ if (isPlacing) {+ return (+ <Button+ variant="tertiary"+ accent="warning"+ size="sm"+ {...layout}+ onClick={onCancel}+ leftSection={<Icon name="pointer" size={iconSize} />}+ style={block ? { paddingInline: 6 } : undefined}+ >+ {t("viewer.comments.placingHint", "Click a page to place… (cancel)")}+ </Button>+ );+ }+ if (readerMode) return null;+ return (+ <Button+ variant="tertiary"+ size="sm"+ {...layout}+ onClick={onAdd}+ leftSection={<Icon name="plus" size={iconSize} />}+ style={+ block+ ? { paddingInline: 6, marginBottom: "var(--space-xs)" }+ : undefined+ }+ >+ {t("viewer.comments.addComment", "Add comment")}+ </Button>+ );+}++function CommentsEmptyState({ children }: { children: ReactNode }) {+ const { t } = useTranslation();+ return (+ <Stack align="center" gap="sm" py="lg">+ <Icon+ name="message-square"+ size="2rem"+ style={{ color: "var(--mantine-color-dimmed)" }}+ />+ <Text size="sm" c="dimmed" ta="center">+ {t(+ "viewer.comments.hint",+ "Place comments with the Comment, Insert Text, or Replace Text tools. They will appear here by page.",+ )}+ </Text>+ {children}+ </Stack>+ );+}++interface CommentPageGroupProps {+ pageIndex: number;+ count: number;+ children: ReactNode;+}++function CommentPageGroup({+ pageIndex,+ count,+ children,+}: CommentPageGroupProps) {+ const { t } = useTranslation();+ return (+ <Box mb="md">+ <Text size="sm" fw={700} mb={2}>+ {t("viewer.comments.pageLabel", "Page {{page}}", {+ page: pageIndex + 1,+ })}+ </Text>+ <Text size="xs" c="dimmed" mb="sm">+ {t("viewer.comments.nComments", "{{count}} comments", { count })}+ </Text>+ <Box+ mb="xs"+ style={{ borderBottom: "1px solid var(--c-border-subtle)" }}+ />+ <Stack gap="sm">{children}</Stack>+ </Box>+ );+}++interface CommentCardHeaderProps {+ ann: PdfAnnotationObject;+ authorName: string;+ typeLabel: string;+ timestamp: string;+ onLocate: () => void;+ onEdit: () => void;+ onDelete: () => void;+}++function CommentCardHeader({+ ann,+ authorName,+ typeLabel,+ timestamp,+ onLocate,+ onEdit,+ onDelete,+}: CommentCardHeaderProps) {+ const { t } = useTranslation();+ return (+ <Group+ wrap="nowrap"+ gap="xs"+ justify="space-between"+ align="flex-start"+ mb="xs"+ >+ <Group wrap="nowrap" gap="xs" style={{ minWidth: 0, flex: 1 }}>+ <AnnotationTypeIcon ann={ann} />+ <Box style={{ minWidth: 0 }}>+ <Text size="sm" fw={600}>+ {authorName}+ </Text>+ <Text size="xs" c="dimmed">+ {typeLabel}+ {timestamp ? ` · ${timestamp}` : ""}+ </Text>+ </Box>+ </Group>+ <Group gap={2} wrap="nowrap" style={{ flexShrink: 0 }}>+ <Tooltip+ label={t("viewer.comments.locateAnnotation", "Locate in document")}+ >+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ size="sm"+ aria-label={t(+ "viewer.comments.locateAnnotation",+ "Locate in document",+ )}+ onClick={onLocate}+ >+ <Icon name="eye" size={16} />+ </ActionIcon>+ </Tooltip>+ <MoreActionsMenu>+ <Menu.Item+ leftSection={<Icon name="pencil" size={18} />}+ onClick={onEdit}+ >+ {t("annotation.editText", "Edit")}+ </Menu.Item>+ <Menu.Item+ leftSection={<Icon name="trash" size={18} />}+ color="red"+ onClick={onDelete}+ >+ {t("annotation.delete", "Delete")}+ </Menu.Item>+ </MoreActionsMenu>+ </Group>+ </Group>+ );+}++interface CommentComposerProps {+ value: string;+ onChange: (value: string) => void;+ onSubmit: () => void;+}++function CommentComposer({ value, onChange, onSubmit }: CommentComposerProps) {+ const { t } = useTranslation();+ const canSubmit = value.trim().length > 0;+ return (+ <Group gap="xs" wrap="nowrap" align="flex-end">+ <Textarea+ placeholder={t(+ "viewer.comments.addCommentPlaceholder",+ "Add comment...",+ )}+ size="sm"+ autosize+ minRows={1}+ maxRows={6}+ value={value}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && canSubmit) {+ e.preventDefault();+ onSubmit();+ }+ }}+ onChange={(e) => onChange((e?.currentTarget ?? e?.target)?.value ?? "")}+ style={{ flex: 1, minWidth: 0 }}+ styles={{ input: { borderColor: "var(--mantine-color-blue-3)" } }}+ autoFocus+ />+ <Tooltip label={t("viewer.comments.addComment", "Add comment")}>+ <ActionIcon+ variant="primary"+ size="md"+ aria-label={t("viewer.comments.addComment", "Add comment")}+ onClick={onSubmit}+ disabled={!canSubmit}+ style={{ height: "36px", width: "36px", flexShrink: 0 }}+ >+ <Icon name="check" size={18} />+ </ActionIcon>+ </Tooltip>+ </Group>+ );+}++interface ReplyEditorProps {+ value: string;+ onChange: (value: string) => void;+ onSave: () => void;+}++function ReplyEditor({ value, onChange, onSave }: ReplyEditorProps) {+ const { t } = useTranslation();+ return (+ <>+ <Textarea+ minRows={2}+ autosize+ value={value}+ onChange={(e) => onChange((e?.currentTarget ?? e?.target)?.value ?? "")}+ styles={{ root: { width: "100%" } }}+ mb="xs"+ />+ <Group gap={4} wrap="nowrap" justify="flex-end">+ <Tooltip label={t("viewer.comments.saveReply", "Save reply")}>+ <ActionIcon+ variant="primary"+ size="sm"+ aria-label={t("viewer.comments.saveReply", "Save reply")}+ onClick={onSave}+ disabled={!value.trim()}+ >+ <Icon name="check" size={18} />+ </ActionIcon>+ </Tooltip>+ </Group>+ </>+ );+}++interface CommentReplyProps {+ reply: SidebarAnnotationEntry["replies"][number];+ displayName: string;+ /** The text being edited, or null when the reply is not being edited. */+ editDraft: string | null;+ onStartEditing: () => void;+ onEditChange: (value: string) => void;+ onSave: (text: string) => void;+}++function CommentReply({+ reply,+ displayName,+ editDraft,+ onStartEditing,+ onEditChange,+ onSave,+}: CommentReplyProps) {+ const { t } = useTranslation();+ const rObj = reply.object;+ const author = getAuthorName(rObj, displayName);+ const timestamp = formatCommentDate(rObj);+ const canEdit = isReplyAuthoredByCurrentUser(rObj, displayName);++ return (+ <Box+ pl="xs"+ style={{ borderLeft: "2px solid var(--mantine-color-blue-3)" }}+ >+ <Box style={{ minWidth: 0 }}>+ <Group+ wrap="nowrap"+ justify="space-between"+ align="flex-start"+ gap={4}+ mb={2}+ >+ <Text size="sm" fw={600}>+ {author}+ </Text>+ <Group wrap="nowrap" gap="xs" align="center">+ {canEdit && editDraft === null ? (+ <Button+ variant="tertiary"+ hover={false}+ type="button"+ onClick={onStartEditing}+ >+ <Text size="xs" c="var(--c-accent-text)">+ {t("annotation.editText", "Edit")}+ </Text>+ </Button>+ ) : null}+ {timestamp ? (+ <Text size="xs" c="dimmed">+ {timestamp}+ </Text>+ ) : null}+ </Group>+ </Group>+ {editDraft !== null ? (+ <ReplyEditor+ value={editDraft}+ onChange={onEditChange}+ onSave={() => onSave(editDraft)}+ />+ ) : (+ <Text size="sm" style={{ whiteSpace: "pre-wrap" }}>+ {rObj?.contents ?? ""}+ </Text>+ )}+ </Box>+ </Box>+ );+}++interface ReplyComposerProps {+ value: string;+ onChange: (value: string) => void;+ onSubmit: () => void;+}++function ReplyComposer({ value, onChange, onSubmit }: ReplyComposerProps) {+ const { t } = useTranslation();+ const canSubmit = value.trim().length > 0;+ return (+ <Group gap="xs" wrap="nowrap" align="center">+ <TextInput+ placeholder={t("viewer.comments.addReplyPlaceholder", "Add reply...")}+ size="sm"+ value={value}+ onKeyDown={(e) => {+ if (e.key === "Enter" && canSubmit) {+ e.preventDefault();+ onSubmit();+ }+ }}+ onChange={(e) => onChange((e?.currentTarget ?? e?.target)?.value ?? "")}+ style={{ flex: 1, minWidth: 0 }}+ styles={{+ input: {+ borderColor: "var(--mantine-color-blue-3)",+ height: "36px",+ minHeight: "36px",+ },+ }}+ />+ <Tooltip label={t("viewer.comments.addComment", "Add comment")}>+ <ActionIcon+ variant="primary"+ size="md"+ aria-label={t("viewer.comments.addComment", "Add comment")}+ onClick={onSubmit}+ disabled={!canSubmit}+ style={{ height: "36px", width: "36px", flexShrink: 0 }}+ >+ <Icon name="check" size={20} />+ </ActionIcon>+ </Tooltip>+ </Group>+ );+}++/** A reply being edited. Only one reply in the sidebar is edited at a time. */+interface EditingReply {+ /** `${pageIndex}_${annotationId}` of the card the reply belongs to. */+ cardKey: string;+ replyId: string;+ draft: string;+}++interface CommentActions {+ locate: (pageIndex: number, ann: PdfAnnotationObject) => void;+ requestDelete: (+ pageIndex: number,+ annotationId: string,+ ann: PdfAnnotationObject,+ ) => void;+ startEditing: (pageIndex: number, annotationId: string) => void;+ changeDraft: (pageIndex: number, annotationId: string, value: string) => void;+ submit: (pageIndex: number, annotationId: string, value: string) => void;+ changeReplyDraft: (+ pageIndex: number,+ parentId: string,+ value: string,+ ) => void;+ sendReply: (+ pageIndex: number,+ parentId: string,+ parentRect: Rect | undefined,+ ) => void;+ startEditingReply: (+ pageIndex: number,+ parentId: string,+ replyId: string,+ contents: string,+ ) => void;+ changeReplyEdit: (value: string) => void;+ saveReplyEdit: (pageIndex: number, replyId: string, value: string) => void;+}++interface CommentRepliesProps {+ pageIndex: number;+ parentId: string;+ replies: SidebarAnnotationEntry["replies"];+ displayName: string;+ editingReply: EditingReply | null;+ actions: CommentActions;+}++function CommentReplies({+ pageIndex,+ parentId,+ replies,+ displayName,+ editingReply,+ actions,+}: CommentRepliesProps) {+ if (replies.length === 0) return null;+ return (+ <Stack gap="sm" mb="sm">+ {replies+ .filter((reply) => reply?.object?.id)+ .map((reply) => (+ <CommentReply+ key={reply.object.id}+ reply={reply}+ displayName={displayName}+ editDraft={+ editingReply?.replyId === reply.object.id+ ? editingReply.draft+ : null+ }+ onStartEditing={() =>+ actions.startEditingReply(+ pageIndex,+ parentId,+ reply.object.id,+ String(reply.object.contents ?? ""),+ )+ }+ onEditChange={actions.changeReplyEdit}+ onSave={(value) =>+ actions.saveReplyEdit(pageIndex, reply.object.id, value)+ }+ />+ ))}+ </Stack>+ );+}++interface CommentThreadProps {+ pageIndex: number;+ entry: SidebarAnnotationEntry;+ content: string;+ displayName: string;+ replyDraft: string;+ editingReply: EditingReply | null;+ actions: CommentActions;+}++function CommentThread({+ pageIndex,+ entry,+ content,+ displayName,+ replyDraft,+ editingReply,+ actions,+}: CommentThreadProps) {+ const ann = entry.annotation.object;+ return (+ <>+ <Text size="sm" mb="sm" style={{ whiteSpace: "pre-wrap" }}>+ {content}+ </Text>+ <CommentReplies+ pageIndex={pageIndex}+ parentId={ann.id}+ replies={entry.replies}+ displayName={displayName}+ editingReply={editingReply}+ actions={actions}+ />+ <ReplyComposer+ value={replyDraft}+ onChange={(value) => actions.changeReplyDraft(pageIndex, ann.id, value)}+ onSubmit={() => actions.sendReply(pageIndex, ann.id, ann.rect)}+ />+ </>+ );+}++interface CommentCardProps {+ pageIndex: number;+ entry: SidebarAnnotationEntry;+ selected: boolean;+ displayName: string;+ /** Text typed but not yet sent; undefined shows the posted content. */+ draft: string | undefined;+ isEditing: boolean;+ replyDraft: string;+ /** Set only when the reply being edited belongs to this card. */+ editingReply: EditingReply | null;+ actions: CommentActions;+}++function CommentCard({+ pageIndex,+ entry,+ selected,+ displayName,+ draft,+ isEditing,+ replyDraft,+ editingReply,+ actions,+}: CommentCardProps) {+ const { t } = useTranslation();+ const ann = entry.annotation.object;+ const id = ann.id;+ const displayContent = getCommentDisplayContent(entry);+ const text = draft !== undefined ? draft : displayContent;+ /** Only treat as "comment posted" when annotation actually has content (user clicked Send), not on every keystroke. */+ const hasMainContent = displayContent.trim().length > 0;++ return (+ <Box+ data-comment-card={`${pageIndex}_${id}`}+ p="sm"+ style={{+ border: selected+ ? "1px solid var(--mantine-color-blue-3)"+ : "1px solid var(--c-border-subtle)",+ borderRadius: 8,+ backgroundColor: "var(--c-surface-raised)",+ }}+ >+ <CommentCardHeader+ ann={ann}+ authorName={getAuthorName(ann, displayName)}+ typeLabel={getAnnotationTypeLabel(ann, t)}+ timestamp={formatCommentDate(ann)}+ onLocate={() => actions.locate(pageIndex, ann)}+ onEdit={() => actions.startEditing(pageIndex, id)}+ onDelete={() => actions.requestDelete(pageIndex, id, ann)}+ />++ {!hasMainContent || isEditing ? (+ <CommentComposer+ value={text}+ onChange={(value) => actions.changeDraft(pageIndex, id, value)}+ onSubmit={() => actions.submit(pageIndex, id, text)}+ />+ ) : (+ <CommentThread+ pageIndex={pageIndex}+ entry={entry}+ content={displayContent}+ displayName={displayName}+ replyDraft={replyDraft}+ editingReply={editingReply}+ actions={actions}+ />+ )}+ </Box>+ );+}++interface DeleteLinkedCommentModalProps {+ opened: boolean;+ onClose: () => void;+ onRemoveComment: () => void;+ onDeleteAnnotation: () => void;+}++function DeleteLinkedCommentModal({+ opened,+ onClose,+ onRemoveComment,+ onDeleteAnnotation,+}: DeleteLinkedCommentModalProps) {+ const { t } = useTranslation();+ return (+ <Modal+ opened={opened}+ onClose={onClose}+ title={t(+ "viewer.comments.deleteTitle",+ "Remove annotation from comments?",+ )}+ centered+ size="sm"+ >+ <Text size="sm" c="dimmed" mb="lg">+ {t(+ "viewer.comments.deleteDescription",+ "This annotation has a comment attached. You can remove just the comment from the sidebar while keeping the annotation, or delete everything.",+ )}+ </Text>+ <Group justify="flex-end" gap="sm">+ <Button variant="secondary" onClick={onRemoveComment}>+ {t("viewer.comments.removeCommentOnly", "Remove comment only")}+ </Button>+ <Button accent="danger" onClick={onDeleteAnnotation}>+ {t(+ "viewer.comments.deleteAnnotationAndComment",+ "Delete annotation & comment",+ )}+ </Button>+ </Group>+ </Modal>+ );+}++interface ClearAllCommentsModalProps {+ opened: boolean;+ onClose: () => void;+ onConfirm: () => void;+}++function ClearAllCommentsModal({+ opened,+ onClose,+ onConfirm,+}: ClearAllCommentsModalProps) {+ const { t } = useTranslation();+ return (+ <Modal+ opened={opened}+ onClose={onClose}+ title={t("viewer.comments.clearAllTitle", "Clear all comments?")}+ centered+ size="sm"+ >+ <Text size="sm" c="dimmed" mb="lg">+ {t(+ "viewer.comments.clearAllDescription",+ "This removes comments and replies from the sidebar while keeping any attached annotations in the document.",+ )}+ </Text>+ <Group justify="flex-end" gap="sm">+ <Button variant="secondary" onClick={onClose}>+ {t("viewer.comments.cancelClearAll", "Cancel")}+ </Button>+ <Button accent="danger" onClick={onConfirm}>+ {t("viewer.comments.clearAll", "Clear all comments")}+ </Button>+ </Group>+ </Modal>+ );+}+export function CommentsSidebar({documentId,visible,@@ -313,14 +1062,9 @@ export function CommentsSidebar({{},);const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({});- /** Draft text while editing an existing reply (`${pageIndex}_${parentId}_${replyId}`). */- const [replyEditDrafts, setReplyEditDrafts] = useState<- Record<string, string>- >({});/** When set, this card's main comment is in edit mode (show textarea for main comment). */const [editingMainKey, setEditingMainKey] = useState<string | null>(null);- /** Which reply is in edit mode (same key shape as replyEditDrafts). */- const [editingReplyKey, setEditingReplyKey] = useState<string | null>(null);+ const [editingReply, setEditingReply] = useState<EditingReply | null>(null);// React to request to focus or highlight a comment card (e.g. from "Add comment" / "View comment" in selection menu)useEffect(() => {@@ -510,6 +1254,17 @@ export function CommentsSidebar({[provides],);+ const handleDraftChange = useCallback(+ (pageIndex: number, annotationId: string, value: string) => {+ const key = `${pageIndex}_${annotationId}`;+ setDraftContents((prev) => ({ ...prev, [key]: value }));+ if (editingMainKey === key) {+ handleContentsChange(pageIndex, annotationId, value);+ }+ },+ [editingMainKey, handleContentsChange],+ );+const [deleteModal, setDeleteModal] = useState<{pageIndex: number;id: string;@@ -606,9 +1361,8 @@ export function CommentsSidebar({setDraftContents({});setReplyDrafts({});- setReplyEditDrafts({});setEditingMainKey(null);- setEditingReplyKey(null);+ setEditingReply(null);setDeleteModal(null);setClearAllModalOpen(false);navActions?.setHasUnsavedChanges(true);@@ -658,7 +1412,7 @@ export function CommentsSidebar({);const handleSaveReplyEdit = useCallback(- (editKey: string, pageIndex: number, replyId: string, value: string) => {+ (pageIndex: number, replyId: string, value: string) => {const trimmed = value.trim();if (!trimmed || !provides?.updateAnnotation) return;provides.updateAnnotation(pageIndex, replyId, {@@ -666,12 +1420,7 @@ export function CommentsSidebar({author: displayName,});navActions?.setHasUnsavedChanges(true);- setReplyEditDrafts((prev) => {- const next = { ...prev };- delete next[editKey];- return next;- });- setEditingReplyKey(null);+ setEditingReply(null);},[provides, displayName, navActions],);@@ -707,50 +1456,32 @@ export function CommentsSidebar({if (!visible) return null;- const commentsHeaderActions =- totalCount > 0 ? (- <Group gap={2} wrap="nowrap" style={{ flexShrink: 0 }}>- {/* Placing a comment arms the annotate tool, which only exists in the- editor: offering it here would take the reader there mid-sentence.- Reading shows the comments that are there and leaves it at that. */}- {!readerMode && (- <Tooltip label={t("viewer.comments.addComment", "Add comment")}>- <ActionIcon- variant="tertiary"- accent="neutral"- size="sm"- aria-label={t("viewer.comments.addComment", "Add comment")}- onClick={handleAddComment}- >- <Icon name="plus" size="1.25rem" />- </ActionIcon>- </Tooltip>- )}- <Menu position="bottom-end" withArrow>- <Menu.Target>- <Tooltip label={t("viewer.comments.moreActions", "More actions")}>- <ActionIcon- variant="tertiary"- accent="neutral"- size="sm"- aria-label={t("viewer.comments.moreActions", "More actions")}- >- <Icon name="ellipsis" size={20} />- </ActionIcon>- </Tooltip>- </Menu.Target>- <Menu.Dropdown>- <Menu.Item- leftSection={<Icon name="trash" size={18} />}- color="red"- onClick={() => setClearAllModalOpen(true)}- >- {t("viewer.comments.clearAll", "Clear all comments")}- </Menu.Item>- </Menu.Dropdown>- </Menu>- </Group>- ) : null;+ const commentActions: CommentActions = {+ locate: handleLocateAnnotation,+ requestDelete: handleDeleteClick,+ startEditing: (pageIndex, annotationId) =>+ setEditingMainKey(`${pageIndex}_${annotationId}`),+ changeDraft: handleDraftChange,+ submit: (pageIndex, annotationId, value) => {+ handleSendMainComment(pageIndex, annotationId, value);+ setEditingMainKey(null);+ },+ changeReplyDraft: (pageIndex, parentId, value) =>+ setReplyDrafts((prev) => ({+ ...prev,+ [`${pageIndex}_${parentId}_reply`]: value,+ })),+ sendReply: handleSendReply,+ startEditingReply: (pageIndex, parentId, replyId, contents) =>+ setEditingReply({+ cardKey: `${pageIndex}_${parentId}`,+ replyId,+ draft: contents,+ }),+ changeReplyEdit: (draft) =>+ setEditingReply((prev) => prev && { ...prev, draft }),+ saveReplyEdit: handleSaveReplyEdit,+ };return (<>@@ -762,7 +1493,15 @@ export function CommentsSidebar({visible={visible}onClose={toggleCommentsSidebar}closeLabel={t("viewer.comments.closeSidebar", "Close comments sidebar")}- headerActions={commentsHeaderActions}+ headerActions={+ totalCount > 0 ? (+ <CommentsHeaderActions+ readerMode={readerMode}+ onAdd={handleAddComment}+ onClearAll={() => setClearAllModalOpen(true)}+ />+ ) : null+ }searchTerm={searchTerm}searchPlaceholder={t("viewer.comments.searchPlaceholder",@@ -772,76 +1511,23 @@ export function CommentsSidebar({viewportRef={scrollViewportRef}>{totalCount === 0 ? (- <Stack align="center" gap="sm" py="lg">- <Icon- name="message-square"- size="2rem"- style={{ color: "var(--mantine-color-dimmed)" }}+ <CommentsEmptyState>+ <AddCommentButton+ isPlacing={isPlacingComment}+ readerMode={readerMode}+ onAdd={handleAddComment}+ onCancel={handleCancelPlacingComment}/>- <Text size="sm" c="dimmed" ta="center">- {t(- "viewer.comments.hint",- "Place comments with the Comment, Insert Text, or Replace Text tools. They will appear here by page.",- )}- </Text>- {isPlacingComment ? (- <Button- variant="tertiary"- accent="warning"- size="sm"- onClick={handleCancelPlacingComment}- leftSection={<Icon name="pointer" size="1rem" />}- >- {t(- "viewer.comments.placingHint",- "Click a page to place… (cancel)",- )}- </Button>- ) : readerMode ? null : (- <Button- variant="tertiary"- size="sm"- onClick={handleAddComment}- leftSection={<Icon name="plus" size="1rem" />}- >- {t("viewer.comments.addComment", "Add comment")}- </Button>- )}- </Stack>+ </CommentsEmptyState>) : (<>- {isPlacingComment ? (- <Button- variant="tertiary"- accent="warning"- size="sm"- fullWidth- justify="start"- onClick={handleCancelPlacingComment}- leftSection={<Icon name="pointer" size="0.9rem" />}- style={{ paddingInline: 6 }}- >- {t(- "viewer.comments.placingHint",- "Click a page to place… (cancel)",- )}- </Button>- ) : readerMode ? null : (- <Button- variant="tertiary"- size="sm"- fullWidth- justify="start"- onClick={handleAddComment}- leftSection={<Icon name="plus" size="0.9rem" />}- style={{- paddingInline: 6,- marginBottom: "var(--space-xs)",- }}- >- {t("viewer.comments.addComment", "Add comment")}- </Button>- )}+ <AddCommentButton+ block+ isPlacing={isPlacingComment}+ readerMode={readerMode}+ onAdd={handleAddComment}+ onCancel={handleCancelPlacingComment}+ />{showSearchEmpty ? (<div className="sidebar-base__empty-state"><Text size="sm" c="dimmed" ta="center">@@ -854,489 +1540,36 @@ export function CommentsSidebar({) : (pageNumbers.map((pageIndex) => {const entries = filteredByPage[pageIndex] ?? [];- const pageNum = pageIndex + 1;return (- <Box key={pageIndex} mb="md">- <Text size="sm" fw={700} mb={2}>- {t("viewer.comments.pageLabel", "Page {{page}}", {- page: pageNum,- })}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t("viewer.comments.nComments", "{{count}} comments", {- count: entries.length,- })}- </Text>- <Box- mb="xs"- style={{- borderBottom: "1px solid var(--c-border-subtle)",- }}- />- <Stack gap="sm">- {entries.map((entry) => {- const ann = entry.annotation?.object;- const id = ann?.id;- if (!id) return null;- const key = `${pageIndex}_${id}`;- const replyKey = `${pageIndex}_${id}_reply`;- const displayContent = getCommentDisplayContent(entry);- const draft =- draftContents[key] !== undefined- ? draftContents[key]- : displayContent;- const replyDraft = replyDrafts[replyKey] ?? "";- const authorName = getAuthorName(ann, displayName);- /** Only treat as "comment posted" when annotation actually has content (user clicked Send), not on every keystroke. */- const hasMainContent =- (displayContent ?? "").trim().length > 0;- const isEditingMain = editingMainKey === key;-- const mainTimestamp = formatCommentDate(ann);- const typeLabel = getAnnotationTypeLabel(ann, t);-- return (- <Box- key={key}- data-comment-card={key}- p="sm"- style={{- border: selectedAnnotationIds.has(id)- ? "1px solid var(--mantine-color-blue-3)"- : "1px solid var(--c-border-subtle)",- borderRadius: 8,- backgroundColor: "var(--c-surface-raised)",- }}- >- <Group- wrap="nowrap"- gap="xs"- justify="space-between"- align="flex-start"- mb="xs"- >- <Group- wrap="nowrap"- gap="xs"- style={{ minWidth: 0, flex: 1 }}- >- <AnnotationTypeIcon ann={ann} />- <Box style={{ minWidth: 0 }}>- <Text size="sm" fw={600}>- {authorName}- </Text>- <Text size="xs" c="dimmed">- {typeLabel}- {mainTimestamp ? ` · ${mainTimestamp}` : ""}- </Text>- </Box>- </Group>- <Group- gap={2}- wrap="nowrap"- style={{ flexShrink: 0 }}- >- <Tooltip- label={t(- "viewer.comments.locateAnnotation",- "Locate in document",- )}- >- <ActionIcon- variant="tertiary"- accent="neutral"- size="sm"- aria-label={t(- "viewer.comments.locateAnnotation",- "Locate in document",- )}- onClick={() =>- handleLocateAnnotation(pageIndex, ann)- }- >- <Icon name="eye" size={16} />- </ActionIcon>- </Tooltip>- <Menu position="bottom-end" withArrow>- <Menu.Target>- <Tooltip- label={t(- "viewer.comments.moreActions",- "More actions",- )}- >- <ActionIcon- variant="tertiary"- accent="neutral"- size="sm"- aria-label={t(- "viewer.comments.moreActions",- "More actions",- )}- >- <Icon name="ellipsis" size={20} />- </ActionIcon>- </Tooltip>- </Menu.Target>- <Menu.Dropdown>- <Menu.Item- leftSection={- <Icon name="pencil" size={18} />- }- onClick={() => setEditingMainKey(key)}- >- {t("annotation.editText", "Edit")}- </Menu.Item>- <Menu.Item- leftSection={- <Icon name="trash" size={18} />- }- color="red"- onClick={() =>- handleDeleteClick(pageIndex, id, ann)- }- >- {t("annotation.delete", "Delete")}- </Menu.Item>- </Menu.Dropdown>- </Menu>- </Group>- </Group>-- {!hasMainContent || isEditingMain ? (- <Group gap="xs" wrap="nowrap" align="flex-end">- <Textarea- placeholder={t(- "viewer.comments.addCommentPlaceholder",- "Add comment...",- )}- size="sm"- autosize- minRows={1}- maxRows={6}- value={draft ?? ""}- onKeyDown={(e) => {- if (- e.key === "Enter" &&- !e.shiftKey &&- (draft ?? "").trim()- ) {- e.preventDefault();- handleSendMainComment(- pageIndex,- id,- draft ?? "",- );- setEditingMainKey(null);- }- }}- onChange={(e) => {- const v =- (e?.currentTarget ?? e?.target)?.value ??- "";- setDraftContents((prev) => ({- ...prev,- [key]: v,- }));- if (isEditingMain) {- handleContentsChange(pageIndex, id, v);- }- }}- style={{ flex: 1, minWidth: 0 }}- styles={{- input: {- borderColor:- "var(--mantine-color-blue-3)",- },- }}- autoFocus- />- <Tooltip- label={t(- "viewer.comments.addComment",- "Add comment",- )}- >- <ActionIcon- variant="primary"- size="md"- aria-label={t(- "viewer.comments.addComment",- "Add comment",- )}- onClick={() => {- handleSendMainComment(- pageIndex,- id,- draft ?? "",- );- setEditingMainKey(null);- }}- disabled={!(draft ?? "").trim()}- style={{- height: "36px",- width: "36px",- flexShrink: 0,- }}- >- <Icon name="check" size={18} />- </ActionIcon>- </Tooltip>- </Group>- ) : (- <>- <Text- size="sm"- mb="sm"- style={{ whiteSpace: "pre-wrap" }}- >- {displayContent}- </Text>-- {entry.replies?.length ? (- <Stack gap="sm" mb="sm">- {entry.replies.map((r) => {- const rObj = r?.object;- const rId = rObj?.id;- if (!rId) return null;- const rAuthor = getAuthorName(- rObj,- displayName,- );- const rTimestamp =- formatCommentDate(rObj);- const replyEditKey = `${pageIndex}_${id}_${rId}`;- const isEditingReply =- editingReplyKey === replyEditKey;- const canEditReply =- isReplyAuthoredByCurrentUser(- rObj,- displayName,- );- const replyBody =- replyEditDrafts[replyEditKey] !==- undefined- ? replyEditDrafts[replyEditKey]- : (rObj?.contents ?? "");- return (- <Box- key={rId}- pl="xs"- style={{- borderLeft:- "2px solid var(--mantine-color-blue-3)",- }}- >- <Box style={{ minWidth: 0 }}>- <Group- wrap="nowrap"- justify="space-between"- align="flex-start"- gap={4}- mb={2}- >- <Text size="sm" fw={600}>- {rAuthor}- </Text>- <Group- wrap="nowrap"- gap="xs"- align="center"- >- {canEditReply &&- !isEditingReply ? (- <Button- variant="tertiary"- hover={false}- type="button"- onClick={() => {- setEditingReplyKey(- replyEditKey,- );- setReplyEditDrafts(- () => ({- [replyEditKey]:- String(- rObj?.contents ??- "",- ),- }),- );- }}- >- <Text- size="xs"- c="var(--c-accent-text)"- >- {t(- "annotation.editText",- "Edit",- )}- </Text>- </Button>- ) : null}- {rTimestamp ? (- <Text size="xs" c="dimmed">- {rTimestamp}- </Text>- ) : null}- </Group>- </Group>- {isEditingReply ? (- <>- <Textarea- minRows={2}- autosize- value={replyBody}- onChange={(e) => {- const v =- (- e?.currentTarget ??- e?.target- )?.value ?? "";- setReplyEditDrafts((p) => ({- ...p,- [replyEditKey]: v,- }));- }}- styles={{- root: { width: "100%" },- }}- mb="xs"- />- <Group- gap={4}- wrap="nowrap"- justify="flex-end"- >- <Tooltip- label={t(- "viewer.comments.saveReply",- "Save reply",- )}- >- <ActionIcon- variant="primary"- size="sm"- aria-label={t(- "viewer.comments.saveReply",- "Save reply",- )}- onClick={() =>- handleSaveReplyEdit(- replyEditKey,- pageIndex,- rId,- replyBody,- )- }- disabled={- !replyBody.trim()- }- >- <Icon- name="check"- size={18}- />- </ActionIcon>- </Tooltip>- </Group>- </>- ) : (- <Text- size="sm"- style={{- whiteSpace: "pre-wrap",- }}- >- {rObj?.contents ?? ""}- </Text>- )}- </Box>- </Box>- );- })}- </Stack>- ) : null}-- <Group gap="xs" wrap="nowrap" align="center">- <TextInput- placeholder={t(- "viewer.comments.addReplyPlaceholder",- "Add reply...",- )}- size="sm"- value={replyDraft}- onKeyDown={(e) => {- if (- e.key === "Enter" &&- replyDraft.trim()- ) {- e.preventDefault();- handleSendReply(- pageIndex,- id,- ann?.rect,- );- }- }}- onChange={(e) => {- const v =- (e?.currentTarget ?? e?.target)- ?.value ?? "";- setReplyDrafts((p) => ({- ...p,- [replyKey]: v,- }));- }}- style={{ flex: 1, minWidth: 0 }}- styles={{- input: {- borderColor:- "var(--mantine-color-blue-3)",- height: "36px",- minHeight: "36px",- },- }}- />- <Tooltip- label={t(- "viewer.comments.addComment",- "Add comment",- )}- >- <ActionIcon- variant="primary"- size="md"- aria-label={t(- "viewer.comments.addComment",- "Add comment",- )}- onClick={() =>- handleSendReply(- pageIndex,- id,- ann?.rect,- )- }- disabled={!replyDraft.trim()}- style={{- height: "36px",- width: "36px",- flexShrink: 0,- }}- >- <Icon name="check" size={20} />- </ActionIcon>- </Tooltip>- </Group>- </>- )}- </Box>- );- })}- </Stack>- </Box>+ <CommentPageGroup+ key={pageIndex}+ pageIndex={pageIndex}+ count={entries.length}+ >+ {entries.map((entry) => {+ const id = entry.annotation?.object?.id;+ if (!id) return null;+ const cardKey = `${pageIndex}_${id}`;+ return (+ <CommentCard+ key={cardKey}+ pageIndex={pageIndex}+ entry={entry}+ selected={selectedAnnotationIds.has(id)}+ displayName={displayName}+ draft={draftContents[cardKey]}+ isEditing={editingMainKey === cardKey}+ replyDraft={replyDrafts[`${cardKey}_reply`] ?? ""}+ editingReply={+ editingReply?.cardKey === cardKey+ ? editingReply+ : null+ }+ actions={commentActions}+ />+ );+ })}+ </CommentPageGroup>);}))}@@ -1344,60 +1577,18 @@ export function CommentsSidebar({)}</SidebarBase>- <Modal+ <DeleteLinkedCommentModalopened={!!deleteModal}onClose={() => setDeleteModal(null)}- title={t(- "viewer.comments.deleteTitle",- "Remove annotation from comments?",- )}- centered- size="sm"- >- <Text size="sm" c="dimmed" mb="lg">- {t(- "viewer.comments.deleteDescription",- "This annotation has a comment attached. You can remove just the comment from the sidebar while keeping the annotation, or delete everything.",- )}- </Text>- <Group justify="flex-end" gap="sm">- <Button variant="secondary" onClick={handleRemoveFromSidebar}>- {t("viewer.comments.removeCommentOnly", "Remove comment only")}- </Button>- <Button accent="danger" onClick={handleDeleteAnnotation}>- {t(- "viewer.comments.deleteAnnotationAndComment",- "Delete annotation & comment",- )}- </Button>- </Group>- </Modal>+ onRemoveComment={handleRemoveFromSidebar}+ onDeleteAnnotation={handleDeleteAnnotation}+ />- <Modal+ <ClearAllCommentsModalopened={clearAllModalOpen}onClose={() => setClearAllModalOpen(false)}- title={t("viewer.comments.clearAllTitle", "Clear all comments?")}- centered- size="sm"- >- <Text size="sm" c="dimmed" mb="lg">- {t(- "viewer.comments.clearAllDescription",- "This removes comments and replies from the sidebar while keeping any attached annotations in the document.",- )}- </Text>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={() => setClearAllModalOpen(false)}- >- {t("viewer.comments.cancelClearAll", "Cancel")}- </Button>- <Button accent="danger" onClick={handleClearAllComments}>- {t("viewer.comments.clearAll", "Clear all comments")}- </Button>- </Group>- </Modal>+ onConfirm={handleClearAllComments}+ /></>);}diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex 5a3a64b2c0..874c6982b5 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -52,8 +52,8 @@ import {AnnotationPluginPackage,} from "@embedpdf/plugin-annotation/react";import type { AnnotationEvent } from "@embedpdf/plugin-annotation";-import { PdfAnnotationSubtype } from "@embedpdf/models";import type { PdfAnnotationObject, Rect } from "@embedpdf/models";+import { registerAnnotationTools } from "@app/components/viewer/annotationTools";import {RedactionPluginPackage,RedactionLayer,@@ -79,7 +79,10 @@ import type {SignaturePreview,SignatureOverlayAPI,} from "@app/components/viewer/viewerTypes";-import { SignaturePreviewLayer } from "@app/components/viewer/SignaturePreviewLayer";+import {+ SignaturePreviewLayer,+ type SignaturePreviewLayerProps,+} from "@app/components/viewer/SignaturePreviewLayer";import { ExportAPIBridge } from "@app/components/viewer/ExportAPIBridge";import { BookmarkAPIBridge } from "@app/components/viewer/BookmarkAPIBridge";import { AttachmentAPIBridge } from "@app/components/viewer/AttachmentAPIBridge";@@ -230,6 +233,426 @@ function ViewerPageContainer({);}+type SignatureOverlayOptions = Omit<+ SignaturePreviewLayerProps,+ "pageIndex" | "pageWidth" | "pageHeight"+>;++type PdfRenderMode = NonNullable<LocalEmbedPDFProps["pdfRenderMode"]>;++const PDF_RENDER_FILTERS: Record<PdfRenderMode, string | undefined> = {+ normal: undefined,+ dark: "invert(1) hue-rotate(180deg)",+ sepia: "sepia(0.7) brightness(0.85)",+};++interface PageLayerProps {+ documentId: string;+ pageIndex: number;+}++interface PageGeometry extends PageLayerProps {+ width: number;+ height: number;+}++interface PageLayerOptions {+ file?: File | Blob;+ fileId?: string | null;+ pdfRenderMode: PdfRenderMode;+ enableFormFill: boolean;+ formEditingActive: boolean;+ enableAnnotations: boolean;+ enableRedaction: boolean;+ showBakedAnnotations: boolean;+ onAnnotationMenuAnchor: (anchor: AnnotationMenuAnchor | null) => void;+ /** Null while the signature preview overlay is not mounted. */+ signatureOverlay: SignatureOverlayOptions | null;+}++/** Everything a page needs besides the geometry the Scroller supplies. */+interface ViewerPageOptions extends PageLayerOptions {+ onPageLayout?: () => void;+ restorePending: boolean;+}++function PageTiles({+ documentId,+ pageIndex,+ renderMode,+}: PageLayerProps & { renderMode: PdfRenderMode }) {+ return (+ <div+ style={{+ position: "absolute",+ inset: 0,+ transition: "filter 0.25s ease",+ filter: PDF_RENDER_FILTERS[renderMode],+ }}+ >+ <TilingLayer documentId={documentId} pageIndex={pageIndex} />+ </div>+ );+}++function PageTextSelection({ documentId, pageIndex }: PageLayerProps) {+ return (+ <>+ <div+ className="pdf-selection-layer"+ style={{+ position: "absolute",+ inset: 0,+ pointerEvents: "none",+ }}+ >+ <SelectionLayer+ documentId={documentId}+ pageIndex={pageIndex}+ background="var(--pdf-selection-bg)"+ selectionMenu={(props) => <TextSelectionMenu {...props} />}+ />+ </div>+ <TextSelectionHandler documentId={documentId} pageIndex={pageIndex} />+ </>+ );+}++interface FormFieldLayersProps extends PageGeometry {+ fileId?: string | null;+}++function FormFieldEditingOverlays({+ active,+ documentId,+ pageIndex,+ width,+ height,+ fileId,+}: FormFieldLayersProps & { active: boolean }) {+ if (!active) return null;+ return (+ <>+ {/* Create-mode: drag to place new fields */}+ <FormFieldCreationOverlay+ documentId={documentId}+ pageIndex={pageIndex}+ pageWidth={width}+ pageHeight={height}+ fileId={fileId}+ />+ {/* Modify-mode: select / move / resize existing fields */}+ <FormFieldEditOverlay+ documentId={documentId}+ pageIndex={pageIndex}+ pageWidth={width}+ pageHeight={height}+ fileId={fileId}+ />+ </>+ );+}++function FormFillLayers({+ enabled,+ editing,+ file,+ ...page+}: FormFieldLayersProps & {+ enabled: boolean;+ editing: boolean;+ file?: File | Blob;+}) {+ if (!enabled) return null;+ return (+ <>+ {/* ButtonAppearanceOverlay: renders PDF-native button visuals as bitmaps */}+ {file && (+ <ButtonAppearanceOverlay+ pageIndex={page.pageIndex}+ pdfSource={file}+ pageWidth={page.width}+ pageHeight={page.height}+ />+ )}+ {/* FormFieldOverlay for interactive form filling */}+ <FormFieldOverlay+ documentId={page.documentId}+ pageIndex={page.pageIndex}+ pageWidth={page.width}+ pageHeight={page.height}+ fileId={page.fileId}+ />+ <FormFieldEditingOverlays active={editing} {...page} />+ </>+ );+}++interface AnnotationEditingLayersProps extends PageLayerProps {+ enableAnnotations: boolean;+ enableRedaction: boolean;+ showBakedAnnotations: boolean;+ onAnnotationMenuAnchor: (anchor: AnnotationMenuAnchor | null) => void;+}++function AnnotationEditingLayers({+ documentId,+ pageIndex,+ enableAnnotations,+ enableRedaction,+ showBakedAnnotations,+ onAnnotationMenuAnchor,+}: AnnotationEditingLayersProps) {+ if (!enableAnnotations && !enableRedaction) return null;+ return (+ <>+ {/* AnnotationLayer for annotation editing and annotation-based redactions */}+ <AnnotationLayer+ documentId={documentId}+ pageIndex={pageIndex}+ selectionOutline={{ color: "#007ACC" }}+ selectionMenu={(props) => (+ <AnnotationSelectionMenu+ {...props}+ onAnchor={onAnnotationMenuAnchor}+ />+ )}+ style={+ !showBakedAnnotations+ ? {+ opacity: 0,+ pointerEvents: "none",+ }+ : undefined+ }+ />+ {enableRedaction && (+ <RedactionLayer+ documentId={documentId}+ pageIndex={pageIndex}+ selectionMenu={(props) => <RedactionSelectionMenu {...props} />}+ />+ )}+ </>+ );+}++function PageLayers({+ documentId,+ pageIndex,+ width,+ height,+ file,+ fileId,+ pdfRenderMode,+ enableFormFill,+ formEditingActive,+ enableAnnotations,+ enableRedaction,+ showBakedAnnotations,+ onAnnotationMenuAnchor,+ signatureOverlay,+}: PageGeometry & PageLayerOptions) {+ return (+ <>+ <PageTiles+ documentId={documentId}+ pageIndex={pageIndex}+ renderMode={pdfRenderMode}+ />+ <CustomSearchLayer documentId={documentId} pageIndex={pageIndex} />+ <PageTextSelection documentId={documentId} pageIndex={pageIndex} />+ <FormFillLayers+ enabled={enableFormFill}+ editing={formEditingActive}+ file={file}+ documentId={documentId}+ pageIndex={pageIndex}+ width={width}+ height={height}+ fileId={fileId}+ />+ {/* SignatureFieldOverlay: bitmaps of digital-signature appearances */}+ {file && (+ <SignatureFieldOverlay+ documentId={documentId}+ pageIndex={pageIndex}+ pdfSource={file}+ pageWidth={width}+ pageHeight={height}+ />+ )}+ <AnnotationEditingLayers+ documentId={documentId}+ pageIndex={pageIndex}+ enableAnnotations={enableAnnotations}+ enableRedaction={enableRedaction}+ showBakedAnnotations={showBakedAnnotations}+ onAnnotationMenuAnchor={onAnnotationMenuAnchor}+ />+ {/* LinkLayer: uses EmbedPDF annotation state for link rendering */}+ <LinkLayer documentId={documentId} pageIndex={pageIndex} />+ {/* Signature preview overlay (opt-in; off by default) */}+ {signatureOverlay && (+ <SignaturePreviewLayer+ pageIndex={pageIndex}+ pageWidth={width}+ pageHeight={height}+ {...signatureOverlay}+ />+ )}+ </>+ );+}++function ViewerPage({+ onPageLayout,+ restorePending,+ ...layers+}: PageGeometry & ViewerPageOptions) {+ const { documentId, pageIndex } = layers;+ return (+ <Rotate documentId={documentId} pageIndex={pageIndex}>+ <ViewerPagePointerProvider documentId={documentId} pageIndex={pageIndex}>+ <ViewerPageContainer+ documentId={documentId}+ pageIndex={pageIndex}+ width={layers.width}+ height={layers.height}+ onPageLayout={onPageLayout}+ restorePending={restorePending}+ >+ <PageLayers {...layers} />+ </ViewerPageContainer>+ </ViewerPagePointerProvider>+ </Rotate>+ );+}++interface DocumentViewportProps {+ documentId: string;+ pageOptions: ViewerPageOptions;+}++function DocumentViewport({ documentId, pageOptions }: DocumentViewportProps) {+ return (+ <ViewerGlobalPointerProvider documentId={documentId}>+ <Viewport+ documentId={documentId}+ style={{+ backgroundColor: "var(--c-bg)",+ height: "100%",+ width: "100%",+ maxHeight: "100%",+ maxWidth: "100%",+ overflow: "auto",+ position: "relative",+ flex: 1,+ minHeight: 0,+ minWidth: 0,+ contain: "strict",+ }}+ >+ <Scroller+ documentId={documentId}+ renderPage={({ width, height, pageIndex }) => (+ <ViewerPage+ key={`${documentId}-${pageIndex}`}+ documentId={documentId}+ pageIndex={pageIndex}+ width={width}+ height={height}+ {...pageOptions}+ />+ )}+ />+ </Viewport>+ </ViewerGlobalPointerProvider>+ );+}++interface DocumentCommentsProps {+ enabled: boolean;+ documentId: string;+ authorName: string;+ visible: boolean;+ rightOffset: string;+}++function DocumentComments({+ enabled,+ documentId,+ authorName,+ visible,+ rightOffset,+}: DocumentCommentsProps) {+ if (!enabled) return null;+ return (+ <CommentAuthorProvider displayName={authorName}>+ <CommentsSidebar+ documentId={documentId}+ visible={visible}+ rightOffset={rightOffset}+ />+ </CommentAuthorProvider>+ );+}++type EditingBridgesProps = Pick<+ LocalEmbedPDFProps,+ | "historyApiRef"+ | "signatureApiRef"+ | "annotationApiRef"+ | "redactionTrackerRef"+> & {+ enableAnnotations: boolean;+ enableRedaction: boolean;+ isManualRedactionMode: boolean;+ isSignMode: boolean;+ getAnnotationAnchor: (annotationId: string) => AnnotationMenuAnchor | null;+ onAnnotationDeleted: (anchor: AnnotationMenuAnchor) => void;+ deletedAnnotationMenu: AnnotationMenuAnchor | null;+ onDismissDeletedAnnotationMenu: () => void;+};++/** Bridges that exist only while annotations or redaction can edit the document. */+function EditingBridges({+ enableAnnotations,+ enableRedaction,+ isManualRedactionMode,+ isSignMode,+ historyApiRef,+ signatureApiRef,+ annotationApiRef,+ redactionTrackerRef,+ getAnnotationAnchor,+ onAnnotationDeleted,+ deletedAnnotationMenu,+ onDismissDeletedAnnotationMenu,+}: EditingBridgesProps) {+ const redactionActive = enableRedaction || isManualRedactionMode;+ if (!enableAnnotations && !redactionActive) return null;+ return (+ <>+ <HistoryAPIBridge ref={historyApiRef} />+ <AnnotationMenuEvents+ getAnchor={getAnnotationAnchor}+ onDeleted={onAnnotationDeleted}+ />+ <AnnotationDeletedMenu+ anchor={deletedAnnotationMenu}+ onDismiss={onDismissDeletedAnnotationMenu}+ />+ {/* Always render RedactionAPIBridge when in manual redaction mode so buttons can switch from annotation mode */}+ {redactionActive && <RedactionAPIBridge />}+ {/* Always render SignatureAPIBridge so annotation tools (draw) can be activated even when starting in redaction mode */}+ <SignatureAPIBridge ref={signatureApiRef} isSignMode={isSignMode} />+ {redactionActive && <RedactionPendingTracker ref={redactionTrackerRef} />}+ {enableAnnotations && <AnnotationAPIBridge ref={annotationApiRef} />}+ </>+ );+}+export function LocalEmbedPDF({file,url,@@ -728,6 +1151,106 @@ export function LocalEmbedPDF({);}+ const handleInitialized = async (registry: PluginRegistry) => {+ // v2.0: Use registry.getPlugin() to access plugin APIs+ const annotationPlugin = registry.getPlugin("annotation");+ if (!annotationPlugin || !annotationPlugin.provides) return;++ const annotationApi = annotationPlugin.provides();+ if (!annotationApi || !enableAnnotations) return;++ registerAnnotationTools(annotationApi);++ annotationApi.onAnnotationEvent((event: AnnotationEvent) => {+ if (event.type === "create" && event.committed) {+ setAnnotations((prev) => [+ ...prev,+ {+ id: event.annotation.id,+ pageIndex: event.pageIndex,+ rect: event.annotation.rect,+ },+ ]);++ // If the annotation doesn't have customData.toolId, patch it from the active tool.+ // EmbedPDF doesn't always persist customData from setToolDefaults into created annotations.+ const annotationId = event.annotation.id;+ const existingCustomData = (+ event.annotation as unknown as {+ customData?: Record<string, unknown>;+ }+ ).customData;+ if (annotationId && !existingCustomData?.toolId) {+ const activeTool = (+ annotationApi as unknown as {+ getActiveTool?: () => { id: string } | null;+ }+ ).getActiveTool?.();+ if (activeTool?.id && activeTool.id !== "select") {+ (+ annotationApi as unknown as {+ updateAnnotation?: (+ page: number,+ id: string,+ patch: Record<string, unknown>,+ ) => void;+ }+ ).updateAnnotation?.(event.pageIndex, annotationId, {+ customData: {+ ...(existingCustomData ?? {}),+ toolId: activeTool.id,+ },+ });+ }+ }++ // Auto-select the annotation after creation so the selection menu appears immediately,+ // letting users discover the editing options before they click away.+ if (annotationId) {+ (+ annotationApi as unknown as {+ selectAnnotation?: (pageIndex: number, id: string) => void;+ }+ ).selectAnnotation?.(event.pageIndex, annotationId);+ }++ if (onSignatureAdded) {+ onSignatureAdded(event.annotation);+ }+ } else if (event.type === "delete" && event.committed) {+ setAnnotations((prev) =>+ prev.filter((ann) => ann.id !== event.annotation.id),+ );+ }+ });+ };++ const pageOptions: ViewerPageOptions = {+ file,+ fileId,+ pdfRenderMode,+ enableFormFill,+ formEditingActive,+ enableAnnotations,+ enableRedaction,+ showBakedAnnotations,+ onAnnotationMenuAnchor: handleAnnotationMenuAnchor,+ signatureOverlay: signatureOverlayEnabled+ ? {+ previews: localSignaturePreviews,+ readOnly: signaturePreviewsReadOnly,+ placementMode: signaturePlacementMode,+ placementData: signaturePlacementData,+ placementType: signaturePlacementType,+ onChange: handleSignaturePreviewsChange,+ selectedId: selectedSignatureId,+ onSelect: setSelectedSignatureId,+ }+ : null,+ onPageLayout,+ restorePending,+ };+// Wrap your UI with the <EmbedPDF> providerreturn (<PrivateContent>@@ -748,493 +1271,7 @@ export function LocalEmbedPDF({<EmbedPDFengine={engine}plugins={plugins}- onInitialized={async (registry: PluginRegistry) => {- // v2.0: Use registry.getPlugin() to access plugin APIs- const annotationPlugin = registry.getPlugin("annotation");- if (!annotationPlugin || !annotationPlugin.provides) return;-- const annotationApi = annotationPlugin.provides();- if (!annotationApi) return;-- if (enableAnnotations) {- // LooseAnnotationTool bypasses strict Partial<T> defaults typing from the library:- // EmbedPDF accepts extra runtime properties (borderWidth, textColor, finishOnDoubleClick,- // etc.) that aren't reflected in the TypeScript model types.- type LooseAnnotationTool = {- id: string;- name: string;- interaction?: {- exclusive: boolean;- cursor: string;- textSelection?: boolean;- isRotatable?: boolean;- };- matchScore?: (annotation: PdfAnnotationObject) => number;- defaults?: Record<string, unknown>;- clickBehavior?: Record<string, unknown>;- behavior?: {- deactivateToolAfterCreate?: boolean;- selectAfterCreate?: boolean;- };- };- const ensureTool = (tool: LooseAnnotationTool) => {- const existing = annotationApi.getTool?.(tool.id);- if (!existing) {- annotationApi.addTool(tool);- }- };-- ensureTool({- id: "highlight",- name: "Highlight",- interaction: {- exclusive: true,- cursor: "text",- textSelection: true,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.HIGHLIGHT ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.HIGHLIGHT,- strokeColor: "#ffd54f",- color: "#ffd54f",- opacity: 0.6,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "underline",- name: "Underline",- interaction: {- exclusive: true,- cursor: "text",- textSelection: true,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.UNDERLINE ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.UNDERLINE,- strokeColor: "#ffb300",- color: "#ffb300",- opacity: 1,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "strikeout",- name: "Strikeout",- interaction: {- exclusive: true,- cursor: "text",- textSelection: true,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.STRIKEOUT ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.STRIKEOUT,- strokeColor: "#e53935",- color: "#e53935",- opacity: 1,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "squiggly",- name: "Squiggly",- interaction: {- exclusive: true,- cursor: "text",- textSelection: true,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.SQUIGGLY ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.SQUIGGLY,- strokeColor: "#00acc1",- color: "#00acc1",- opacity: 1,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "ink",- name: "Pen",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.INK ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.INK,- strokeColor: "#1f2933",- color: "#1f2933",- opacity: 1,- borderWidth: 2,- lineWidth: 2,- strokeWidth: 2,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "inkHighlighter",- name: "Ink Highlighter",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.INK &&- (annotation.strokeColor === "#ffd54f" ||- annotation.color === "#ffd54f")- ? 8- : 0,- defaults: {- type: PdfAnnotationSubtype.INK,- strokeColor: "#ffd54f",- color: "#ffd54f",- opacity: 0.5,- borderWidth: 6,- lineWidth: 6,- strokeWidth: 6,- },- behavior: {- deactivateToolAfterCreate: false,- selectAfterCreate: true,- },- });-- ensureTool({- id: "square",- name: "Square",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.SQUARE ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.SQUARE,- color: "#0000ff", // fill color (blue)- strokeColor: "#cf5b5b", // border color (reddish pink)- opacity: 0.5,- borderWidth: 1,- strokeWidth: 1,- lineWidth: 1,- },- clickBehavior: {- enabled: true,- defaultSize: { width: 120, height: 90 },- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "circle",- name: "Circle",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.CIRCLE ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.CIRCLE,- color: "#0000ff", // fill color (blue)- strokeColor: "#cf5b5b", // border color (reddish pink)- opacity: 0.5,- borderWidth: 1,- strokeWidth: 1,- lineWidth: 1,- },- clickBehavior: {- enabled: true,- defaultSize: { width: 100, height: 100 },- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "line",- name: "Line",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.LINE ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.LINE,- color: "#1565c0",- opacity: 1,- borderWidth: 2,- strokeWidth: 2,- lineWidth: 2,- },- clickBehavior: {- enabled: true,- defaultLength: 120,- defaultAngle: 0,- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "lineArrow",- name: "Arrow",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) => {- if (annotation.type !== PdfAnnotationSubtype.LINE) return 0;- // EmbedPDF stores endStyle/lineEndingStyles at runtime; library types use lineEndings- const ann = annotation as PdfAnnotationObject & {- endStyle?: string;- lineEndingStyles?: { end?: string };- };- return ann.endStyle === "ClosedArrow" ||- ann.lineEndingStyles?.end === "ClosedArrow"- ? 9- : 0;- },- defaults: {- type: PdfAnnotationSubtype.LINE,- color: "#1565c0",- opacity: 1,- borderWidth: 2,- startStyle: "None",- endStyle: "ClosedArrow",- lineEndingStyles: { start: "None", end: "ClosedArrow" },- },- clickBehavior: {- enabled: true,- defaultLength: 120,- defaultAngle: 0,- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "polyline",- name: "Polyline",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.POLYLINE ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.POLYLINE,- color: "#1565c0",- opacity: 1,- borderWidth: 2,- },- clickBehavior: {- enabled: true,- finishOnDoubleClick: true,- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "polygon",- name: "Polygon",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.POLYGON ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.POLYGON,- color: "#0000ff", // fill color (blue)- strokeColor: "#cf5b5b", // border color (reddish pink)- opacity: 0.5,- borderWidth: 1,- },- clickBehavior: {- enabled: true,- finishOnDoubleClick: true,- defaultSize: { width: 140, height: 100 },- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "text",- name: "Text",- interaction: {- exclusive: true,- cursor: "text",- isRotatable: false,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.FREETEXT ? 10 : 0,- defaults: {- type: PdfAnnotationSubtype.FREETEXT,- textColor: "#111111",- fontSize: 14,- fontFamily: "Helvetica",- opacity: 1,- interiorColor: "#fffef7",- contents: "Text",- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "note",- name: "Note",- interaction: {- exclusive: true,- cursor: "pointer",- isRotatable: false,- },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.FREETEXT ? 8 : 0,- defaults: {- type: PdfAnnotationSubtype.FREETEXT,- textColor: "#1b1b1b",- color: "#ffa000",- interiorColor: "#fff8e1",- opacity: 1,- contents: "Note",- fontSize: 12,- },- clickBehavior: {- enabled: true,- defaultSize: { width: 160, height: 100 },- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "stamp",- name: "Image Stamp",- interaction: { exclusive: false, cursor: "copy" },- matchScore: (annotation: PdfAnnotationObject) =>- annotation.type === PdfAnnotationSubtype.STAMP ? 5 : 0,- defaults: {- type: PdfAnnotationSubtype.STAMP,- },- behavior: {- deactivateToolAfterCreate: true,- selectAfterCreate: true,- },- });-- ensureTool({- id: "signatureStamp",- name: "Digital Signature",- interaction: { exclusive: false, cursor: "copy" },- matchScore: () => 0,- defaults: {- type: PdfAnnotationSubtype.STAMP,- },- });-- ensureTool({- id: "signatureInk",- name: "Signature Draw",- interaction: { exclusive: true, cursor: "crosshair" },- matchScore: () => 0,- defaults: {- type: PdfAnnotationSubtype.INK,- strokeColor: "#000000",- color: "#000000",- opacity: 1.0,- borderWidth: 2,- },- });-- annotationApi.onAnnotationEvent((event: AnnotationEvent) => {- if (event.type === "create" && event.committed) {- setAnnotations((prev) => [- ...prev,- {- id: event.annotation.id,- pageIndex: event.pageIndex,- rect: event.annotation.rect,- },- ]);-- // If the annotation doesn't have customData.toolId, patch it from the active tool.- // EmbedPDF doesn't always persist customData from setToolDefaults into created annotations.- const annotationId = event.annotation.id;- const existingCustomData = (- event.annotation as unknown as {- customData?: Record<string, unknown>;- }- ).customData;- if (annotationId && !existingCustomData?.toolId) {- const activeTool = (- annotationApi as unknown as {- getActiveTool?: () => { id: string } | null;- }- ).getActiveTool?.();- if (activeTool?.id && activeTool.id !== "select") {- (- annotationApi as unknown as {- updateAnnotation?: (- page: number,- id: string,- patch: Record<string, unknown>,- ) => void;- }- ).updateAnnotation?.(event.pageIndex, annotationId, {- customData: {- ...(existingCustomData ?? {}),- toolId: activeTool.id,- },- });- }- }-- // Auto-select the annotation after creation so the selection menu appears immediately,- // letting users discover the editing options before they click away.- if (annotationId) {- (- annotationApi as unknown as {- selectAnnotation?: (- pageIndex: number,- id: string,- ) => void;- }- ).selectAnnotation?.(event.pageIndex, annotationId);- }-- if (onSignatureAdded) {- onSignatureAdded(event.annotation);- }- } else if (event.type === "delete" && event.committed) {- setAnnotations((prev) =>- prev.filter((ann) => ann.id !== event.annotation.id),- );- }- });- }- }}+ onInitialized={handleInitialized}><DocumentSwapBridgepending={pendingDocument}@@ -1250,32 +1287,20 @@ export function LocalEmbedPDF({<SearchAPIBridge /><ThumbnailAPIBridge /><RotateAPIBridge />- {(enableAnnotations || enableRedaction || isManualRedactionMode) && (- <HistoryAPIBridge ref={historyApiRef} />- )}- {(enableAnnotations || enableRedaction || isManualRedactionMode) && (- <>- <AnnotationMenuEvents- getAnchor={getAnnotationAnchor}- onDeleted={handleAnnotationDeleted}- />- <AnnotationDeletedMenu- anchor={deletedAnnotationMenu}- onDismiss={dismissDeletedAnnotationMenu}- />- </>- )}- {/* Always render RedactionAPIBridge when in manual redaction mode so buttons can switch from annotation mode */}- {(enableRedaction || isManualRedactionMode) && <RedactionAPIBridge />}- {/* Always render SignatureAPIBridge so annotation tools (draw) can be activated even when starting in redaction mode */}- {(enableAnnotations || enableRedaction || isManualRedactionMode) && (- <SignatureAPIBridge ref={signatureApiRef} isSignMode={isSignMode} />- )}- {(enableRedaction || isManualRedactionMode) && (- <RedactionPendingTracker ref={redactionTrackerRef} />- )}- {enableAnnotations && <AnnotationAPIBridge ref={annotationApiRef} />}-+ <EditingBridges+ enableAnnotations={enableAnnotations}+ enableRedaction={enableRedaction}+ isManualRedactionMode={isManualRedactionMode}+ isSignMode={isSignMode}+ historyApiRef={historyApiRef}+ signatureApiRef={signatureApiRef}+ annotationApiRef={annotationApiRef}+ redactionTrackerRef={redactionTrackerRef}+ getAnnotationAnchor={getAnnotationAnchor}+ onAnnotationDeleted={handleAnnotationDeleted}+ deletedAnnotationMenu={deletedAnnotationMenu}+ onDismissDeletedAnnotationMenu={dismissDeletedAnnotationMenu}+ /><ExportAPIBridge /><BookmarkAPIBridge /><AttachmentAPIBridge />@@ -1290,216 +1315,17 @@ export function LocalEmbedPDF({>{(documentId) => (<>- <ViewerGlobalPointerProvider documentId={documentId}>- <Viewport- documentId={documentId}- style={{- backgroundColor: "var(--c-bg)",- height: "100%",- width: "100%",- maxHeight: "100%",- maxWidth: "100%",- overflow: "auto",- position: "relative",- flex: 1,- minHeight: 0,- minWidth: 0,- contain: "strict",- }}- >- <Scroller- documentId={documentId}- renderPage={({ width, height, pageIndex }) => {- return (- <Rotate- key={`${documentId}-${pageIndex}`}- documentId={documentId}- pageIndex={pageIndex}- >- <ViewerPagePointerProvider- documentId={documentId}- pageIndex={pageIndex}- >- <ViewerPageContainer- documentId={documentId}- pageIndex={pageIndex}- width={width}- height={height}- onPageLayout={onPageLayout}- restorePending={restorePending}- >- <div- style={{- position: "absolute",- inset: 0,- transition: "filter 0.25s ease",- filter:- pdfRenderMode === "dark"- ? "invert(1) hue-rotate(180deg)"- : pdfRenderMode === "sepia"- ? "sepia(0.7) brightness(0.85)"- : undefined,- }}- >- <TilingLayer- documentId={documentId}- pageIndex={pageIndex}- />- </div>-- <CustomSearchLayer- documentId={documentId}- pageIndex={pageIndex}- />-- <div- className="pdf-selection-layer"- style={{- position: "absolute",- inset: 0,- pointerEvents: "none",- }}- >- <SelectionLayer- documentId={documentId}- pageIndex={pageIndex}- background="var(--pdf-selection-bg)"- selectionMenu={(props) => (- <TextSelectionMenu {...props} />- )}- />- </div>- <TextSelectionHandler- documentId={documentId}- pageIndex={pageIndex}- />-- {/* ButtonAppearanceOverlay — renders PDF-native button visuals as bitmaps */}- {enableFormFill && file && (- <ButtonAppearanceOverlay- pageIndex={pageIndex}- pdfSource={file}- pageWidth={width}- pageHeight={height}- />- )}-- {/* FormFieldOverlay for interactive form filling */}- {enableFormFill && (- <FormFieldOverlay- documentId={documentId}- pageIndex={pageIndex}- pageWidth={width}- pageHeight={height}- fileId={fileId}- />- )}-- {/* Create-mode: drag to place new fields */}- {enableFormFill && formEditingActive && (- <FormFieldCreationOverlay- documentId={documentId}- pageIndex={pageIndex}- pageWidth={width}- pageHeight={height}- fileId={fileId}- />- )}-- {/* Modify-mode: select / move / resize existing fields */}- {enableFormFill && formEditingActive && (- <FormFieldEditOverlay- documentId={documentId}- pageIndex={pageIndex}- pageWidth={width}- pageHeight={height}- fileId={fileId}- />- )}-- {/* SignatureFieldOverlay — bitmaps of digital-signature appearances */}- {file && (- <SignatureFieldOverlay- documentId={documentId}- pageIndex={pageIndex}- pdfSource={file}- pageWidth={width}- pageHeight={height}- />- )}-- {/* AnnotationLayer for annotation editing and annotation-based redactions */}- {(enableAnnotations || enableRedaction) && (- <AnnotationLayer- documentId={documentId}- pageIndex={pageIndex}- selectionOutline={{ color: "#007ACC" }}- selectionMenu={(props) => (- <AnnotationSelectionMenu- {...props}- onAnchor={handleAnnotationMenuAnchor}- />- )}- style={- !showBakedAnnotations- ? {- opacity: 0,- pointerEvents: "none",- }- : undefined- }- />- )}-- {enableRedaction && (- <RedactionLayer- documentId={documentId}- pageIndex={pageIndex}- selectionMenu={(props) => (- <RedactionSelectionMenu {...props} />- )}- />- )}-- {/* LinkLayer – uses EmbedPDF annotation state for link rendering */}- <LinkLayer- documentId={documentId}- pageIndex={pageIndex}- />-- {/* Signature preview overlay (opt-in; off by default) */}- {signatureOverlayEnabled && (- <SignaturePreviewLayer- pageIndex={pageIndex}- pageWidth={width}- pageHeight={height}- previews={localSignaturePreviews}- readOnly={signaturePreviewsReadOnly}- placementMode={signaturePlacementMode}- placementData={signaturePlacementData}- placementType={signaturePlacementType}- onChange={handleSignaturePreviewsChange}- selectedId={selectedSignatureId}- onSelect={setSelectedSignatureId}- />- )}- </ViewerPageContainer>- </ViewerPagePointerProvider>- </Rotate>- );- }}- />- </Viewport>- </ViewerGlobalPointerProvider>- {enableAnnotations && (- <CommentAuthorProvider displayName={commentAuthorName}>- <CommentsSidebar- documentId={documentId}- visible={isCommentsSidebarVisible}- rightOffset={commentsSidebarRightOffset}- />- </CommentAuthorProvider>- )}+ <DocumentViewport+ documentId={documentId}+ pageOptions={pageOptions}+ />+ <DocumentComments+ enabled={enableAnnotations}+ documentId={documentId}+ authorName={commentAuthorName}+ visible={isCommentsSidebarVisible}+ rightOffset={commentsSidebarRightOffset}+ /></>)}</DocumentReadyWrapper>diff --git a/frontend/editor/src/core/components/viewer/annotationTools.ts b/frontend/editor/src/core/components/viewer/annotationTools.tsnew file mode 100644index 0000000000..00674f2deb--- /dev/null+++ b/frontend/editor/src/core/components/viewer/annotationTools.ts@@ -0,0 +1,422 @@+import type {+ AnnotationCapability,+ AnnotationTool,+} from "@embedpdf/plugin-annotation";+import { PdfAnnotationSubtype } from "@embedpdf/models";+import type { PdfAnnotationObject } from "@embedpdf/models";++// LooseAnnotationTool bypasses strict Partial<T> defaults typing from the library:+// EmbedPDF accepts extra runtime properties (borderWidth, textColor, finishOnDoubleClick,+// etc.) that aren't reflected in the TypeScript model types.+type LooseAnnotationTool = {+ id: string;+ name: string;+ interaction?: {+ exclusive: boolean;+ cursor: string;+ textSelection?: boolean;+ isRotatable?: boolean;+ };+ matchScore?: (annotation: PdfAnnotationObject) => number;+ defaults?: Record<string, unknown>;+ clickBehavior?: Record<string, unknown>;+ behavior?: {+ deactivateToolAfterCreate?: boolean;+ selectAfterCreate?: boolean;+ };+};++/** Adds the viewer's annotation tools to the plugin, skipping any it already has. */+export function registerAnnotationTools(+ annotationApi: Pick<AnnotationCapability, "getTool" | "addTool">,+): void {+ const ensureTool = (tool: LooseAnnotationTool) => {+ const existing = annotationApi.getTool?.(tool.id);+ if (!existing) {+ annotationApi.addTool(tool as unknown as AnnotationTool);+ }+ };++ ensureTool({+ id: "highlight",+ name: "Highlight",+ interaction: {+ exclusive: true,+ cursor: "text",+ textSelection: true,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.HIGHLIGHT ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.HIGHLIGHT,+ strokeColor: "#ffd54f",+ color: "#ffd54f",+ opacity: 0.6,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "underline",+ name: "Underline",+ interaction: {+ exclusive: true,+ cursor: "text",+ textSelection: true,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.UNDERLINE ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.UNDERLINE,+ strokeColor: "#ffb300",+ color: "#ffb300",+ opacity: 1,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "strikeout",+ name: "Strikeout",+ interaction: {+ exclusive: true,+ cursor: "text",+ textSelection: true,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.STRIKEOUT ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.STRIKEOUT,+ strokeColor: "#e53935",+ color: "#e53935",+ opacity: 1,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "squiggly",+ name: "Squiggly",+ interaction: {+ exclusive: true,+ cursor: "text",+ textSelection: true,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.SQUIGGLY ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.SQUIGGLY,+ strokeColor: "#00acc1",+ color: "#00acc1",+ opacity: 1,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "ink",+ name: "Pen",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.INK ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.INK,+ strokeColor: "#1f2933",+ color: "#1f2933",+ opacity: 1,+ borderWidth: 2,+ lineWidth: 2,+ strokeWidth: 2,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "inkHighlighter",+ name: "Ink Highlighter",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.INK &&+ (annotation.strokeColor === "#ffd54f" || annotation.color === "#ffd54f")+ ? 8+ : 0,+ defaults: {+ type: PdfAnnotationSubtype.INK,+ strokeColor: "#ffd54f",+ color: "#ffd54f",+ opacity: 0.5,+ borderWidth: 6,+ lineWidth: 6,+ strokeWidth: 6,+ },+ behavior: {+ deactivateToolAfterCreate: false,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "square",+ name: "Square",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.SQUARE ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.SQUARE,+ color: "#0000ff", // fill color (blue)+ strokeColor: "#cf5b5b", // border color (reddish pink)+ opacity: 0.5,+ borderWidth: 1,+ strokeWidth: 1,+ lineWidth: 1,+ },+ clickBehavior: {+ enabled: true,+ defaultSize: { width: 120, height: 90 },+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "circle",+ name: "Circle",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.CIRCLE ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.CIRCLE,+ color: "#0000ff", // fill color (blue)+ strokeColor: "#cf5b5b", // border color (reddish pink)+ opacity: 0.5,+ borderWidth: 1,+ strokeWidth: 1,+ lineWidth: 1,+ },+ clickBehavior: {+ enabled: true,+ defaultSize: { width: 100, height: 100 },+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "line",+ name: "Line",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.LINE ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.LINE,+ color: "#1565c0",+ opacity: 1,+ borderWidth: 2,+ strokeWidth: 2,+ lineWidth: 2,+ },+ clickBehavior: {+ enabled: true,+ defaultLength: 120,+ defaultAngle: 0,+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "lineArrow",+ name: "Arrow",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) => {+ if (annotation.type !== PdfAnnotationSubtype.LINE) return 0;+ // EmbedPDF stores endStyle/lineEndingStyles at runtime; library types use lineEndings+ const ann = annotation as PdfAnnotationObject & {+ endStyle?: string;+ lineEndingStyles?: { end?: string };+ };+ return ann.endStyle === "ClosedArrow" ||+ ann.lineEndingStyles?.end === "ClosedArrow"+ ? 9+ : 0;+ },+ defaults: {+ type: PdfAnnotationSubtype.LINE,+ color: "#1565c0",+ opacity: 1,+ borderWidth: 2,+ startStyle: "None",+ endStyle: "ClosedArrow",+ lineEndingStyles: { start: "None", end: "ClosedArrow" },+ },+ clickBehavior: {+ enabled: true,+ defaultLength: 120,+ defaultAngle: 0,+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "polyline",+ name: "Polyline",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.POLYLINE ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.POLYLINE,+ color: "#1565c0",+ opacity: 1,+ borderWidth: 2,+ },+ clickBehavior: {+ enabled: true,+ finishOnDoubleClick: true,+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "polygon",+ name: "Polygon",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.POLYGON ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.POLYGON,+ color: "#0000ff", // fill color (blue)+ strokeColor: "#cf5b5b", // border color (reddish pink)+ opacity: 0.5,+ borderWidth: 1,+ },+ clickBehavior: {+ enabled: true,+ finishOnDoubleClick: true,+ defaultSize: { width: 140, height: 100 },+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "text",+ name: "Text",+ interaction: {+ exclusive: true,+ cursor: "text",+ isRotatable: false,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.FREETEXT ? 10 : 0,+ defaults: {+ type: PdfAnnotationSubtype.FREETEXT,+ textColor: "#111111",+ fontSize: 14,+ fontFamily: "Helvetica",+ opacity: 1,+ interiorColor: "#fffef7",+ contents: "Text",+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "note",+ name: "Note",+ interaction: {+ exclusive: true,+ cursor: "pointer",+ isRotatable: false,+ },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.FREETEXT ? 8 : 0,+ defaults: {+ type: PdfAnnotationSubtype.FREETEXT,+ textColor: "#1b1b1b",+ color: "#ffa000",+ interiorColor: "#fff8e1",+ opacity: 1,+ contents: "Note",+ fontSize: 12,+ },+ clickBehavior: {+ enabled: true,+ defaultSize: { width: 160, height: 100 },+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "stamp",+ name: "Image Stamp",+ interaction: { exclusive: false, cursor: "copy" },+ matchScore: (annotation: PdfAnnotationObject) =>+ annotation.type === PdfAnnotationSubtype.STAMP ? 5 : 0,+ defaults: {+ type: PdfAnnotationSubtype.STAMP,+ },+ behavior: {+ deactivateToolAfterCreate: true,+ selectAfterCreate: true,+ },+ });++ ensureTool({+ id: "signatureStamp",+ name: "Digital Signature",+ interaction: { exclusive: false, cursor: "copy" },+ matchScore: () => 0,+ defaults: {+ type: PdfAnnotationSubtype.STAMP,+ },+ });++ ensureTool({+ id: "signatureInk",+ name: "Signature Draw",+ interaction: { exclusive: true, cursor: "crosshair" },+ matchScore: () => 0,+ defaults: {+ type: PdfAnnotationSubtype.INK,+ strokeColor: "#000000",+ color: "#000000",+ opacity: 1.0,+ borderWidth: 2,+ },+ });+}diff --git a/frontend/editor/src/proprietary/App.tsx b/frontend/editor/src/proprietary/App.tsxindex b5d98c877b..673f1adc49 100644--- a/frontend/editor/src/proprietary/App.tsx+++ b/frontend/editor/src/proprietary/App.tsx@@ -49,6 +49,39 @@ function ParticipantViewPage() {return <ParticipantView token={token} />;}+function MainRoutes() {+ return (+ <Routes>+ {/* Not the app: no rail over any of these, ever. */}+ <Route element={<NoAppChrome />}>+ <Route path="/login" element={<Login />} />+ {/* Self-hosted has no signup: old links land on login. */}+ <Route path="/signup" element={<Navigate to="/login" replace />} />+ <Route path="/auth/callback" element={<AuthCallback />} />+ <Route path="/invite/:token" element={<InviteAccept />} />+ <Route path="/share/:token" element={<ShareLinkPage />} />+ </Route>+ {/* The editor and its tool routes - Landing handles auth logic */}+ <Route path="/*" element={<Landing />} />+ </Routes>+ );+}++// All other routes need AppProviders for backend integration. RootGate routes+// "/" by role before any of it mounts.+function MainApp() {+ return (+ <RootGate>+ <AppProviders>+ <AppLayout>+ <MainRoutes />+ <Onboarding />+ </AppLayout>+ </AppProviders>+ </RootGate>+ );+}+export default function App() {return (<Suspense fallback={<LoadingFallback />}>@@ -87,46 +120,7 @@ export default function App() {<Route element={<AppFrame />}>{/* The portal: its own shell, before the catch-all. An empty stub in core. */}{getAdminRouteExtensions()}-- {/* All other routes need AppProviders for backend integration. RootGate- routes "/" by role before any of it mounts. */}- <Route- path="*"- element={- <RootGate>- <AppProviders>- <AppLayout>- <Routes>- {/* Not the app: no rail over any of these, ever. */}- <Route element={<NoAppChrome />}>- <Route path="/login" element={<Login />} />- {/* Self-hosted has no signup: old links land on login. */}- <Route- path="/signup"- element={<Navigate to="/login" replace />}- />- <Route- path="/auth/callback"- element={<AuthCallback />}- />- <Route- path="/invite/:token"- element={<InviteAccept />}- />- <Route- path="/share/:token"- element={<ShareLinkPage />}- />- </Route>- {/* The editor and its tool routes - Landing handles auth logic */}- <Route path="/*" element={<Landing />} />- </Routes>- <Onboarding />- </AppLayout>- </AppProviders>- </RootGate>- }- />+ <Route path="*" element={<MainApp />} /></Route></Routes></Suspense>diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsxindex 4fa9585cbc..cd87006c9b 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsx@@ -1,5 +1,5 @@-import { useEffect, useState } from "react";-import { Icon } from "@app/ui/Icon";+import { useEffect, useState, type ReactNode } from "react";+import { Icon, type IconName } from "@app/ui/Icon";import { isAxiosError } from "axios";import { useTranslation } from "react-i18next";import {@@ -31,6 +31,454 @@ interface DatabaseBackupsCardProps {isEmbeddedH2: boolean;}+function H2OnlyNotice() {+ const { t } = useTranslation();+ return (+ <Alert icon={<Icon name="info" size="1.2rem" />} color="yellow" radius="md">+ <Text fw={600} size="sm">+ {t(+ "admin.settings.database.h2Only",+ "Backups are available only for the embedded H2 database.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {t(+ "admin.settings.database.h2Hint",+ "Set the database type to H2 and disable custom database to enable backup and restore.",+ )}+ </Text>+ </Alert>+ );+}++function BackupsPanel({ children }: { children: ReactNode }) {+ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">{children}</Stack>+ </Paper>+ );+}++interface BackupsHeaderProps {+ databaseVersion: string | null;+ disabled: boolean;+ creating: boolean;+ onRefresh: () => void;+ onCreate: () => void;+}++function BackupsHeader({+ databaseVersion,+ disabled,+ creating,+ onRefresh,+ onCreate,+}: BackupsHeaderProps) {+ const { t } = useTranslation();+ return (+ <Group justify="space-between" align="center">+ <Group gap="xs">+ <Icon name="cloud-upload" size="1.4rem" />+ <Text fw={600}>+ {t("admin.settings.database.manageBackups", "Manage backups")}+ </Text>+ <Badge color="green" variant="light" size="sm">+ {t("admin.settings.database.embedded", "Embedded H2")}+ </Badge>+ {databaseVersion && (+ <Badge color="blue" variant="light" size="sm">+ {t("admin.settings.database.version", "H2 Version")}:{" "}+ {databaseVersion}+ </Badge>+ )}+ </Group>+ <Group gap="xs">+ <Button+ variant="secondary"+ leftSection={<Icon name="refresh-cw" size="1rem" />}+ onClick={onRefresh}+ disabled={disabled}+ >+ {t("admin.settings.database.refresh", "Refresh")}+ </Button>+ <Button+ leftSection={<Icon name="upload" size="1rem" />}+ onClick={onCreate}+ loading={creating}+ disabled={disabled}+ >+ {t("admin.settings.database.createBackup", "Create backup")}+ </Button>+ </Group>+ </Group>+ );+}++interface UploadImportFormProps {+ file: File | null;+ onFileChange: (file: File | null) => void;+ importing: boolean;+ disabled: boolean;+ onImport: () => void;+}++function UploadImportForm({+ file,+ onFileChange,+ importing,+ disabled,+ onImport,+}: UploadImportFormProps) {+ const { t } = useTranslation();+ return (+ <Box>+ <Text fw={500} size="sm" mb={6}>+ {t("admin.settings.database.uploadTitle", "Upload & import")}+ </Text>+ <Group gap="sm" align="flex-end" wrap="wrap">+ <FileInput+ value={file}+ onChange={onFileChange}+ placeholder={t(+ "admin.settings.database.chooseFile",+ "Choose a .sql backup file",+ )}+ accept=".sql"+ disabled={disabled}+ styles={{ input: { minWidth: 280 } }}+ />+ <Button+ variant="secondary"+ onClick={onImport}+ loading={importing}+ disabled={disabled}+ leftSection={<Icon name="circle-play" size="1rem" />}+ >+ {t("admin.settings.database.importFromUpload", "Import upload")}+ </Button>+ </Group>+ </Box>+ );+}++interface BackupActionButtonProps {+ label: string;+ icon: IconName;+ busy: boolean;+ disabled: boolean;+ danger?: boolean;+ onClick: () => void;+}++function BackupActionButton({+ label,+ icon,+ busy,+ disabled,+ danger = false,+ onClick,+}: BackupActionButtonProps) {+ return (+ <Tooltip label={label} withArrow>+ <ActionIcon+ variant="tertiary"+ accent={danger ? "danger" : undefined}+ onClick={onClick}+ disabled={disabled}+ aria-label={label}+ >+ {busy ? <Loader size="xs" /> : <Icon name={icon} size="1rem" />}+ </ActionIcon>+ </Tooltip>+ );+}++interface BackupRowProps {+ backup: DatabaseBackupFile;+ disabled: boolean;+ downloading: boolean;+ importing: boolean;+ deleting: boolean;+ onDownload: () => void;+ onImport: () => void;+ onDelete: () => void;+}++function BackupRow({+ backup,+ disabled,+ downloading,+ importing,+ deleting,+ onDownload,+ onImport,+ onDelete,+}: BackupRowProps) {+ const { t } = useTranslation();+ return (+ <Table.Tr>+ <Table.Td>{backup.fileName}</Table.Td>+ <Table.Td>+ {backup.formattedCreationDate || backup.creationDate || "-"}+ </Table.Td>+ <Table.Td>{backup.formattedFileSize || "-"}</Table.Td>+ <Table.Td>+ <Group gap="xs" justify="flex-start">+ <BackupActionButton+ label={t("admin.settings.database.download", "Download")}+ icon="download"+ busy={downloading}+ disabled={disabled}+ onClick={onDownload}+ />+ <BackupActionButton+ label={t("admin.settings.database.import", "Import")}+ icon="cloud-upload"+ busy={importing}+ disabled={disabled}+ onClick={onImport}+ />+ <BackupActionButton+ label={t("admin.settings.database.delete", "Delete")}+ icon="trash"+ danger+ busy={deleting}+ disabled={disabled}+ onClick={onDelete}+ />+ </Group>+ </Table.Td>+ </Table.Tr>+ );+}++interface BackupsTableProps {+ backups: DatabaseBackupFile[];+ disabled: boolean;+ downloadingFile: string | null;+ importingFile: string | null;+ deletingFile: string | null;+ onDownload: (fileName: string) => void;+ onImport: (fileName: string) => void;+ onDelete: (fileName: string) => void;+}++function BackupsTable({+ backups,+ disabled,+ downloadingFile,+ importingFile,+ deletingFile,+ onDownload,+ onImport,+ onDelete,+}: BackupsTableProps) {+ const { t } = useTranslation();+ return (+ <Table highlightOnHover withColumnBorders verticalSpacing="sm">+ <Table.Thead>+ <Table.Tr>+ <Table.Th>{t("admin.settings.database.fileName", "File")}</Table.Th>+ <Table.Th>{t("admin.settings.database.created", "Created")}</Table.Th>+ <Table.Th>{t("admin.settings.database.size", "Size")}</Table.Th>+ <Table.Th w={150}>+ {t("admin.settings.database.actions", "Actions")}+ </Table.Th>+ </Table.Tr>+ </Table.Thead>+ <Table.Tbody>+ {backups.map((backup) => (+ <BackupRow+ key={backup.fileName}+ backup={backup}+ disabled={disabled}+ downloading={downloadingFile === backup.fileName}+ importing={importingFile === backup.fileName}+ deleting={deletingFile === backup.fileName}+ onDownload={() => onDownload(backup.fileName)}+ onImport={() => onImport(backup.fileName)}+ onDelete={() => onDelete(backup.fileName)}+ />+ ))}+ </Table.Tbody>+ </Table>+ );+}++function BackupList({+ loading,+ ...table+}: BackupsTableProps & { loading: boolean }) {+ const { t } = useTranslation();+ if (loading) {+ return (+ <Group justify="center" py="md">+ <Loader size="sm" />+ </Group>+ );+ }+ if (table.backups.length === 0) {+ return (+ <Text size="sm" c="dimmed">+ {t("admin.settings.database.noBackups", "No backups found yet.")}+ </Text>+ );+ }+ return <BackupsTable {...table} />;+}++interface ConfirmImportModalProps {+ opened: boolean;+ onClose: () => void;+ code: string;+ input: string;+ onInputChange: (value: string) => void;+ importing: boolean;+ onConfirm: () => void;+}++function ConfirmImportModal({+ opened,+ onClose,+ code,+ input,+ onInputChange,+ importing,+ onConfirm,+}: ConfirmImportModalProps) {+ const { t } = useTranslation();+ return (+ <Modal+ opened={opened}+ onClose={onClose}+ title={t(+ "admin.settings.database.confirmImportTitle",+ "Confirm database import",+ )}+ centered+ withinPortal+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ >+ <Stack gap="md">+ <Alert+ color="red"+ variant="light"+ icon={<Icon name="triangle-alert" size="1.2rem" />}+ >+ <Text fw={600}>+ {t(+ "admin.settings.database.overwriteWarning",+ "Warning: This will overwrite the current database.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {t(+ "admin.settings.database.overwriteWarningBody",+ "All existing data will be replaced by the uploaded backup. This action cannot be undone.",+ )}+ </Text>+ </Alert>+ <Stack gap={6}>+ <Text size="sm" fw={600}>+ {t(+ "admin.settings.database.confirmCodeLabel",+ "Enter the confirmation code to proceed",+ )}+ </Text>+ <Text size="lg" fw={700}>+ {code}+ </Text>+ <TextInput+ value={input}+ onChange={(e) => onInputChange(e.currentTarget.value)}+ placeholder={t(+ "admin.settings.database.enterCode",+ "Enter the code shown above",+ )}+ minLength={4}+ maxLength={4}+ disabled={importing}+ />+ </Stack>+ <Group justify="flex-end" gap="sm">+ <Button variant="secondary" onClick={onClose} disabled={importing}>+ {t("cancel", "Cancel")}+ </Button>+ <Button+ accent="danger"+ onClick={onConfirm}+ loading={importing}+ disabled={input.length === 0}+ >+ {t("admin.settings.database.confirmImport", "Confirm import")}+ </Button>+ </Group>+ </Stack>+ </Modal>+ );+}++interface DeleteBackupModalProps {+ /** The backup awaiting confirmation; null keeps the modal closed. */+ fileName: string | null;+ deletingFile: string | null;+ onClose: () => void;+ onConfirm: (fileName: string) => void;+}++function DeleteBackupModal({+ fileName,+ deletingFile,+ onClose,+ onConfirm,+}: DeleteBackupModalProps) {+ const { t } = useTranslation();+ return (+ <Modal+ opened={fileName !== null}+ onClose={onClose}+ title={t("admin.settings.database.deleteTitle", "Delete backup")}+ centered+ withinPortal+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ >+ <Stack gap="md">+ <Alert+ color="red"+ variant="light"+ icon={<Icon name="triangle-alert" size="1.2rem" />}+ >+ <Text fw={600}>+ {t(+ "admin.settings.database.deleteConfirm",+ "Delete this backup? This cannot be undone.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {fileName}+ </Text>+ </Alert>+ <Group justify="flex-end" gap="sm">+ <Button+ variant="secondary"+ onClick={onClose}+ disabled={deletingFile !== null}+ >+ {t("cancel", "Cancel")}+ </Button>+ <Button+ accent="danger"+ onClick={() => fileName && onConfirm(fileName)}+ loading={deletingFile === fileName}+ >+ {t("admin.settings.database.deleteConfirmAction", "Delete backup")}+ </Button>+ </Group>+ </Stack>+ </Modal>+ );+}+/*** Instant CRUD over the H2 backup files: nothing here belongs to the settings* draft, so this card owns its own state and never touches Save or Discard.@@ -310,353 +758,60 @@ export function DatabaseBackupsCard({}};+ const actionsDisabled = !loginEnabled || !isEmbeddedH2;+return (<><Stack gap="md">- {!isEmbeddedH2 && (- <Alert- icon={<Icon name="info" size="1.2rem" />}- color="yellow"- radius="md"- >- <Text fw={600} size="sm">- {t(- "admin.settings.database.h2Only",- "Backups are available only for the embedded H2 database.",- )}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.h2Hint",- "Set the database type to H2 and disable custom database to enable backup and restore.",- )}- </Text>- </Alert>- )}- {isEmbeddedH2 && (- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Group gap="xs">- <Icon name="cloud-upload" size="1.4rem" />- <Text fw={600}>- {t(- "admin.settings.database.manageBackups",- "Manage backups",- )}- </Text>- <Badge color="green" variant="light" size="sm">- {t("admin.settings.database.embedded", "Embedded H2")}- </Badge>- {databaseVersion && (- <Badge color="blue" variant="light" size="sm">- {t("admin.settings.database.version", "H2 Version")}:{" "}- {databaseVersion}- </Badge>- )}- </Group>- <Group gap="xs">- <Button- variant="secondary"- leftSection={<Icon name="refresh-cw" size="1rem" />}- onClick={loadBackupData}- disabled={!loginEnabled || !isEmbeddedH2}- >- {t("admin.settings.database.refresh", "Refresh")}- </Button>- <Button- leftSection={<Icon name="upload" size="1rem" />}- onClick={handleCreateBackup}- loading={creatingBackup}- disabled={!loginEnabled || !isEmbeddedH2}- >- {t("admin.settings.database.createBackup", "Create backup")}- </Button>- </Group>- </Group>-- <Box>- <Text fw={500} size="sm" mb={6}>- {t("admin.settings.database.uploadTitle", "Upload & import")}- </Text>- <Group gap="sm" align="flex-end" wrap="wrap">- <FileInput- value={uploadFile}- onChange={setUploadFile}- placeholder={t(- "admin.settings.database.chooseFile",- "Choose a .sql backup file",- )}- accept=".sql"- disabled={!loginEnabled || !isEmbeddedH2}- styles={{ input: { minWidth: 280 } }}- />- <Button- variant="secondary"- onClick={handleUploadImport}- loading={importingUpload}- disabled={!loginEnabled || !isEmbeddedH2}- leftSection={<Icon name="circle-play" size="1rem" />}- >- {t(- "admin.settings.database.importFromUpload",- "Import upload",- )}- </Button>- </Group>- </Box>-- {backupsLoading ? (- <Group justify="center" py="md">- <Loader size="sm" />- </Group>- ) : backupFiles.length === 0 ? (- <Text size="sm" c="dimmed">- {isEmbeddedH2- ? t(- "admin.settings.database.noBackups",- "No backups found yet.",- )- : t(- "admin.settings.database.unavailable",- "Backup list unavailable for the current database configuration.",- )}- </Text>- ) : (- <Table highlightOnHover withColumnBorders verticalSpacing="sm">- <Table.Thead>- <Table.Tr>- <Table.Th>- {t("admin.settings.database.fileName", "File")}- </Table.Th>- <Table.Th>- {t("admin.settings.database.created", "Created")}- </Table.Th>- <Table.Th>- {t("admin.settings.database.size", "Size")}- </Table.Th>- <Table.Th w={150}>- {t("admin.settings.database.actions", "Actions")}- </Table.Th>- </Table.Tr>- </Table.Thead>- <Table.Tbody>- {backupFiles.map((backup) => (- <Table.Tr key={backup.fileName}>- <Table.Td>{backup.fileName}</Table.Td>- <Table.Td>- {backup.formattedCreationDate ||- backup.creationDate ||- "-"}- </Table.Td>- <Table.Td>{backup.formattedFileSize || "-"}</Table.Td>- <Table.Td>- <Group gap="xs" justify="flex-start">- <Tooltip- label={t(- "admin.settings.database.download",- "Download",- )}- withArrow- >- <ActionIcon- variant="tertiary"- onClick={() => handleDownload(backup.fileName)}- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.download",- "Download",- )}- >- {downloadingFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <Icon name="download" size="1rem" />- )}- </ActionIcon>- </Tooltip>- <Tooltip- label={t(- "admin.settings.database.import",- "Import",- )}- withArrow- >- <ActionIcon- variant="tertiary"- onClick={() =>- handleImportExisting(backup.fileName)- }- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.import",- "Import",- )}- >- {importingBackupFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <Icon name="cloud-upload" size="1rem" />- )}- </ActionIcon>- </Tooltip>- <Tooltip- label={t(- "admin.settings.database.delete",- "Delete",- )}- withArrow- >- <ActionIcon- variant="tertiary"- accent="danger"- onClick={() =>- handleDeleteClick(backup.fileName)- }- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.delete",- "Delete",- )}- >- {deletingFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <Icon name="trash" size="1rem" />- )}- </ActionIcon>- </Tooltip>- </Group>- </Table.Td>- </Table.Tr>- ))}- </Table.Tbody>- </Table>- )}- </Stack>- </Paper>+ {isEmbeddedH2 ? (+ <BackupsPanel>+ <BackupsHeader+ databaseVersion={databaseVersion}+ disabled={actionsDisabled}+ creating={creatingBackup}+ onRefresh={loadBackupData}+ onCreate={handleCreateBackup}+ />+ <UploadImportForm+ file={uploadFile}+ onFileChange={setUploadFile}+ importing={importingUpload}+ disabled={actionsDisabled}+ onImport={handleUploadImport}+ />+ <BackupList+ loading={backupsLoading}+ backups={backupFiles}+ disabled={actionsDisabled}+ downloadingFile={downloadingFile}+ importingFile={importingBackupFile}+ deletingFile={deletingFile}+ onDownload={handleDownload}+ onImport={handleImportExisting}+ onDelete={handleDeleteClick}+ />+ </BackupsPanel>+ ) : (+ <H2OnlyNotice />)}</Stack>- <Modal+ <ConfirmImportModalopened={confirmImportOpen}onClose={closeConfirmImportModal}- title={t(- "admin.settings.database.confirmImportTitle",- "Confirm database import",- )}- centered- withinPortal- zIndex={Z_INDEX_OVER_CONFIG_MODAL}- >- <Stack gap="md">- <Alert- color="red"- variant="light"- icon={<Icon name="triangle-alert" size="1.2rem" />}- >- <Text fw={600}>- {t(- "admin.settings.database.overwriteWarning",- "Warning: This will overwrite the current database.",- )}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.overwriteWarningBody",- "All existing data will be replaced by the uploaded backup. This action cannot be undone.",- )}- </Text>- </Alert>- <Stack gap={6}>- <Text size="sm" fw={600}>- {t(- "admin.settings.database.confirmCodeLabel",- "Enter the confirmation code to proceed",- )}- </Text>- <Text size="lg" fw={700}>- {confirmCode}- </Text>- <TextInput- value={confirmInput}- onChange={(e) => setConfirmInput(e.currentTarget.value)}- placeholder={t(- "admin.settings.database.enterCode",- "Enter the code shown above",- )}- minLength={4}- maxLength={4}- disabled={importingUpload}- />- </Stack>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={closeConfirmImportModal}- disabled={importingUpload}- >- {t("cancel", "Cancel")}- </Button>- <Button- accent="danger"- onClick={handleConfirmImport}- loading={importingUpload}- disabled={confirmInput.length === 0}- >- {t("admin.settings.database.confirmImport", "Confirm import")}- </Button>- </Group>- </Stack>- </Modal>+ code={confirmCode}+ input={confirmInput}+ onInputChange={setConfirmInput}+ importing={importingUpload}+ onConfirm={handleConfirmImport}+ />- <Modal- opened={deleteConfirmFile !== null}+ <DeleteBackupModal+ fileName={deleteConfirmFile}+ deletingFile={deletingFile}onClose={() => setDeleteConfirmFile(null)}- title={t("admin.settings.database.deleteTitle", "Delete backup")}- centered- withinPortal- zIndex={Z_INDEX_OVER_CONFIG_MODAL}- >- <Stack gap="md">- <Alert- color="red"- variant="light"- icon={<Icon name="triangle-alert" size="1.2rem" />}- >- <Text fw={600}>- {t(- "admin.settings.database.deleteConfirm",- "Delete this backup? This cannot be undone.",- )}- </Text>- <Text size="sm" c="dimmed">- {deleteConfirmFile}- </Text>- </Alert>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={() => setDeleteConfirmFile(null)}- disabled={deletingFile !== null}- >- {t("cancel", "Cancel")}- </Button>- <Button- accent="danger"- onClick={() =>- deleteConfirmFile && handleDelete(deleteConfirmFile)- }- loading={deletingFile === deleteConfirmFile}- >- {t(- "admin.settings.database.deleteConfirmAction",- "Delete backup",- )}- </Button>- </Group>- </Stack>- </Modal>+ onConfirm={handleDelete}+ /></>);}diff --git a/frontend/editor/src/saas/App.tsx b/frontend/editor/src/saas/App.tsxindex 07a563ea5f..0acf378e71 100644--- a/frontend/editor/src/saas/App.tsx+++ b/frontend/editor/src/saas/App.tsx@@ -72,6 +72,51 @@ function NonAuthBootstraps() {);}+function MainRoutes() {+ return (+ <Routes>+ {/* Not the app: no rail over any of these, ever. */}+ <Route element={<NoAppChrome />}>+ <Route path="/login" element={<Login />} />+ <Route path="/signup" element={<Signup />} />+ <Route path="/auth/callback" element={<AuthCallback />} />+ <Route path="/auth/reset" element={<ResetPassword />} />+ <Route path="/oauth/consent" element={<OAuthConsent />} />+ {/* Human half of the self-hosted account-link handshake. It lives on+ this origin because a customer hostname can never be in the+ provider's redirect allow-list. Grouped with the pages above: it is+ an approval step, not the app. */}+ <Route path="/link" element={<ConnectApprove />} />+ {/* Shared-file links. Team invites are NOT routed here: on SaaS they+ are accepted in-app via the Supabase team invitation banner, not the+ Spring password-based /invite/:token page used by the self-hosted+ build. */}+ <Route path="/share/:token" element={<ShareLinkPage />} />+ </Route>+ <Route path="/*" element={<Landing />} />+ </Routes>+ );+}++// Everything else needs the auth/backend providers. RootGate routes "/" by role+// before any of it mounts.+function MainApp() {+ return (+ <RootGate>+ <AppProviders+ appConfigProviderProps={{ onConfigLoaded: handleConfigLoaded }}+ >+ <AppLayout>+ <NonAuthBootstraps />+ <ResumePendingConnect />+ <MainRoutes />+ <OnboardingTour />+ </AppLayout>+ </AppProviders>+ </RootGate>+ );+}+export default function App() {return (<Suspense fallback={<LoadingFallback />}>@@ -102,58 +147,7 @@ export default function App() {<Route element={<AppFrame />}>{/* The portal: its own top-level shell, before the catch-all. */}{getAdminRouteExtensions()}-- {/* Everything else needs the auth/backend providers. RootGate routes "/"- by role before any of it mounts. */}- <Route- path="*"- element={- <RootGate>- <AppProviders- appConfigProviderProps={{- onConfigLoaded: handleConfigLoaded,- }}- >- <AppLayout>- <NonAuthBootstraps />- <ResumePendingConnect />- <Routes>- {/* Not the app: no rail over any of these, ever. */}- <Route element={<NoAppChrome />}>- <Route path="/login" element={<Login />} />- <Route path="/signup" element={<Signup />} />- <Route- path="/auth/callback"- element={<AuthCallback />}- />- <Route path="/auth/reset" element={<ResetPassword />} />- <Route- path="/oauth/consent"- element={<OAuthConsent />}- />- {/* Human half of the self-hosted account-link handshake.- It lives on this origin because a customer hostname can- never be in the provider's redirect allow-list. Grouped- with the pages above: it is an approval step, not the- app. */}- <Route path="/link" element={<ConnectApprove />} />- {/* Shared-file links. Team invites are NOT routed here:- on SaaS they are accepted in-app via the Supabase team- invitation banner, not the Spring password-based- /invite/:token page used by the self-hosted build. */}- <Route- path="/share/:token"- element={<ShareLinkPage />}- />- </Route>- <Route path="/*" element={<Landing />} />- </Routes>- <OnboardingTour />- </AppLayout>- </AppProviders>- </RootGate>- }- />+ <Route path="*" element={<MainApp />} /></Route></Routes></Suspense>diff --git a/frontend/oxlint.config.ts b/frontend/oxlint.config.tsindex 336d1affaa..abe882f2b1 100644--- a/frontend/oxlint.config.ts+++ b/frontend/oxlint.config.ts@@ -73,7 +73,7 @@ const modernGlobals: OxlintGlobals = {};export default defineConfig({- plugins: ["typescript", "import"],+ plugins: ["typescript", "import", "react"],options: {typeAware: true,},@@ -199,6 +199,7 @@ export default defineConfig({"typescript/prefer-as-const": "error","typescript/prefer-namespace-keyword": "error","typescript/triple-slash-reference": "error",+ "react/jsx-max-depth": ["error", { max: 10 }],},overrides: [{@@ -383,6 +384,14 @@ export default defineConfig({],},},+ {+ // A provider stack nests one context per level in dependency order, so its+ // depth counts providers rather than measuring how hard the tree is to read.+ files: ["editor/src/core/components/AppProviders.tsx"],+ rules: {+ "react/jsx-max-depth": "off",+ },+ },{// Circular-import detection across the editor app source (the import// plugin resolves @app/* and the other tsconfig path aliases). Replaces