Skip to content

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

Set max JSX depth to 8 (#8187)

James Brunton4c6aa3e11e5c
diff --git a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
index 1a63418c0d..e6d751904a 100644
--- a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
+++ b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
@@ -90,27 +90,10 @@ export default function OnboardingSlideShell({
}: OnboardingSlideShellProps) {
const { t } = useTranslation();
const showProgress = stepCount > 1;
-
- // Back/icon buttons anchor the left; text actions cluster on the right.
- // A back control can't do anything on the first slide, so hide it there.
- const backButtons = stepIndex === 0 ? [] : buttons.filter((b) => b.back);
- const actionButtons = buttons.filter((b) => !b.back);
-
- const renderButton = (button: ShellButton) => (
- <Button
- key={button.key}
- onClick={() => onAction(button.action)}
- disabled={button.disabled}
- variant={button.primary ? "primary" : "quiet"}
- accent={button.accent ?? (button.primary ? "default" : "neutral")}
- >
- {button.label}
- </Button>
- );
-
- const actions = (
- <div className={styles.footerGroup}>{actionButtons.map(renderButton)}</div>
- );
+ const stepLabel = t("onboarding.stepOf", "Step {{current}} of {{total}}", {
+ current: stepIndex + 1,
+ total: stepCount,
+ });
return (
// Composed rather than the plain <Modal>, because only Modal.Content lands
@@ -142,72 +125,19 @@ export default function OnboardingSlideShell({
>
<Modal.Body>
<div className={styles.card}>
- <header className={styles.header}>
- <div className={styles.brand}>
- <img
- src={stirlingMark}
- alt=""
- aria-hidden="true"
- className={styles.brandLogo}
- />
- <span className={styles.wordmark}>Stirling</span>
- </div>
- <div className={styles.headerRight}>
- {showProgress && (
- <span className={styles.stepPill}>
- {t("onboarding.stepOf", "Step {{current}} of {{total}}", {
- current: stepIndex + 1,
- total: stepCount,
- })}
- </span>
- )}
- {(allowDismiss || headerControl === "forward") && (
- <ActionIcon
- onClick={onClose}
- variant="tertiary"
- accent="neutral"
- size="md"
- aria-label={
- headerControl === "forward"
- ? t("onboarding.buttons.continue", "Continue")
- : t("common.close", "Close")
- }
- >
- {headerControl === "forward" ? (
- <Icon name="arrow-right" size="1.1rem" />
- ) : (
- <Icon name="x" size="1.1rem" />
- )}
- </ActionIcon>
- )}
- </div>
- </header>
+ <ShellHeader
+ stepLabel={showProgress ? stepLabel : null}
+ showClose={allowDismiss}
+ headerControl={headerControl}
+ onClose={onClose}
+ />
{showProgress && (
- <div
- className={styles.progressTrack}
- role="progressbar"
- aria-valuenow={stepIndex + 1}
- aria-valuemin={1}
- aria-valuemax={stepCount}
- aria-label={t(
- "onboarding.stepOf",
- "Step {{current}} of {{total}}",
- {
- current: stepIndex + 1,
- total: stepCount,
- },
- )}
- >
- {Array.from({ length: stepCount }, (_, index) => (
- <span
- key={index}
- className={`${styles.progressSeg} ${
- index <= stepIndex ? styles.progressSegDone : ""
- }`}
- />
- ))}
- </div>
+ <StepProgress
+ stepIndex={stepIndex}
+ stepCount={stepCount}
+ label={stepLabel}
+ />
)}
<div className={styles.divider} />
@@ -232,29 +162,11 @@ export default function OnboardingSlideShell({
<style>{`.${styles.bodyNew} strong{color: var(--c-text); font-weight: 600;}`}</style>
</div>
- <div className={styles.footer}>
- {backButtons.length === 0 ? (
- <div className={styles.footerEnd}>{actions}</div>
- ) : (
- <div className={styles.footerBetween}>
- <div className={styles.footerGroup}>
- {backButtons.map((button) => (
- <ActionIcon
- key={button.key}
- onClick={() => onAction(button.action)}
- variant="tertiary"
- accent="neutral"
- disabled={button.disabled}
- aria-label={t("onboarding.buttons.back", "Back")}
- >
- <Icon name="chevron-left" size={20} />
- </ActionIcon>
- ))}
- </div>
- {actions}
- </div>
- )}
- </div>
+ <ShellFooter
+ buttons={buttons}
+ stepIndex={stepIndex}
+ onAction={onAction}
+ />
</div>
</div>
</Modal.Body>
@@ -262,3 +174,156 @@ export default function OnboardingSlideShell({
</Modal.Root>
);
}
+
+interface ShellHeaderProps {
+ stepLabel: string | null;
+ showClose: boolean;
+ headerControl: "close" | "forward";
+ onClose: () => void;
+}
+
+function ShellHeader({
+ stepLabel,
+ showClose,
+ headerControl,
+ onClose,
+}: ShellHeaderProps) {
+ return (
+ <header className={styles.header}>
+ <div className={styles.brand}>
+ <img
+ src={stirlingMark}
+ alt=""
+ aria-hidden="true"
+ className={styles.brandLogo}
+ />
+ <span className={styles.wordmark}>Stirling</span>
+ </div>
+ <div className={styles.headerRight}>
+ {stepLabel && <span className={styles.stepPill}>{stepLabel}</span>}
+ <HeaderControl
+ showClose={showClose}
+ headerControl={headerControl}
+ onClose={onClose}
+ />
+ </div>
+ </header>
+ );
+}
+
+function HeaderControl({
+ showClose,
+ headerControl,
+ onClose,
+}: Omit<ShellHeaderProps, "stepLabel">) {
+ const { t } = useTranslation();
+ const forward = headerControl === "forward";
+ if (!showClose && !forward) return null;
+ return (
+ <ActionIcon
+ onClick={onClose}
+ variant="tertiary"
+ accent="neutral"
+ size="md"
+ aria-label={
+ forward
+ ? t("onboarding.buttons.continue", "Continue")
+ : t("common.close", "Close")
+ }
+ >
+ <Icon name={forward ? "arrow-right" : "x"} size="1.1rem" />
+ </ActionIcon>
+ );
+}
+
+function StepProgress({
+ stepIndex,
+ stepCount,
+ label,
+}: {
+ stepIndex: number;
+ stepCount: number;
+ label: string;
+}) {
+ return (
+ <div
+ className={styles.progressTrack}
+ role="progressbar"
+ aria-valuenow={stepIndex + 1}
+ aria-valuemin={1}
+ aria-valuemax={stepCount}
+ aria-label={label}
+ >
+ {Array.from({ length: stepCount }, (_, index) => (
+ <span
+ key={index}
+ className={`${styles.progressSeg} ${
+ index <= stepIndex ? styles.progressSegDone : ""
+ }`}
+ />
+ ))}
+ </div>
+ );
+}
+
+function ShellFooter({
+ buttons,
+ stepIndex,
+ onAction,
+}: {
+ buttons: ShellButton[];
+ stepIndex: number;
+ onAction: (action: string) => void;
+}) {
+ const { t } = useTranslation();
+
+ // Back/icon buttons anchor the left; text actions cluster on the right.
+ // A back control can't do anything on the first slide, so hide it there.
+ const backButtons = stepIndex === 0 ? [] : buttons.filter((b) => b.back);
+ const actionButtons = buttons.filter((b) => !b.back);
+
+ const actions = (
+ <div className={styles.footerGroup}>
+ {actionButtons.map((button) => (
+ <Button
+ key={button.key}
+ onClick={() => onAction(button.action)}
+ disabled={button.disabled}
+ variant={button.primary ? "primary" : "quiet"}
+ accent={button.accent ?? (button.primary ? "default" : "neutral")}
+ >
+ {button.label}
+ </Button>
+ ))}
+ </div>
+ );
+
+ if (backButtons.length === 0) {
+ return (
+ <div className={styles.footer}>
+ <div className={styles.footerEnd}>{actions}</div>
+ </div>
+ );
+ }
+ return (
+ <div className={styles.footer}>
+ <div className={styles.footerBetween}>
+ <div className={styles.footerGroup}>
+ {backButtons.map((button) => (
+ <ActionIcon
+ key={button.key}
+ onClick={() => onAction(button.action)}
+ variant="tertiary"
+ accent="neutral"
+ disabled={button.disabled}
+ aria-label={t("onboarding.buttons.back", "Back")}
+ >
+ <Icon name="chevron-left" size={20} />
+ </ActionIcon>
+ ))}
+ </div>
+ {actions}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/FilePickerModal.tsx b/frontend/editor/src/core/components/shared/FilePickerModal.tsx
index 10fdfa228a..8de6c8dd7d 100644
--- a/frontend/editor/src/core/components/shared/FilePickerModal.tsx
+++ b/frontend/editor/src/core/components/shared/FilePickerModal.tsx
@@ -31,6 +31,223 @@ interface FilePickerModalProps {
onSelectFiles: (selectedFiles: File[]) => void;
}
+function formatFileSize(bytes: number): string {
+ if (bytes === 0) return "0 B";
+ const k = 1024;
+ const sizes = ["B", "KB", "MB", "GB"];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
+}
+
+interface SelectionControlsProps {
+ total: number;
+ selectedCount: number;
+ onSelectAll: () => void;
+ onSelectNone: () => void;
+}
+
+function SelectionControls({
+ total,
+ selectedCount,
+ onSelectAll,
+ onSelectNone,
+}: SelectionControlsProps) {
+ const { t } = useTranslation();
+ return (
+ <Group justify="space-between">
+ <Text size="sm" c="dimmed">
+ {t("fileUpload.filesAvailableCount", {
+ count: total,
+ defaultValue_one: "{{count}} file available",
+ defaultValue_other: "{{count}} files available",
+ })}
+ {selectedCount > 0 && (
+ <>
+ {" • "}
+ {t("fileUpload.selectedCount", "{{count}} selected", {
+ count: selectedCount,
+ })}
+ </>
+ )}
+ </Text>
+ <Group gap="xs">
+ <Button size="sm" variant="secondary" onClick={onSelectAll}>
+ {t("pageEdit.selectAll", "Select All")}
+ </Button>
+ <Button size="sm" variant="secondary" onClick={onSelectNone}>
+ {t("pageEdit.deselectAll", "Select None")}
+ </Button>
+ </Group>
+ </Group>
+ );
+}
+
+interface StoredFileCardProps {
+ file: StoredFileItem;
+ selected: boolean;
+ onToggle: () => void;
+}
+
+function StoredFileCard({ file, selected, onToggle }: StoredFileCardProps) {
+ const { t } = useTranslation();
+ return (
+ <Box
+ p="sm"
+ style={{
+ border: selected
+ ? "2px solid var(--mantine-color-blue-6)"
+ : "1px solid var(--mantine-color-gray-3)",
+ borderRadius: 8,
+ backgroundColor: selected
+ ? "var(--mantine-color-blue-0)"
+ : "transparent",
+ cursor: "pointer",
+ transition: "all 0.2s ease",
+ }}
+ onClick={onToggle}
+ >
+ <Group gap="sm" align="flex-start">
+ <Checkbox
+ checked={selected}
+ onChange={onToggle}
+ onClick={(e) => e.stopPropagation()}
+ aria-label={t("fileUpload.selectFile", "Select {{name}}", {
+ name: file.name,
+ })}
+ />
+ <Box
+ style={{
+ width: 60,
+ height: 80,
+ border: "1px solid var(--mantine-color-gray-3)",
+ borderRadius: 4,
+ backgroundColor: "white",
+ flexShrink: 0,
+ overflow: "hidden",
+ }}
+ >
+ <DocumentThumbnail
+ file={file.file ?? null}
+ thumbnail={
+ file.processedFile?.isEncrypted ? undefined : file.thumbnail
+ }
+ isEncrypted={Boolean(file.processedFile?.isEncrypted)}
+ iconSize="2rem"
+ />
+ </Box>
+ <Stack gap="xs" style={{ flex: 1, minWidth: 0 }}>
+ <Text size="sm" fw={500} lineClamp={2}>
+ {file.name}
+ </Text>
+ <Group gap="xs">
+ <Badge size="xs" variant="light" color="gray">
+ {formatFileSize(file.size || file.file?.size || 0)}
+ </Badge>
+ </Group>
+ </Stack>
+ </Group>
+ </Box>
+ );
+}
+
+interface StoredFileGridProps {
+ files: StoredFileItem[];
+ selectedIds: FileId[];
+ onToggle: (fileId: FileId) => void;
+}
+
+function StoredFileGrid({ files, selectedIds, onToggle }: StoredFileGridProps) {
+ return (
+ <ScrollArea.Autosize mah={400}>
+ <SimpleGrid cols={2} spacing="md">
+ {files.map((file) => (
+ <StoredFileCard
+ key={file.id}
+ file={file}
+ selected={selectedIds.includes(file.id)}
+ onToggle={() => onToggle(file.id)}
+ />
+ ))}
+ </SimpleGrid>
+ </ScrollArea.Autosize>
+ );
+}
+
+function SelectionSummary({ count }: { count: number }) {
+ const { t } = useTranslation();
+ if (count === 0) return null;
+ return (
+ <Text size="sm" c="var(--c-accent-text)" ta="center">
+ {count} {t("fileManager.filesSelected", "files selected")}
+ </Text>
+ );
+}
+
+interface StoredFileBrowserProps extends StoredFileGridProps {
+ onSelectAll: () => void;
+ onSelectNone: () => void;
+}
+
+function StoredFileBrowser({
+ files,
+ selectedIds,
+ onToggle,
+ onSelectAll,
+ onSelectNone,
+}: StoredFileBrowserProps) {
+ const terminology = useFileActionTerminology();
+ if (files.length === 0) {
+ return (
+ <Text c="dimmed" ta="center" py="xl">
+ {terminology.noFilesInStorage}
+ </Text>
+ );
+ }
+ return (
+ <>
+ <SelectionControls
+ total={files.length}
+ selectedCount={selectedIds.length}
+ onSelectAll={onSelectAll}
+ onSelectNone={onSelectNone}
+ />
+ <StoredFileGrid
+ files={files}
+ selectedIds={selectedIds}
+ onToggle={onToggle}
+ />
+ <SelectionSummary count={selectedIds.length} />
+ </>
+ );
+}
+
+interface PickerActionsProps {
+ selectedCount: number;
+ onCancel: () => void;
+ onConfirm: () => void;
+}
+
+function PickerActions({
+ selectedCount,
+ onCancel,
+ onConfirm,
+}: PickerActionsProps) {
+ const { t } = useTranslation();
+ const terminology = useFileActionTerminology();
+ return (
+ <Group justify="flex-end" mt="md">
+ <Button variant="secondary" onClick={onCancel}>
+ {t("close", "Cancel")}
+ </Button>
+ <Button onClick={onConfirm} disabled={selectedCount === 0}>
+ {selectedCount > 0
+ ? `${t("fileUpload.loadFromStorage", "Load")} ${selectedCount} ${terminology.uploadFiles}`
+ : t("fileUpload.loadFromStorage", "Load Files")}
+ </Button>
+ </Group>
+ );
+}
+
const FilePickerModal = ({
opened,
onClose,
@@ -38,7 +255,6 @@ const FilePickerModal = ({
onSelectFiles,
}: FilePickerModalProps) => {
const { t } = useTranslation();
- const terminology = useFileActionTerminology();
const [selectedFileIds, setSelectedFileIds] = useState<FileId[]>([]);
// Reset selection when modal opens
@@ -125,14 +341,6 @@ const FilePickerModal = ({
onClose();
};
- const formatFileSize = (bytes: number) => {
- if (bytes === 0) return "0 B";
- const k = 1024;
- const sizes = ["B", "KB", "MB", "GB"];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
- };
-
return (
<Modal
opened={opened}
@@ -143,147 +351,18 @@ const FilePickerModal = ({
zIndex={1100}
>
<Stack gap="md">
- {storedFiles.length === 0 ? (
- <Text c="dimmed" ta="center" py="xl">
- {terminology.noFilesInStorage}
- </Text>
- ) : (
- <>
- {/* Selection controls */}
- <Group justify="space-between">
- <Text size="sm" c="dimmed">
- {t("fileUpload.filesAvailableCount", {
- count: storedFiles.length,
- defaultValue_one: "{{count}} file available",
- defaultValue_other: "{{count}} files available",
- })}
- {selectedFileIds.length > 0 && (
- <>
- {" • "}
- {t("fileUpload.selectedCount", "{{count}} selected", {
- count: selectedFileIds.length,
- })}
- </>
- )}
- </Text>
- <Group gap="xs">
- <Button size="sm" variant="secondary" onClick={selectAll}>
- {t("pageEdit.selectAll", "Select All")}
- </Button>
- <Button size="sm" variant="secondary" onClick={selectNone}>
- {t("pageEdit.deselectAll", "Select None")}
- </Button>
- </Group>
- </Group>
-
- {/* File grid */}
- <ScrollArea.Autosize mah={400}>
- <SimpleGrid cols={2} spacing="md">
- {storedFiles.map((file) => {
- const fileId = file.id;
- const isSelected = selectedFileIds.includes(fileId);
-
- return (
- <Box
- key={fileId}
- p="sm"
- style={{
- border: isSelected
- ? "2px solid var(--mantine-color-blue-6)"
- : "1px solid var(--mantine-color-gray-3)",
- borderRadius: 8,
- backgroundColor: isSelected
- ? "var(--mantine-color-blue-0)"
- : "transparent",
- cursor: "pointer",
- transition: "all 0.2s ease",
- }}
- onClick={() => toggleFileSelection(fileId)}
- >
- <Group gap="sm" align="flex-start">
- <Checkbox
- checked={isSelected}
- onChange={() => toggleFileSelection(fileId)}
- onClick={(e) => e.stopPropagation()}
- aria-label={t(
- "fileUpload.selectFile",
- "Select {{name}}",
- {
- name: file.name,
- },
- )}
- />
-
- {/* Thumbnail */}
- <Box
- style={{
- width: 60,
- height: 80,
- border: "1px solid var(--mantine-color-gray-3)",
- borderRadius: 4,
- backgroundColor: "white",
- flexShrink: 0,
- overflow: "hidden",
- }}
- >
- <DocumentThumbnail
- file={file.file ?? null}
- thumbnail={
- file.processedFile?.isEncrypted
- ? undefined
- : file.thumbnail
- }
- isEncrypted={Boolean(
- file.processedFile?.isEncrypted,
- )}
- iconSize="2rem"
- />
- </Box>
-
- {/* File info */}
- <Stack gap="xs" style={{ flex: 1, minWidth: 0 }}>
- <Text size="sm" fw={500} lineClamp={2}>
- {file.name}
- </Text>
- <Group gap="xs">
- <Badge size="xs" variant="light" color="gray">
- {formatFileSize(
- file.size || file.file?.size || 0,
- )}
- </Badge>
- </Group>
- </Stack>
- </Group>
- </Box>
- );
- })}
- </SimpleGrid>
- </ScrollArea.Autosize>
-
- {/* Selection summary */}
- {selectedFileIds.length > 0 && (
- <Text size="sm" c="var(--c-accent-text)" ta="center">
- {selectedFileIds.length}{" "}
- {t("fileManager.filesSelected", "files selected")}
- </Text>
- )}
- </>
- )}
-
- {/* Action buttons */}
- <Group justify="flex-end" mt="md">
- <Button variant="secondary" onClick={onClose}>
- {t("close", "Cancel")}
- </Button>
- <Button
- onClick={handleConfirm}
- disabled={selectedFileIds.length === 0}
- >
- {selectedFileIds.length > 0
- ? `${t("fileUpload.loadFromStorage", "Load")} ${selectedFileIds.length} ${terminology.uploadFiles}`
- : t("fileUpload.loadFromStorage", "Load Files")}
- </Button>
- </Group>
+ <StoredFileBrowser
+ files={storedFiles}
+ selectedIds={selectedFileIds}
+ onToggle={toggleFileSelection}
+ onSelectAll={selectAll}
+ onSelectNone={selectNone}
+ />
+ <PickerActions
+ selectedCount={selectedFileIds.length}
+ onCancel={onClose}
+ onConfirm={handleConfirm}
+ />
</Stack>
</Modal>
);
diff --git a/frontend/editor/src/core/components/tools/sign/SavedSignaturesSection.tsx b/frontend/editor/src/core/components/tools/sign/SavedSignaturesSection.tsx
index effe28bdb8..e8dd927230 100644
--- a/frontend/editor/src/core/components/tools/sign/SavedSignaturesSection.tsx
+++ b/frontend/editor/src/core/components/tools/sign/SavedSignaturesSection.tsx
@@ -1,4 +1,13 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type Dispatch,
+ type ReactNode,
+ type SetStateAction,
+} from "react";
import { useTranslation } from "react-i18next";
import {
Alert,
@@ -11,7 +20,7 @@ import {
TextInput,
Tooltip,
} from "@mantine/core";
-import { Icon } from "@app/ui/Icon";
+import { Icon, type IconName } from "@app/ui/Icon";
import { ActionIcon } from "@app/ui/ActionIcon";
import {
SavedSignature,
@@ -38,6 +47,447 @@ const typeBadgeColor: Record<SavedSignatureType, string> = {
text: "grape",
};
+/** `t` bound to the section's translation scope, e.g. `sign.saved.heading`. */
+type ScopedTranslate = (
+ key: string,
+ defaultValue: string,
+ options?: Record<string, unknown>,
+) => string;
+
+function typeLabel(translate: ScopedTranslate, type: SavedSignatureType) {
+ switch (type) {
+ case "canvas":
+ return translate("saved.type.canvas", "Drawing");
+ case "image":
+ return translate("saved.type.image", "Upload");
+ case "text":
+ return translate("saved.type.text", "Text");
+ default:
+ return type;
+ }
+}
+
+function SavedSignaturesHeader({ translate }: { translate: ScopedTranslate }) {
+ return (
+ <Group justify="space-between" align="flex-start">
+ <Stack gap={0}>
+ <Text fw={600} size="md">
+ {translate("saved.heading", "Saved signatures")}
+ </Text>
+ <Text size="sm" c="dimmed">
+ {translate(
+ "saved.description",
+ "Reuse saved signatures at any time.",
+ )}
+ </Text>
+ </Stack>
+ </Group>
+ );
+}
+
+interface CapacityAlertProps {
+ show: boolean;
+ max: number;
+ translate: ScopedTranslate;
+}
+
+function CapacityAlert({ show, max, translate }: CapacityAlertProps) {
+ if (!show) return null;
+ return (
+ <Alert
+ color="yellow"
+ title={translate("saved.limitTitle", "Limit reached")}
+ >
+ <Text size="sm">
+ {translate(
+ "saved.limitDescription",
+ "Remove a saved signature before adding new ones (max {{max}}).",
+ { max },
+ )}
+ </Text>
+ </Alert>
+ );
+}
+
+function SavedSignaturesEmpty({
+ max,
+ translate,
+}: {
+ max: number;
+ translate: ScopedTranslate;
+}) {
+ return (
+ <Card withBorder>
+ <Stack gap="xs">
+ <Text fw={500}>
+ {translate("saved.emptyTitle", "No saved signatures yet")}
+ </Text>
+ <Text size="sm" c="dimmed">
+ {translate(
+ "saved.emptyDescription",
+ 'Draw, upload, or type a signature above, then use "Save to library" to keep up to {{max}} favourites ready to use.',
+ { max },
+ )}
+ </Text>
+ </Stack>
+ </Card>
+ );
+}
+
+interface SignatureGroupHeadingProps {
+ icon: IconName;
+ title: string;
+ description: string;
+}
+
+function SignatureGroupHeading({
+ icon,
+ title,
+ description,
+}: SignatureGroupHeadingProps) {
+ return (
+ <>
+ <Group gap="xs">
+ <Icon name={icon} size={18} />
+ <Text fw={600} size="sm">
+ {title}
+ </Text>
+ </Group>
+ <Text size="xs" c="dimmed">
+ {description}
+ </Text>
+ </>
+ );
+}
+
+function TemporaryStorageNotice({ translate }: { translate: ScopedTranslate }) {
+ return (
+ <Alert
+ color="blue"
+ title={translate("saved.tempStorageTitle", "Temporary browser storage")}
+ >
+ <Text size="xs">
+ {translate(
+ "saved.tempStorageDescription",
+ "Signatures are stored in your browser only. They will be lost if you clear browser data or switch browsers.",
+ )}
+ </Text>
+ </Alert>
+ );
+}
+
+interface CarouselNavProps {
+ activeIndex: number;
+ total: number;
+ disabled: boolean;
+ onActiveIndexChange: Dispatch<SetStateAction<number>>;
+ translate: ScopedTranslate;
+}
+
+function CarouselNav({
+ activeIndex,
+ total,
+ disabled,
+ onActiveIndexChange,
+ translate,
+}: CarouselNavProps) {
+ return (
+ <Group justify="space-between" align="center">
+ <Text size="sm" c="dimmed">
+ {translate("saved.carouselPosition", "{{current}} of {{total}}", {
+ current: activeIndex + 1,
+ total,
+ })}
+ </Text>
+ <Group gap={4}>
+ <ActionIcon
+ variant="secondary"
+ aria-label={translate("saved.prev", "Previous")}
+ onClick={() => onActiveIndexChange((prev) => Math.max(0, prev - 1))}
+ disabled={disabled || activeIndex === 0}
+ >
+ <Icon name="chevron-left" size={18} />
+ </ActionIcon>
+ <ActionIcon
+ variant="secondary"
+ aria-label={translate("saved.next", "Next")}
+ onClick={() =>
+ onActiveIndexChange((prev) => Math.min(total - 1, prev + 1))
+ }
+ disabled={disabled || activeIndex >= total - 1}
+ >
+ <Icon name="chevron-right" size={18} />
+ </ActionIcon>
+ </Group>
+ </Group>
+ );
+}
+
+function SignaturePreview({ signature }: { signature: SavedSignature }) {
+ if (signature.type === "text") {
+ return (
+ <Box
+ component="div"
+ style={{
+ fontFamily: signature.fontFamily,
+ fontSize: `${signature.fontSize}px`,
+ color: signature.textColor,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ height: "120px",
+ borderRadius: "0.5rem",
+ backgroundColor: "#ffffff",
+ padding: "0.5rem",
+ textAlign: "center",
+ overflow: "hidden",
+ }}
+ >
+ <Text
+ size="lg"
+ style={{
+ fontFamily: signature.fontFamily,
+ color: signature.textColor,
+ whiteSpace: "nowrap",
+ }}
+ >
+ {signature.signerName}
+ </Text>
+ </Box>
+ );
+ }
+
+ return (
+ <Box
+ component="div"
+ style={{
+ backgroundColor: "#ffffff",
+ borderRadius: "0.5rem",
+ height: "120px",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ padding: "0.5rem",
+ }}
+ >
+ <Box
+ component="img"
+ src={signature.dataUrl}
+ alt={signature.label}
+ style={{
+ maxWidth: "100%",
+ maxHeight: "100%",
+ objectFit: "contain",
+ }}
+ />
+ </Box>
+ );
+}
+
+interface SignatureCardActionsProps {
+ canDelete: boolean;
+ disabled: boolean;
+ translate: ScopedTranslate;
+ onUse: () => void;
+ onDelete: () => void;
+}
+
+function SignatureCardActions({
+ canDelete,
+ disabled,
+ translate,
+ onUse,
+ onDelete,
+}: SignatureCardActionsProps) {
+ const { t } = useTranslation();
+ return (
+ <Group gap="xs">
+ <ActionIcon
+ variant="tertiary"
+ aria-label={t("sign.saved.use", "Use signature")}
+ onClick={onUse}
+ disabled={disabled}
+ >
+ <Icon name="circle-check" size={18} />
+ </ActionIcon>
+ {canDelete && (
+ <Tooltip label={translate("saved.delete", "Remove")}>
+ <ActionIcon
+ variant="tertiary"
+ accent="danger"
+ aria-label={translate("saved.delete", "Remove")}
+ onClick={onDelete}
+ disabled={disabled}
+ >
+ <Icon name="trash" size={18} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </Group>
+ );
+}
+
+interface SignatureCardHandlers {
+ disabled: boolean;
+ translate: ScopedTranslate;
+ labelDrafts: Record<string, string>;
+ onUse: (signature: SavedSignature) => void;
+ onDelete: (signature: SavedSignature) => void;
+ onLabelChange: (
+ event: React.ChangeEvent<HTMLInputElement>,
+ signature: SavedSignature,
+ ) => void;
+ onLabelBlur: (signature: SavedSignature) => void;
+ onLabelKeyDown: (
+ event: React.KeyboardEvent<HTMLInputElement>,
+ signature: SavedSignature,
+ ) => void;
+}
+
+interface SavedSignatureCardProps extends SignatureCardHandlers {
+ signature: SavedSignature;
+ canDelete: boolean;
+}
+
+function SavedSignatureCard({
+ signature,
+ canDelete,
+ disabled,
+ translate,
+ labelDrafts,
+ onUse,
+ onDelete,
+ onLabelChange,
+ onLabelBlur,
+ onLabelKeyDown,
+}: SavedSignatureCardProps) {
+ return (
+ <Card withBorder padding="sm">
+ <Stack gap="sm">
+ <Group justify="space-between" align="center">
+ <Badge color={typeBadgeColor[signature.type]} variant="light">
+ {typeLabel(translate, signature.type)}
+ </Badge>
+ <SignatureCardActions
+ canDelete={canDelete}
+ disabled={disabled}
+ translate={translate}
+ onUse={() => onUse(signature)}
+ onDelete={() => onDelete(signature)}
+ />
+ </Group>
+ <SignaturePreview signature={signature} />
+ <TextInput
+ label={translate("saved.label", "Label")}
+ value={labelDrafts[signature.id] ?? signature.label}
+ onChange={(event) => onLabelChange(event, signature)}
+ onBlur={() => onLabelBlur(signature)}
+ onKeyDown={(event) => onLabelKeyDown(event, signature)}
+ disabled={disabled}
+ />
+ </Stack>
+ </Card>
+ );
+}
+
+interface SignatureCarouselProps extends SignatureCardHandlers {
+ signatures: SavedSignature[];
+ canDelete?: boolean;
+ children: ReactNode;
+}
+
+function SignatureCarousel({
+ signatures,
+ canDelete = true,
+ children,
+ ...card
+}: SignatureCarouselProps) {
+ const [activeIndex, setActiveIndex] = useState(0);
+
+ // Keep the index in range when signatures are removed.
+ useEffect(() => {
+ setActiveIndex((prev) =>
+ Math.min(prev, Math.max(signatures.length - 1, 0)),
+ );
+ }, [signatures.length]);
+
+ const active = signatures[activeIndex];
+ if (signatures.length === 0 || !active) return null;
+ return (
+ <Stack gap="xs">
+ {children}
+ <CarouselNav
+ activeIndex={activeIndex}
+ total={signatures.length}
+ disabled={card.disabled}
+ onActiveIndexChange={setActiveIndex}
+ translate={card.translate}
+ />
+ <SavedSignatureCard signature={active} canDelete={canDelete} {...card} />
+ </Stack>
+ );
+}
+
+interface SavedSignatureGroupsProps extends SignatureCardHandlers {
+ signatures: SavedSignature[];
+ isAdmin: boolean;
+ maxLimit: number;
+}
+
+function SavedSignatureGroups({
+ signatures,
+ isAdmin,
+ maxLimit,
+ ...card
+}: SavedSignatureGroupsProps) {
+ const { translate } = card;
+
+ // Group signatures by scope
+ const groupedSignatures = useMemo(() => {
+ const personal = signatures.filter((sig) => sig.scope === "personal");
+ const shared = signatures.filter((sig) => sig.scope === "shared");
+ const localStorage = signatures.filter(
+ (sig) => sig.scope === "localStorage",
+ );
+ return { personal, shared, localStorage };
+ }, [signatures]);
+
+ if (signatures.length === 0) {
+ return <SavedSignaturesEmpty max={maxLimit} translate={translate} />;
+ }
+ return (
+ <Stack gap="md">
+ <SignatureCarousel signatures={groupedSignatures.personal} {...card}>
+ <SignatureGroupHeading
+ icon="user"
+ title={translate("saved.personalHeading", "Personal Signatures")}
+ description={translate(
+ "saved.personalDescription",
+ "Only you can see these signatures.",
+ )}
+ />
+ </SignatureCarousel>
+ <SignatureCarousel
+ signatures={groupedSignatures.shared}
+ canDelete={isAdmin}
+ {...card}
+ >
+ <SignatureGroupHeading
+ icon="users"
+ title={translate("saved.sharedHeading", "Shared Signatures")}
+ description={translate(
+ "saved.sharedDescription",
+ "All users can see and use these signatures.",
+ )}
+ />
+ </SignatureCarousel>
+ <SignatureCarousel signatures={groupedSignatures.localStorage} {...card}>
+ <TemporaryStorageNotice translate={translate} />
+ </SignatureCarousel>
+ </Stack>
+ );
+}
+
export const SavedSignaturesSection = ({
signatures,
disabled = false,
@@ -58,27 +508,6 @@ export const SavedSignaturesSection = ({
);
const [labelDrafts, setLabelDrafts] = useState<Record<string, string>>({});
- // Group signatures by scope
- const groupedSignatures = useMemo(() => {
- const personal = signatures.filter((sig) => sig.scope === "personal");
- const shared = signatures.filter((sig) => sig.scope === "shared");
- const localStorage = signatures.filter(
- (sig) => sig.scope === "localStorage",
- );
- return { personal, shared, localStorage };
- }, [signatures]);
-
- // Separate carousel state for each category
- const [activePersonalIndex, setActivePersonalIndex] = useState(0);
- const [activeSharedIndex, setActiveSharedIndex] = useState(0);
- const [activeLocalStorageIndex, setActiveLocalStorageIndex] = useState(0);
-
- const activePersonalSignature =
- groupedSignatures.personal[activePersonalIndex];
- const activeSharedSignature = groupedSignatures.shared[activeSharedIndex];
- const activeLocalStorageSignature =
- groupedSignatures.localStorage[activeLocalStorageIndex];
-
const onUseSignatureRef = useRef(onUseSignature);
useEffect(() => {
@@ -95,116 +524,6 @@ export const SavedSignaturesSection = ({
});
}, [signatures]);
- // Reset carousel indices when categories change
- useEffect(() => {
- setActivePersonalIndex((prev) =>
- Math.min(prev, Math.max(groupedSignatures.personal.length - 1, 0)),
- );
- }, [groupedSignatures.personal.length]);
-
- useEffect(() => {
- setActiveSharedIndex((prev) =>
- Math.min(prev, Math.max(groupedSignatures.shared.length - 1, 0)),
- );
- }, [groupedSignatures.shared.length]);
-
- useEffect(() => {
- setActiveLocalStorageIndex((prev) =>
- Math.min(prev, Math.max(groupedSignatures.localStorage.length - 1, 0)),
- );
- }, [groupedSignatures.localStorage.length]);
-
- const renderPreview = (signature: SavedSignature) => {
- if (signature.type === "text") {
- return (
- <Box
- component="div"
- style={{
- fontFamily: signature.fontFamily,
- fontSize: `${signature.fontSize}px`,
- color: signature.textColor,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- height: "120px",
- borderRadius: "0.5rem",
- backgroundColor: "#ffffff",
- padding: "0.5rem",
- textAlign: "center",
- overflow: "hidden",
- }}
- >
- <Text
- size="lg"
- style={{
- fontFamily: signature.fontFamily,
- color: signature.textColor,
- whiteSpace: "nowrap",
- }}
- >
- {signature.signerName}
- </Text>
- </Box>
- );
- }
-
- return (
- <Box
- component="div"
- style={{
- backgroundColor: "#ffffff",
- borderRadius: "0.5rem",
- height: "120px",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- padding: "0.5rem",
- }}
- >
- <Box
- component="img"
- src={signature.dataUrl}
- alt={signature.label}
- style={{
- maxWidth: "100%",
- maxHeight: "100%",
- objectFit: "contain",
- }}
- />
- </Box>
- );
- };
-
- const emptyState = (
- <Card withBorder>
- <Stack gap="xs">
- <Text fw={500}>
- {translate("saved.emptyTitle", "No saved signatures yet")}
- </Text>
- <Text size="sm" c="dimmed">
- {translate(
- "saved.emptyDescription",
- 'Draw, upload, or type a signature above, then use "Save to library" to keep up to {{max}} favourites ready to use.',
- { max: maxLimit },
- )}
- </Text>
- </Stack>
- </Card>
- );
-
- const typeLabel = (type: SavedSignatureType) => {
- switch (type) {
- case "canvas":
- return translate("saved.type.canvas", "Drawing");
- case "image":
- return translate("saved.type.image", "Upload");
- case "text":
- return translate("saved.type.text", "Text");
- default:
- return type;
- }
- };
-
const handleLabelBlur = (signature: SavedSignature) => {
const nextValue = labelDrafts[signature.id]?.trim() ?? "";
if (!nextValue || nextValue === signature.label) {
@@ -235,393 +554,27 @@ export const SavedSignaturesSection = ({
}
};
+ const cardHandlers: SignatureCardHandlers = {
+ disabled,
+ translate,
+ labelDrafts,
+ onUse: onUseSignature,
+ onDelete: onDeleteSignature,
+ onLabelChange: handleLabelChange,
+ onLabelBlur: handleLabelBlur,
+ onLabelKeyDown: handleLabelKeyDown,
+ };
+
return (
<Stack gap="sm">
- <Group justify="space-between" align="flex-start">
- <Stack gap={0}>
- <Text fw={600} size="md">
- {translate("saved.heading", "Saved signatures")}
- </Text>
- <Text size="sm" c="dimmed">
- {translate(
- "saved.description",
- "Reuse saved signatures at any time.",
- )}
- </Text>
- </Stack>
- </Group>
-
- {isAtCapacity && (
- <Alert
- color="yellow"
- title={translate("saved.limitTitle", "Limit reached")}
- >
- <Text size="sm">
- {translate(
- "saved.limitDescription",
- "Remove a saved signature before adding new ones (max {{max}}).",
- {
- max: maxLimit,
- },
- )}
- </Text>
- </Alert>
- )}
-
- {signatures.length === 0 ? (
- emptyState
- ) : (
- <Stack gap="md">
- {/* Personal Signatures */}
- {groupedSignatures.personal.length > 0 && activePersonalSignature && (
- <Stack gap="xs">
- <Group gap="xs">
- <Icon name="user" size={18} />
- <Text fw={600} size="sm">
- {translate("saved.personalHeading", "Personal Signatures")}
- </Text>
- </Group>
- <Text size="xs" c="dimmed">
- {translate(
- "saved.personalDescription",
- "Only you can see these signatures.",
- )}
- </Text>
-
- <Group justify="space-between" align="center">
- <Text size="sm" c="dimmed">
- {translate(
- "saved.carouselPosition",
- "{{current}} of {{total}}",
- {
- current: activePersonalIndex + 1,
- total: groupedSignatures.personal.length,
- },
- )}
- </Text>
- <Group gap={4}>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.prev", "Previous")}
- onClick={() =>
- setActivePersonalIndex((prev) => Math.max(0, prev - 1))
- }
- disabled={disabled || activePersonalIndex === 0}
- >
- <Icon name="chevron-left" size={18} />
- </ActionIcon>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.next", "Next")}
- onClick={() =>
- setActivePersonalIndex((prev) =>
- Math.min(
- groupedSignatures.personal.length - 1,
- prev + 1,
- ),
- )
- }
- disabled={
- disabled ||
- activePersonalIndex >=
- groupedSignatures.personal.length - 1
- }
- >
- <Icon name="chevron-right" size={18} />
- </ActionIcon>
- </Group>
- </Group>
-
- <Card withBorder padding="sm">
- <Stack gap="sm">
- <Group justify="space-between" align="center">
- <Badge
- color={typeBadgeColor[activePersonalSignature.type]}
- variant="light"
- >
- {typeLabel(activePersonalSignature.type)}
- </Badge>
- <Group gap="xs">
- <ActionIcon
- variant="tertiary"
- aria-label={t("sign.saved.use", "Use signature")}
- onClick={() => onUseSignature(activePersonalSignature)}
- disabled={disabled}
- >
- <Icon name="circle-check" size={18} />
- </ActionIcon>
- <Tooltip label={translate("saved.delete", "Remove")}>
- <ActionIcon
- variant="tertiary"
- accent="danger"
- aria-label={translate("saved.delete", "Remove")}
- onClick={() =>
- onDeleteSignature(activePersonalSignature)
- }
- disabled={disabled}
- >
- <Icon name="trash" size={18} />
- </ActionIcon>
- </Tooltip>
- </Group>
- </Group>
- {renderPreview(activePersonalSignature)}
- <TextInput
- label={translate("saved.label", "Label")}
- value={
- labelDrafts[activePersonalSignature.id] ??
- activePersonalSignature.label
- }
- onChange={(event) =>
- handleLabelChange(event, activePersonalSignature)
- }
- onBlur={() => handleLabelBlur(activePersonalSignature)}
- onKeyDown={(event) =>
- handleLabelKeyDown(event, activePersonalSignature)
- }
- disabled={disabled}
- />
- </Stack>
- </Card>
- </Stack>
- )}
-
- {/* Shared Signatures */}
- {groupedSignatures.shared.length > 0 && activeSharedSignature && (
- <Stack gap="xs">
- <Group gap="xs">
- <Icon name="users" size={18} />
- <Text fw={600} size="sm">
- {translate("saved.sharedHeading", "Shared Signatures")}
- </Text>
- </Group>
- <Text size="xs" c="dimmed">
- {translate(
- "saved.sharedDescription",
- "All users can see and use these signatures.",
- )}
- </Text>
-
- <Group justify="space-between" align="center">
- <Text size="sm" c="dimmed">
- {translate(
- "saved.carouselPosition",
- "{{current}} of {{total}}",
- {
- current: activeSharedIndex + 1,
- total: groupedSignatures.shared.length,
- },
- )}
- </Text>
- <Group gap={4}>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.prev", "Previous")}
- onClick={() =>
- setActiveSharedIndex((prev) => Math.max(0, prev - 1))
- }
- disabled={disabled || activeSharedIndex === 0}
- >
- <Icon name="chevron-left" size={18} />
- </ActionIcon>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.next", "Next")}
- onClick={() =>
- setActiveSharedIndex((prev) =>
- Math.min(groupedSignatures.shared.length - 1, prev + 1),
- )
- }
- disabled={
- disabled ||
- activeSharedIndex >= groupedSignatures.shared.length - 1
- }
- >
- <Icon name="chevron-right" size={18} />
- </ActionIcon>
- </Group>
- </Group>
-
- <Card withBorder padding="sm">
- <Stack gap="sm">
- <Group justify="space-between" align="center">
- <Badge
- color={typeBadgeColor[activeSharedSignature.type]}
- variant="light"
- >
- {typeLabel(activeSharedSignature.type)}
- </Badge>
- <Group gap="xs">
- <ActionIcon
- variant="tertiary"
- aria-label={t("sign.saved.use", "Use signature")}
- onClick={() => onUseSignature(activeSharedSignature)}
- disabled={disabled}
- >
- <Icon name="circle-check" size={18} />
- </ActionIcon>
- {isAdmin && (
- <Tooltip label={translate("saved.delete", "Remove")}>
- <ActionIcon
- variant="tertiary"
- accent="danger"
- aria-label={translate("saved.delete", "Remove")}
- onClick={() =>
- onDeleteSignature(activeSharedSignature)
- }
- disabled={disabled}
- >
- <Icon name="trash" size={18} />
- </ActionIcon>
- </Tooltip>
- )}
- </Group>
- </Group>
- {renderPreview(activeSharedSignature)}
- <TextInput
- label={translate("saved.label", "Label")}
- value={
- labelDrafts[activeSharedSignature.id] ??
- activeSharedSignature.label
- }
- onChange={(event) =>
- handleLabelChange(event, activeSharedSignature)
- }
- onBlur={() => handleLabelBlur(activeSharedSignature)}
- onKeyDown={(event) =>
- handleLabelKeyDown(event, activeSharedSignature)
- }
- disabled={disabled}
- />
- </Stack>
- </Card>
- </Stack>
- )}
-
- {/* Browser Storage (localStorage) - Temporary */}
- {groupedSignatures.localStorage.length > 0 &&
- activeLocalStorageSignature && (
- <Stack gap="xs">
- <Alert
- color="blue"
- title={translate(
- "saved.tempStorageTitle",
- "Temporary browser storage",
- )}
- >
- <Text size="xs">
- {translate(
- "saved.tempStorageDescription",
- "Signatures are stored in your browser only. They will be lost if you clear browser data or switch browsers.",
- )}
- </Text>
- </Alert>
-
- <Group justify="space-between" align="center">
- <Text size="sm" c="dimmed">
- {translate(
- "saved.carouselPosition",
- "{{current}} of {{total}}",
- {
- current: activeLocalStorageIndex + 1,
- total: groupedSignatures.localStorage.length,
- },
- )}
- </Text>
- <Group gap={4}>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.prev", "Previous")}
- onClick={() =>
- setActiveLocalStorageIndex((prev) =>
- Math.max(0, prev - 1),
- )
- }
- disabled={disabled || activeLocalStorageIndex === 0}
- >
- <Icon name="chevron-left" size={18} />
- </ActionIcon>
- <ActionIcon
- variant="secondary"
- aria-label={translate("saved.next", "Next")}
- onClick={() =>
- setActiveLocalStorageIndex((prev) =>
- Math.min(
- groupedSignatures.localStorage.length - 1,
- prev + 1,
- ),
- )
- }
- disabled={
- disabled ||
- activeLocalStorageIndex >=
- groupedSignatures.localStorage.length - 1
- }
- >
- <Icon name="chevron-right" size={18} />
- </ActionIcon>
- </Group>
- </Group>
-
- <Card withBorder padding="sm">
- <Stack gap="sm">
- <Group justify="space-between" align="center">
- <Badge
- color={typeBadgeColor[activeLocalStorageSignature.type]}
- variant="light"
- >
- {typeLabel(activeLocalStorageSignature.type)}
- </Badge>
- <Group gap="xs">
- <ActionIcon
- variant="tertiary"
- aria-label={t("sign.saved.use", "Use signature")}
- onClick={() =>
- onUseSignature(activeLocalStorageSignature)
- }
- disabled={disabled}
- >
- <Icon name="circle-check" size={18} />
- </ActionIcon>
- <Tooltip label={translate("saved.delete", "Remove")}>
- <ActionIcon
- variant="tertiary"
- accent="danger"
- aria-label={translate("saved.delete", "Remove")}
- onClick={() =>
- onDeleteSignature(activeLocalStorageSignature)
- }
- disabled={disabled}
- >
- <Icon name="trash" size={18} />
- </ActionIcon>
- </Tooltip>
- </Group>
- </Group>
- {renderPreview(activeLocalStorageSignature)}
- <TextInput
- label={translate("saved.label", "Label")}
- value={
- labelDrafts[activeLocalStorageSignature.id] ??
- activeLocalStorageSignature.label
- }
- onChange={(event) =>
- handleLabelChange(event, activeLocalStorageSignature)
- }
- onBlur={() =>
- handleLabelBlur(activeLocalStorageSignature)
- }
- onKeyDown={(event) =>
- handleLabelKeyDown(event, activeLocalStorageSignature)
- }
- disabled={disabled}
- />
- </Stack>
- </Card>
- </Stack>
- )}
- </Stack>
- )}
+ <SavedSignaturesHeader translate={translate} />
+ <CapacityAlert show={isAtCapacity} max={maxLimit} translate={translate} />
+ <SavedSignatureGroups
+ signatures={signatures}
+ isAdmin={isAdmin}
+ maxLimit={maxLimit}
+ {...cardHandlers}
+ />
</Stack>
);
};
diff --git a/frontend/editor/src/core/components/tools/validateSignature/ValidateSignatureReportView.tsx b/frontend/editor/src/core/components/tools/validateSignature/ValidateSignatureReportView.tsx
index 87880f7f78..ffb0b8d828 100644
--- a/frontend/editor/src/core/components/tools/validateSignature/ValidateSignatureReportView.tsx
+++ b/frontend/editor/src/core/components/tools/validateSignature/ValidateSignatureReportView.tsx
@@ -1,7 +1,10 @@
import React, { useMemo } from "react";
import { Badge, Group, Stack, Text, Divider } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import type { SignatureValidationReportData } from "@app/types/validateSignature";
+import type {
+ SignatureValidationReportData,
+ SignatureValidationReportEntry,
+} from "@app/types/validateSignature";
import "@app/components/tools/validateSignature/reportView/styles.css";
import ThumbnailPreview from "@app/components/tools/validateSignature/reportView/ThumbnailPreview";
import FileSummaryHeader from "@app/components/tools/validateSignature/reportView/FileSummaryHeader";
@@ -11,6 +14,12 @@ interface ValidateSignatureReportViewProps {
data: SignatureValidationReportData;
}
+interface ReportPageDef {
+ entry: SignatureValidationReportEntry;
+ signatureIndex: number | null;
+ includeSummary: boolean;
+}
+
const NoSignatureSection = ({
message,
label,
@@ -38,21 +47,142 @@ const NoSignatureSection = ({
</Stack>
);
-const ValidateSignatureReportView: React.FC<
- ValidateSignatureReportViewProps
-> = ({ data }) => {
+const ReportHeader = ({ generatedAt }: { generatedAt: number }) => {
+ const { t } = useTranslation();
+ return (
+ <Stack gap="xs" align="center">
+ <Badge size="lg" color="blue" variant="light">
+ {t("validateSignature.report.title", "Signature Validation Report")}
+ </Badge>
+ <Text size="sm" c="dimmed">
+ {t("validateSignature.report.generatedAt", "Generated")}{" "}
+ {new Date(generatedAt).toLocaleString()}
+ </Text>
+ </Stack>
+ );
+};
+
+const PageSummary = ({
+ page,
+ pageNumber,
+}: {
+ page: ReportPageDef;
+ pageNumber: number;
+}) => {
const { t } = useTranslation();
- const noSignaturesLabel = t(
- "validateSignature.noSignaturesShort",
- "No signatures",
+ if (!page.includeSummary) return null;
+ const { entry } = page;
+ return (
+ <>
+ <Group align="flex-start" gap="lg">
+ <ThumbnailPreview
+ thumbnailUrl={entry.thumbnailUrl}
+ fileName={entry.fileName}
+ />
+ <Stack gap="sm" style={{ flex: 1 }}>
+ <Group justify="space-between" align="flex-start">
+ <div>
+ <Text fw={700} size="xl" style={{ lineHeight: 1.1 }}>
+ {entry.fileName}
+ </Text>
+ <Text size="sm" c="dimmed">
+ {t("validateSignature.report.entryLabel", "Signature Summary")}
+ </Text>
+ </div>
+ <Badge color="gray" variant="light">
+ {t("validateSignature.report.page", "Page")} {pageNumber}
+ </Badge>
+ </Group>
+
+ <FileSummaryHeader
+ fileSize={entry.fileSize}
+ createdAt={entry.createdAtLabel ?? null}
+ totalSignatures={entry.signatures.length}
+ lastSignatureDate={entry.signatures[0]?.signatureDate}
+ />
+ </Stack>
+ </Group>
+
+ <Divider />
+ </>
);
+};
+const PageSignature = ({ page }: { page: ReportPageDef }) => {
+ const { t } = useTranslation();
+ const { entry, signatureIndex } = page;
+ if (entry.error) {
+ return (
+ <NoSignatureSection
+ message={entry.error}
+ label={t("validateSignature.status.invalid", "Invalid")}
+ />
+ );
+ }
+ if (signatureIndex === null) {
+ return (
+ <NoSignatureSection
+ message={t(
+ "validateSignature.noSignatures",
+ "No digital signatures found in this document",
+ )}
+ label={t("validateSignature.noSignaturesShort", "No signatures")}
+ />
+ );
+ }
+ return (
+ <Stack gap="xl">
+ <SignatureSection
+ signature={entry.signatures[signatureIndex]}
+ index={signatureIndex}
+ />
+ </Stack>
+ );
+};
+
+const PageFooter = ({
+ pageNumber,
+ pageCount,
+}: {
+ pageNumber: number;
+ pageCount: number;
+}) => {
+ const { t } = useTranslation();
+ return (
+ <Group justify="space-between" align="center" mt="auto" pt="md">
+ <Text size="xs" c="dimmed">
+ {t("validateSignature.report.footer", "Validated via Stirling PDF")}
+ </Text>
+ <Text size="xs" c="dimmed">
+ {t("validateSignature.report.page", "Page")} {pageNumber} / {pageCount}
+ </Text>
+ </Group>
+ );
+};
+
+const ReportPage = ({
+ page,
+ pageNumber,
+ pageCount,
+}: {
+ page: ReportPageDef;
+ pageNumber: number;
+ pageCount: number;
+}) => (
+ <div className="simulated-page">
+ <Stack gap="lg" style={{ flex: 1 }}>
+ <PageSummary page={page} pageNumber={pageNumber} />
+ <PageSignature page={page} />
+ </Stack>
+ <PageFooter pageNumber={pageNumber} pageCount={pageCount} />
+ </div>
+);
+
+const ValidateSignatureReportView: React.FC<
+ ValidateSignatureReportViewProps
+> = ({ data }) => {
const pages = useMemo(() => {
- const result: Array<{
- entry: SignatureValidationReportData["entries"][number];
- signatureIndex: number | null;
- includeSummary: boolean;
- }> = [];
+ const result: ReportPageDef[] = [];
for (const entry of data.entries) {
if (entry.signatures.length === 0 || entry.error) {
@@ -75,103 +205,15 @@ const ValidateSignatureReportView: React.FC<
return (
<div className="report-container">
<Stack gap="xl" align="center">
- <Stack gap="xs" align="center">
- <Badge size="lg" color="blue" variant="light">
- {t("validateSignature.report.title", "Signature Validation Report")}
- </Badge>
- <Text size="sm" c="dimmed">
- {t("validateSignature.report.generatedAt", "Generated")}{" "}
- {new Date(data.generatedAt).toLocaleString()}
- </Text>
- </Stack>
+ <ReportHeader generatedAt={data.generatedAt} />
- {pages.map((pageDef, index) => (
- <div
- className="simulated-page"
- key={`${pageDef.entry.fileId}-${index}`}
- >
- <Stack gap="lg" style={{ flex: 1 }}>
- {pageDef.includeSummary && (
- <>
- <Group align="flex-start" gap="lg">
- <ThumbnailPreview
- thumbnailUrl={pageDef.entry.thumbnailUrl}
- fileName={pageDef.entry.fileName}
- />
- <Stack gap="sm" style={{ flex: 1 }}>
- <Group justify="space-between" align="flex-start">
- <div>
- <Text fw={700} size="xl" style={{ lineHeight: 1.1 }}>
- {pageDef.entry.fileName}
- </Text>
- <Text size="sm" c="dimmed">
- {t(
- "validateSignature.report.entryLabel",
- "Signature Summary",
- )}
- </Text>
- </div>
- <Badge color="gray" variant="light">
- {t("validateSignature.report.page", "Page")}{" "}
- {index + 1}
- </Badge>
- </Group>
-
- <FileSummaryHeader
- fileSize={pageDef.entry.fileSize}
- createdAt={pageDef.entry.createdAtLabel ?? null}
- totalSignatures={pageDef.entry.signatures.length}
- lastSignatureDate={
- pageDef.entry.signatures[0]?.signatureDate
- }
- />
- </Stack>
- </Group>
-
- <Divider />
- </>
- )}
-
- {pageDef.entry.error ? (
- <NoSignatureSection
- message={pageDef.entry.error}
- label={t("validateSignature.status.invalid", "Invalid")}
- />
- ) : pageDef.entry.signatures.length === 0 ? (
- <NoSignatureSection
- message={t(
- "validateSignature.noSignatures",
- "No digital signatures found in this document",
- )}
- label={noSignaturesLabel}
- />
- ) : (
- <Stack gap="xl">
- {pageDef.signatureIndex === null ? null : (
- <SignatureSection
- signature={
- pageDef.entry.signatures[pageDef.signatureIndex]
- }
- index={pageDef.signatureIndex}
- />
- )}
- </Stack>
- )}
- </Stack>
-
- <Group justify="space-between" align="center" mt="auto" pt="md">
- <Text size="xs" c="dimmed">
- {t(
- "validateSignature.report.footer",
- "Validated via Stirling PDF",
- )}
- </Text>
- <Text size="xs" c="dimmed">
- {t("validateSignature.report.page", "Page")} {index + 1} /{" "}
- {pages.length}
- </Text>
- </Group>
- </div>
+ {pages.map((page, index) => (
+ <ReportPage
+ key={`${page.entry.fileId}-${index}`}
+ page={page}
+ pageNumber={index + 1}
+ pageCount={pages.length}
+ />
))}
</Stack>
</div>
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx b/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
index 5af6f6df3e..384eaa949a 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
@@ -1,10 +1,11 @@
/** Left panel for "modify" mode; page highlighting lives in FormFieldEditOverlay. */
-import React, {
+import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
+ type RefObject,
} from "react";
import {
Text,
@@ -44,8 +45,18 @@ interface FormFieldModifyPanelProps {
onApplied?: (blob: Blob) => void;
}
+interface FieldGeometry {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
/** Current backend (lower-left origin) coords for a field's first widget. */
-function currentCoords(field: FormField, staged?: ModifyFieldDefinition) {
+function currentCoords(
+ field: FormField,
+ staged?: ModifyFieldDefinition,
+): FieldGeometry | null {
const w = field.widgets?.[0];
if (!w) return null;
if (
@@ -71,6 +82,336 @@ function currentCoords(field: FormField, staged?: ModifyFieldDefinition) {
};
}
+function editorValue(
+ field: FormField,
+ staged?: ModifyFieldDefinition,
+): EditableFieldProps {
+ return {
+ name: staged?.name ?? field.name,
+ label: staged?.label ?? field.label,
+ type: staged?.type ?? field.type,
+ defaultValue: staged?.defaultValue ?? field.value,
+ tooltip: staged?.tooltip ?? field.tooltip ?? "",
+ fontSize: staged?.fontSize ?? field.widgets?.[0]?.fontSize,
+ required: staged?.required ?? field.required,
+ readOnly: staged?.readOnly ?? field.readOnly,
+ multiline: staged?.multiline ?? field.multiline,
+ multiSelect: staged?.multiSelect ?? field.multiSelect,
+ options: staged?.options ?? field.options ?? [],
+ // Test for the staged KEY, not its value, or an explicit clear reads as
+ // "unchanged" and the input snaps back.
+ maxLength:
+ staged && "maxLength" in staged
+ ? staged.maxLength
+ : (field.maxLength ?? undefined),
+ buttonAction:
+ staged && "buttonAction" in staged
+ ? staged.buttonAction
+ : (field.buttonActionSpec ?? undefined),
+ };
+}
+
+function CommitErrorAlert({ error }: { error: string | null }) {
+ if (!error) return null;
+ return (
+ <Alert
+ icon={<Icon name="triangle-alert" size={16} />}
+ color="red"
+ variant="light"
+ p="xs"
+ radius="sm"
+ >
+ <Text size="xs">{error}</Text>
+ </Alert>
+ );
+}
+
+function NoFieldsMessage() {
+ const { t } = useTranslation();
+ const { state } = useFormFill();
+ if (state.fields.length > 0 || state.loading) return null;
+ return (
+ <Text size="xs" c="dimmed" ta="center" py="md">
+ {t("formFill.modify.empty", "This PDF has no form fields yet.")}
+ </Text>
+ );
+}
+
+function GoToPageButton({ pageIdx }: { pageIdx: number }) {
+ const { t } = useTranslation();
+ const { scrollActions } = useViewer();
+ const label = t("formFill.goToPage", "Go to this page");
+ return (
+ <Tooltip label={label} withArrow>
+ <ActionIcon
+ size="sm"
+ variant="tertiary"
+ aria-label={label}
+ data-testid={`form-page-goto-${pageIdx}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ scrollActions.scrollToPage(pageIdx + 1);
+ }}
+ >
+ <Icon name="locate-fixed" size={15} />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
+
+interface PageHeaderProps {
+ pageIdx: number;
+ first: boolean;
+ collapsed: boolean;
+ fieldCount: number;
+ onToggle: () => void;
+}
+
+function PageHeader({
+ pageIdx,
+ first,
+ collapsed,
+ fieldCount,
+ onToggle,
+}: PageHeaderProps) {
+ const { t } = useTranslation();
+ return (
+ <div
+ className={styles.pageDivider}
+ style={{
+ ...(first ? { marginTop: 0 } : {}),
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ gap: 4,
+ }}
+ onClick={onToggle}
+ data-testid={`form-page-header-${pageIdx}`}
+ >
+ <Icon
+ name="chevron-down"
+ size={16}
+ style={{
+ transform: collapsed ? "rotate(-90deg)" : undefined,
+ transition: "transform 120ms",
+ }}
+ />
+ <Text className={styles.pageDividerLabel}>
+ {t("formFill.page", "Page")} {pageIdx + 1}
+ </Text>
+ <Text size="xs" c="dimmed">
+ {fieldCount}
+ </Text>
+ <GoToPageButton pageIdx={pageIdx} />
+ </div>
+ );
+}
+
+function DeleteToggleButton({
+ fieldName,
+ deleted,
+}: {
+ fieldName: string;
+ deleted: boolean;
+}) {
+ const { t } = useTranslation();
+ const { toggleFieldDeleted } = useFormFill();
+ const label = deleted
+ ? t("formFill.modify.restore", "Restore")
+ : t("formFill.modify.delete", "Delete");
+ return (
+ <Tooltip label={label} withArrow>
+ <ActionIcon
+ size="sm"
+ variant="tertiary"
+ accent={deleted ? "default" : "danger"}
+ aria-label={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleFieldDeleted(fieldName);
+ }}
+ data-testid={`form-modify-delete-${fieldName}`}
+ >
+ <Icon name={deleted ? "rotate-ccw-clock" : "trash"} size={16} />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
+
+function FieldGeometryInputs({
+ field,
+ pageIdx,
+}: {
+ field: FormField;
+ pageIdx: number;
+}) {
+ const { t } = useTranslation();
+ const { modifiedFields, stageModification } = useFormFill();
+ const coords = currentCoords(field, modifiedFields[field.name]);
+ if (!coords) return null;
+ // Resizing a group here would only resize its first widget.
+ const multiWidget = (field.widgets?.length ?? 0) > 1;
+ const stageGeometry = (patch: Partial<FieldGeometry>) =>
+ stageModification(field.name, { pageIndex: pageIdx, ...coords, ...patch });
+ return (
+ <Group gap={6} mt="xs" grow>
+ <NumberInput
+ size="xs"
+ label="X"
+ value={Math.round(coords.x)}
+ onChange={(v) => typeof v === "number" && stageGeometry({ x: v })}
+ />
+ <NumberInput
+ size="xs"
+ label="Y"
+ value={Math.round(coords.y)}
+ onChange={(v) => typeof v === "number" && stageGeometry({ y: v })}
+ />
+ <NumberInput
+ size="xs"
+ label="W"
+ value={Math.round(coords.width)}
+ min={1}
+ disabled={multiWidget}
+ description={
+ multiWidget
+ ? t("formFill.modify.groupSizeHint", "Use Option size")
+ : undefined
+ }
+ onChange={(v) => typeof v === "number" && stageGeometry({ width: v })}
+ />
+ <NumberInput
+ size="xs"
+ label="H"
+ value={Math.round(coords.height)}
+ min={1}
+ disabled={multiWidget}
+ onChange={(v) => typeof v === "number" && stageGeometry({ height: v })}
+ />
+ </Group>
+ );
+}
+
+function FieldEditor({
+ field,
+ pageIdx,
+ open,
+}: {
+ field: FormField;
+ pageIdx: number;
+ open: boolean;
+}) {
+ const { modifiedFields, stageModification } = useFormFill();
+ // Built only while open: Collapse keeps its children mounted, so every
+ // unopened row would otherwise carry a full property editor.
+ if (!open) return null;
+ return (
+ <div style={{ marginTop: 8 }} onClick={(e) => e.stopPropagation()}>
+ <FormFieldPropertyEditor
+ value={editorValue(field, modifiedFields[field.name])}
+ onChange={(patch) =>
+ stageModification(field.name, patch as Partial<ModifyFieldDefinition>)
+ }
+ showName
+ allowTypeChange
+ />
+
+ <FieldGeometryInputs field={field} pageIdx={pageIdx} />
+ </div>
+ );
+}
+
+interface FieldRowProps {
+ field: FormField;
+ pageIdx: number;
+ selectedRowRef: RefObject<HTMLDivElement | null>;
+}
+
+function FieldRow({ field, pageIdx, selectedRowRef }: FieldRowProps) {
+ const { selectedFieldName, setSelectedField, deletedFieldNames } =
+ useFormFill();
+ const selected = selectedFieldName === field.name;
+ const deleted = deletedFieldNames.includes(field.name);
+ const editing = selected && !deleted;
+ return (
+ <Paper
+ ref={selected ? selectedRowRef : undefined}
+ withBorder
+ p={6}
+ radius="sm"
+ style={{
+ cursor: "pointer",
+ borderColor: selected ? "var(--mantine-color-blue-5)" : undefined,
+ opacity: deleted ? 0.55 : 1,
+ }}
+ onClick={() => setSelectedField(selected ? null : field.name)}
+ data-testid={`form-modify-row-${field.name}`}
+ >
+ <Group gap={6} wrap="nowrap" justify="space-between">
+ <Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
+ <span
+ style={{
+ color: `var(--mantine-color-${FIELD_TYPE_COLOR[field.type]}-6)`,
+ display: "flex",
+ }}
+ >
+ <Icon name={FIELD_TYPE_ICON[field.type]} size={16} />
+ </span>
+ <Text size="xs" truncate td={deleted ? "line-through" : undefined}>
+ {field.label || field.name}
+ </Text>
+ </Group>
+ <DeleteToggleButton fieldName={field.name} deleted={deleted} />
+ </Group>
+
+ <Collapse in={editing}>
+ <FieldEditor field={field} pageIdx={pageIdx} open={editing} />
+ </Collapse>
+ </Paper>
+ );
+}
+
+interface PageSectionProps {
+ pageIdx: number;
+ fields: FormField[];
+ first: boolean;
+ collapsed: boolean;
+ onToggle: () => void;
+ selectedRowRef: RefObject<HTMLDivElement | null>;
+}
+
+function PageSection({
+ pageIdx,
+ fields,
+ first,
+ collapsed,
+ onToggle,
+ selectedRowRef,
+}: PageSectionProps) {
+ return (
+ <>
+ <PageHeader
+ pageIdx={pageIdx}
+ first={first}
+ collapsed={collapsed}
+ fieldCount={fields.length}
+ onToggle={onToggle}
+ />
+
+ <Collapse in={!collapsed}>
+ {fields.map((field) => (
+ <FieldRow
+ key={field.name}
+ field={field}
+ pageIdx={pageIdx}
+ selectedRowRef={selectedRowRef}
+ />
+ ))}
+ </Collapse>
+ </>
+ );
+}
+
export function FormFieldModifyPanel({
currentFile,
onApplied,
@@ -81,9 +422,7 @@ export function FormFieldModifyPanel({
selectedFieldName,
setSelectedField,
modifiedFields,
- stageModification,
deletedFieldNames,
- toggleFieldDeleted,
commitModifications,
hasUncommittedChanges,
dragActiveRef,
@@ -101,7 +440,6 @@ export function FormFieldModifyPanel({
else next.add(pageIdx);
return next;
});
- const { scrollActions } = useViewer();
const { sortedPages, fieldsByPage } = useMemo(() => {
const byPage = new Map<number, FormField[]>();
@@ -151,36 +489,6 @@ export function FormFieldModifyPanel({
);
}, [currentFile, hasUncommittedChanges, commitModifications, commit]);
- const editorValue = useCallback(
- (field: FormField): EditableFieldProps => {
- const staged = modifiedFields[field.name];
- return {
- name: staged?.name ?? field.name,
- label: staged?.label ?? field.label,
- type: staged?.type ?? field.type,
- defaultValue: staged?.defaultValue ?? field.value,
- tooltip: staged?.tooltip ?? field.tooltip ?? "",
- fontSize: staged?.fontSize ?? field.widgets?.[0]?.fontSize,
- required: staged?.required ?? field.required,
- readOnly: staged?.readOnly ?? field.readOnly,
- multiline: staged?.multiline ?? field.multiline,
- multiSelect: staged?.multiSelect ?? field.multiSelect,
- options: staged?.options ?? field.options ?? [],
- // Test for the staged KEY, not its value, or an explicit clear reads as
- // "unchanged" and the input snaps back.
- maxLength:
- staged && "maxLength" in staged
- ? staged.maxLength
- : (field.maxLength ?? undefined),
- buttonAction:
- staged && "buttonAction" in staged
- ? staged.buttonAction
- : (field.buttonActionSpec ?? undefined),
- };
- },
- [modifiedFields],
- );
-
return (
<div className={styles.root}>
<div className={styles.header}>
@@ -191,264 +499,25 @@ export function FormFieldModifyPanel({
)}
</Text>
- {error && (
- <Alert
- icon={<Icon name="triangle-alert" size={16} />}
- color="red"
- variant="light"
- p="xs"
- radius="sm"
- >
- <Text size="xs">{error}</Text>
- </Alert>
- )}
+ <CommitErrorAlert error={error} />
<SkippedEditsAlert />
- {state.fields.length === 0 && !state.loading && (
- <Text size="xs" c="dimmed" ta="center" py="md">
- {t("formFill.modify.empty", "This PDF has no form fields yet.")}
- </Text>
- )}
+ <NoFieldsMessage />
</div>
<ScrollArea className={styles.fieldList}>
<div className={styles.fieldListInner}>
{sortedPages.map((pageIdx, i) => (
- <React.Fragment key={pageIdx}>
- <div
- className={styles.pageDivider}
- style={{
- ...(i === 0 ? { marginTop: 0 } : {}),
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- gap: 4,
- }}
- onClick={() => togglePage(pageIdx)}
- data-testid={`form-page-header-${pageIdx}`}
- >
- <Icon
- name="chevron-down"
- size={16}
- style={{
- transform: collapsedPages.has(pageIdx)
- ? "rotate(-90deg)"
- : undefined,
- transition: "transform 120ms",
- }}
- />
- <Text className={styles.pageDividerLabel}>
- {t("formFill.page", "Page")} {pageIdx + 1}
- </Text>
- <Text size="xs" c="dimmed">
- {fieldsByPage.get(pageIdx)!.length}
- </Text>
- <Tooltip
- label={t("formFill.goToPage", "Go to this page")}
- withArrow
- >
- <ActionIcon
- size="sm"
- variant="tertiary"
- aria-label={t("formFill.goToPage", "Go to this page")}
- data-testid={`form-page-goto-${pageIdx}`}
- onClick={(e) => {
- e.stopPropagation();
- scrollActions.scrollToPage(pageIdx + 1);
- }}
- >
- <Icon name="locate-fixed" size={15} />
- </ActionIcon>
- </Tooltip>
- </div>
-
- <Collapse in={!collapsedPages.has(pageIdx)}>
- {fieldsByPage.get(pageIdx)!.map((field) => {
- const selected = selectedFieldName === field.name;
- const deleted = deletedFieldNames.includes(field.name);
- const coords = currentCoords(
- field,
- modifiedFields[field.name],
- );
- // Resizing a group here would only resize its first widget.
- const multiWidget = (field.widgets?.length ?? 0) > 1;
- return (
- <Paper
- key={field.name}
- ref={selected ? selectedRowRef : undefined}
- withBorder
- p={6}
- radius="sm"
- style={{
- cursor: "pointer",
- borderColor: selected
- ? "var(--mantine-color-blue-5)"
- : undefined,
- opacity: deleted ? 0.55 : 1,
- }}
- onClick={() =>
- setSelectedField(selected ? null : field.name)
- }
- data-testid={`form-modify-row-${field.name}`}
- >
- <Group gap={6} wrap="nowrap" justify="space-between">
- <Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
- <span
- style={{
- color: `var(--mantine-color-${FIELD_TYPE_COLOR[field.type]}-6)`,
- display: "flex",
- }}
- >
- <Icon
- name={FIELD_TYPE_ICON[field.type]}
- size={16}
- />
- </span>
- <Text
- size="xs"
- truncate
- td={deleted ? "line-through" : undefined}
- >
- {field.label || field.name}
- </Text>
- </Group>
- <Tooltip
- label={
- deleted
- ? t("formFill.modify.restore", "Restore")
- : t("formFill.modify.delete", "Delete")
- }
- withArrow
- >
- <ActionIcon
- size="sm"
- variant="tertiary"
- accent={deleted ? "default" : "danger"}
- aria-label={
- deleted
- ? t("formFill.modify.restore", "Restore")
- : t("formFill.modify.delete", "Delete")
- }
- onClick={(e) => {
- e.stopPropagation();
- toggleFieldDeleted(field.name);
- }}
- data-testid={`form-modify-delete-${field.name}`}
- >
- {deleted ? (
- <Icon name="rotate-ccw-clock" size={16} />
- ) : (
- <Icon name="trash" size={16} />
- )}
- </ActionIcon>
- </Tooltip>
- </Group>
-
- {/* Children are built only while open: Collapse keeps them mounted, so
- every unopened row would otherwise carry a full property editor. */}
- <Collapse in={selected && !deleted}>
- {selected && !deleted && (
- <div
- style={{ marginTop: 8 }}
- onClick={(e) => e.stopPropagation()}
- >
- <FormFieldPropertyEditor
- value={editorValue(field)}
- onChange={(patch) =>
- stageModification(
- field.name,
- patch as Partial<ModifyFieldDefinition>,
- )
- }
- showName
- allowTypeChange
- />
-
- {coords && (
- <Group gap={6} mt="xs" grow>
- <NumberInput
- size="xs"
- label="X"
- value={Math.round(coords.x)}
- onChange={(v) =>
- typeof v === "number" &&
- stageModification(field.name, {
- pageIndex: pageIdx,
- x: v,
- y: coords.y,
- width: coords.width,
- height: coords.height,
- })
- }
- />
- <NumberInput
- size="xs"
- label="Y"
- value={Math.round(coords.y)}
- onChange={(v) =>
- typeof v === "number" &&
- stageModification(field.name, {
- pageIndex: pageIdx,
- x: coords.x,
- y: v,
- width: coords.width,
- height: coords.height,
- })
- }
- />
- <NumberInput
- size="xs"
- label="W"
- value={Math.round(coords.width)}
- min={1}
- disabled={multiWidget}
- description={
- multiWidget
- ? t(
- "formFill.modify.groupSizeHint",
- "Use Option size",
- )
- : undefined
- }
- onChange={(v) =>
- typeof v === "number" &&
- stageModification(field.name, {
- pageIndex: pageIdx,
- x: coords.x,
- y: coords.y,
- width: v,
- height: coords.height,
- })
- }
- />
- <NumberInput
- size="xs"
- label="H"
- value={Math.round(coords.height)}
- min={1}
- disabled={multiWidget}
- onChange={(v) =>
- typeof v === "number" &&
- stageModification(field.name, {
- pageIndex: pageIdx,
- x: coords.x,
- y: coords.y,
- width: coords.width,
- height: v,
- })
- }
- />
- </Group>
- )}
- </div>
- )}
- </Collapse>
- </Paper>
- );
- })}
- </Collapse>
- </React.Fragment>
+ <PageSection
+ key={pageIdx}
+ pageIdx={pageIdx}
+ fields={fieldsByPage.get(pageIdx)!}
+ first={i === 0}
+ collapsed={collapsedPages.has(pageIdx)}
+ onToggle={() => togglePage(pageIdx)}
+ selectedRowRef={selectedRowRef}
+ />
))}
</div>
</ScrollArea>
diff --git a/frontend/editor/src/core/ui/DataTable.tsx b/frontend/editor/src/core/ui/DataTable.tsx
index 552f522931..c8ad2e410d 100644
--- a/frontend/editor/src/core/ui/DataTable.tsx
+++ b/frontend/editor/src/core/ui/DataTable.tsx
@@ -1,10 +1,19 @@
-import { type KeyboardEvent, type ReactNode, useMemo, useState } from "react";
+import {
+ type HTMLAttributes,
+ type KeyboardEvent,
+ type ReactNode,
+ useMemo,
+ useState,
+} from "react";
import { Icon } from "@app/ui/Icon";
import {
type ColumnDef,
createColumnHelper,
createSortedRowModel,
flexRender,
+ type Header,
+ type HeaderGroup,
+ type Row,
type RowData,
rowSortingFeature,
sortFn_alphanumeric,
@@ -71,6 +80,11 @@ export interface DataTableGroup<T> {
muted?: boolean;
}
+interface CollapseLabels {
+ showAll: (total: number) => string;
+ showLess: string;
+}
+
export interface DataTableProps<T> {
/** Columns built with the `column` vocabulary — never raw JSX. */
columns: DataTableColumn<T>[];
@@ -107,7 +121,7 @@ export interface DataTableProps<T> {
caption?: string;
/** Labels for a group's "show all / show less" toggle (pass translated).
* `showAll` receives the group's total row count. */
- collapseLabels?: { showAll: (total: number) => string; showLess: string };
+ collapseLabels?: CollapseLabels;
}
function SortGlyph() {
@@ -126,6 +140,11 @@ function SortGlyph() {
const CHEVRON_COLUMN_KEY = "__affordance";
+type RowPropsFn<T> = (
+ original: T,
+ muted?: boolean,
+) => HTMLAttributes<HTMLTableRowElement>;
+
/**
* The shared Stirling table. Call-sites supply data + behaviour; the component
* owns 100% of the appearance. Columns come from the `column` vocabulary (typed
@@ -252,11 +271,9 @@ export function DataTable<T extends RowData>({
getRowId: (row) => rowKey(row),
});
- const colCount = effectiveColumns.length;
-
// Shared row wiring so grouped rows behave like flat ones (interactivity +
// the affordance column) instead of being a second-class path.
- const rowProps = (original: T, muted?: boolean) => {
+ const rowProps: RowPropsFn<T> = (original, muted) => {
const rowInteractive =
interactive && (isRowInteractive?.(original) ?? true);
// A row that owns the whole interaction takes the button role + keyboard
@@ -284,198 +301,383 @@ export function DataTable<T extends RowData>({
};
};
+ return (
+ <div className={`sui-datatable sui-datatable--${variant}`}>
+ <div className="sui-datatable__frame">
+ <DataTableToolbar toolbar={toolbar} />
+ <div className="sui-datatable__scroll">
+ <table className="sui-datatable__table">
+ <DataTableCaption caption={caption} />
+ <DataTableHead headerGroups={table.getHeaderGroups()} />
+ <tbody>
+ <BodyRows
+ columns={effectiveColumns}
+ sortedRows={table.getRowModel().rows}
+ groups={groups}
+ loading={loading}
+ skeletonRows={skeletonRows}
+ error={error}
+ empty={empty}
+ rowKey={rowKey}
+ rowProps={rowProps}
+ openGroups={openGroups}
+ onToggleGroup={toggleGroup}
+ collapseLabels={resolvedCollapseLabels}
+ />
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function DataTableToolbar({ toolbar }: { toolbar: ReactNode }) {
+ if (!toolbar) return null;
+ return <div className="sui-datatable__toolbar">{toolbar}</div>;
+}
+
+function DataTableCaption({ caption }: { caption?: string }) {
+ if (!caption) return null;
+ return <caption className="sui-datatable__caption">{caption}</caption>;
+}
+
+function DataTableHead<T extends RowData>({
+ headerGroups,
+}: {
+ headerGroups: HeaderGroup<DataTableFeatures, T>[];
+}) {
+ return (
+ <thead>
+ {headerGroups.map((headerGroup) => (
+ <tr key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <HeaderCell key={header.id} header={header} />
+ ))}
+ </tr>
+ ))}
+ </thead>
+ );
+}
+
+function HeaderCell<T extends RowData>({
+ header,
+}: {
+ header: Header<DataTableFeatures, T>;
+}) {
+ const meta = header.column.columnDef.meta;
+ return (
+ <th
+ scope="col"
+ className={headerClass(meta?.align ?? "left", meta?.fit ?? false)}
+ aria-sort={ariaSort(header)}
+ >
+ <HeaderContent header={header} />
+ </th>
+ );
+}
+
+function HeaderContent<T extends RowData>({
+ header,
+}: {
+ header: Header<DataTableFeatures, T>;
+}) {
+ const label = header.isPlaceholder
+ ? null
+ : flexRender(header.column.columnDef.header, header.getContext());
+ if (header.column.getCanSort()) {
+ return (
+ <button
+ type="button"
+ className="sui-datatable__sort"
+ onClick={header.column.getToggleSortingHandler()}
+ >
+ {label}
+ <span
+ className={`sui-datatable__sort-icon sui-datatable__sort-icon--${header.column.getIsSorted() || "none"}`}
+ >
+ <SortGlyph />
+ </span>
+ </button>
+ );
+ }
+ const srHeader = header.column.columnDef.meta?.srHeader;
+ if (srHeader) {
+ return <span className="sui-datatable__th-sr">{srHeader}</span>;
+ }
+ return label;
+}
+
+function ariaSort<T extends RowData>(header: Header<DataTableFeatures, T>) {
+ if (!header.column.getCanSort()) return undefined;
+ const sorted = header.column.getIsSorted();
+ if (sorted === "asc") return "ascending";
+ if (sorted === "desc") return "descending";
+ return "none";
+}
+
+interface BodyRowsProps<T extends RowData> {
+ columns: DataTableColumn<T>[];
+ sortedRows: Row<DataTableFeatures, T>[];
+ groups?: DataTableGroup<T>[];
+ loading: boolean;
+ skeletonRows: number;
+ error?: ReactNode;
+ empty?: ReactNode;
+ rowKey: (row: T) => string;
+ rowProps: RowPropsFn<T>;
+ openGroups: Set<string>;
+ onToggleGroup: (key: string) => void;
+ collapseLabels: CollapseLabels;
+}
+
+function BodyRows<T extends RowData>({
+ columns,
+ sortedRows,
+ groups,
+ loading,
+ skeletonRows,
+ error,
+ empty,
+ rowKey,
+ rowProps,
+ openGroups,
+ onToggleGroup,
+ collapseLabels,
+}: BodyRowsProps<T>) {
// No rows at all - covers a grouped table whose groups are all empty (or an
// empty groups list), which would otherwise render a header-only table.
const noRows = groups
? groups.every((g) => g.rows.length === 0)
- : rows.length === 0;
-
- let body: ReactNode;
- if (loading) {
- body = Array.from({ length: skeletonRows }).map((_, r) => (
- <tr key={`skeleton-${r}`} className="sui-datatable__row">
- {effectiveColumns.map((c) => (
- <td key={c.key} className={cellClass(c.align, c.nowrap, c.fit)}>
- <Skeleton
- height="0.75rem"
- width={c.align === "right" || c.fit ? "40%" : "70%"}
- />
- </td>
+ : sortedRows.length === 0;
+
+ if (loading) return <SkeletonRows count={skeletonRows} columns={columns} />;
+ if (error != null)
+ return <ErrorRow error={error} colCount={columns.length} />;
+ if (noRows) return <EmptyRow empty={empty} colCount={columns.length} />;
+ if (groups) {
+ return (
+ <>
+ {groups.map((group) => (
+ <GroupSection
+ key={group.key}
+ group={group}
+ open={openGroups.has(group.key)}
+ onToggle={() => onToggleGroup(group.key)}
+ columns={columns}
+ rowKey={rowKey}
+ rowProps={rowProps}
+ collapseLabels={collapseLabels}
+ />
))}
- </tr>
- ));
- } else if (error != null) {
- body = (
- <tr>
- <td
- className="sui-datatable__state sui-datatable__state--error"
- colSpan={colCount}
- role="alert"
- >
- {error}
- </td>
- </tr>
+ </>
);
- } else if (noRows) {
- const isNode = typeof empty === "object" && empty !== null;
- body = (
- <tr>
- <td
- className={
- isNode
- ? "sui-datatable__state sui-datatable__state--node"
- : "sui-datatable__state"
- }
- colSpan={colCount}
- >
- {empty ?? t("common.noData", "No data")}
- </td>
- </tr>
- );
- } else if (groups) {
- body = groups.flatMap((g) => {
- const limit = g.collapseAfter ?? Infinity;
- const open = openGroups.has(g.key);
- const overflow = g.rows.length > limit;
- const shown = overflow && !open ? g.rows.slice(0, limit) : g.rows;
- const header = (
- <tr key={`group-${g.key}`} className="sui-datatable__group">
- <td colSpan={colCount} className="sui-datatable__group-cell">
- <div className="sui-datatable__group-head">
- <div className="sui-datatable__group-title">
- <strong>{g.title}</strong>
- {g.meta && (
- <span className="sui-datatable__group-meta">{g.meta}</span>
- )}
- </div>
- {g.actions &&
- g.actions.length > 0 &&
- renderCellActions(g.actions)}
- </div>
- </td>
+ }
+ return <FlatRows rows={sortedRows} rowProps={rowProps} />;
+}
+
+function SkeletonRows<T>({
+ count,
+ columns,
+}: {
+ count: number;
+ columns: DataTableColumn<T>[];
+}) {
+ return (
+ <>
+ {Array.from({ length: count }).map((_, r) => (
+ <tr key={`skeleton-${r}`} className="sui-datatable__row">
+ {columns.map((c) => (
+ <td key={c.key} className={cellClass(c.align, c.nowrap, c.fit)}>
+ <Skeleton
+ height="0.75rem"
+ width={c.align === "right" || c.fit ? "40%" : "70%"}
+ />
+ </td>
+ ))}
</tr>
- );
- const rowEls = shown.map((row) => (
+ ))}
+ </>
+ );
+}
+
+function ErrorRow({ error, colCount }: { error: ReactNode; colCount: number }) {
+ return (
+ <tr>
+ <td
+ className="sui-datatable__state sui-datatable__state--error"
+ colSpan={colCount}
+ role="alert"
+ >
+ {error}
+ </td>
+ </tr>
+ );
+}
+
+function EmptyRow({ empty, colCount }: { empty: ReactNode; colCount: number }) {
+ const { t } = useTranslation();
+ const isNode = typeof empty === "object" && empty !== null;
+ return (
+ <tr>
+ <td
+ className={
+ isNode
+ ? "sui-datatable__state sui-datatable__state--node"
+ : "sui-datatable__state"
+ }
+ colSpan={colCount}
+ >
+ {empty ?? t("common.noData", "No data")}
+ </td>
+ </tr>
+ );
+}
+
+interface GroupSectionProps<T> {
+ group: DataTableGroup<T>;
+ open: boolean;
+ onToggle: () => void;
+ columns: DataTableColumn<T>[];
+ rowKey: (row: T) => string;
+ rowProps: RowPropsFn<T>;
+ collapseLabels: CollapseLabels;
+}
+
+function GroupSection<T>({
+ group,
+ open,
+ onToggle,
+ columns,
+ rowKey,
+ rowProps,
+ collapseLabels,
+}: GroupSectionProps<T>) {
+ const limit = group.collapseAfter ?? Infinity;
+ const overflow = group.rows.length > limit;
+ const shown = overflow && !open ? group.rows.slice(0, limit) : group.rows;
+ return (
+ <>
+ <GroupHeaderRow group={group} colCount={columns.length} />
+ {shown.map((row) => (
<tr
key={rowKey(row)}
data-row-key={rowKey(row)}
- {...rowProps(row, g.muted)}
+ {...rowProps(row, group.muted)}
>
- {effectiveColumns.map((c) => (
+ {columns.map((c) => (
<td key={c.key} className={cellClass(c.align, c.nowrap, c.fit)}>
{c.renderCell(row)}
</td>
))}
</tr>
- ));
- const moreEl = overflow ? (
- <tr key={`more-${g.key}`}>
- <td colSpan={colCount} className="sui-datatable__group-more">
- <button
- type="button"
- className="sui-datatable__show-all"
- onClick={() => toggleGroup(g.key)}
- >
- {open
- ? resolvedCollapseLabels.showLess
- : resolvedCollapseLabels.showAll(g.rows.length)}
- </button>
- </td>
- </tr>
- ) : null;
- return moreEl ? [header, ...rowEls, moreEl] : [header, ...rowEls];
- });
- } else {
- body = table.getRowModel().rows.map((row) => (
- <tr key={row.id} data-row-key={row.id} {...rowProps(row.original)}>
- {row.getAllCells().map((cell) => {
- const meta = cell.column.columnDef.meta;
- return (
- <td
- key={cell.id}
- className={cellClass(
- meta?.align ?? "left",
- meta?.nowrap ?? false,
- meta?.fit ?? false,
- )}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </td>
- );
- })}
- </tr>
- ));
- }
+ ))}
+ <GroupToggleRow
+ overflow={overflow}
+ open={open}
+ total={group.rows.length}
+ colCount={columns.length}
+ labels={collapseLabels}
+ onToggle={onToggle}
+ />
+ </>
+ );
+}
+function GroupHeaderRow<T>({
+ group,
+ colCount,
+}: {
+ group: DataTableGroup<T>;
+ colCount: number;
+}) {
return (
- <div className={`sui-datatable sui-datatable--${variant}`}>
- <div className="sui-datatable__frame">
- {toolbar && <div className="sui-datatable__toolbar">{toolbar}</div>}
- <div className="sui-datatable__scroll">
- <table className="sui-datatable__table">
- {caption && (
- <caption className="sui-datatable__caption">{caption}</caption>
- )}
- <thead>
- {table.getHeaderGroups().map((headerGroup) => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
- const meta = header.column.columnDef.meta;
- const align = meta?.align ?? "left";
- const canSort = header.column.getCanSort();
- const sorted = header.column.getIsSorted();
- const label = header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- );
- return (
- <th
- key={header.id}
- scope="col"
- className={headerClass(align, meta?.fit ?? false)}
- aria-sort={
- canSort
- ? sorted === "asc"
- ? "ascending"
- : sorted === "desc"
- ? "descending"
- : "none"
- : undefined
- }
- >
- {canSort ? (
- <button
- type="button"
- className="sui-datatable__sort"
- onClick={header.column.getToggleSortingHandler()}
- >
- {label}
- <span
- className={`sui-datatable__sort-icon sui-datatable__sort-icon--${sorted || "none"}`}
- >
- <SortGlyph />
- </span>
- </button>
- ) : meta?.srHeader ? (
- <span className="sui-datatable__th-sr">
- {meta.srHeader}
- </span>
- ) : (
- label
- )}
- </th>
- );
- })}
- </tr>
- ))}
- </thead>
- <tbody>{body}</tbody>
- </table>
+ <tr className="sui-datatable__group">
+ <td colSpan={colCount} className="sui-datatable__group-cell">
+ <div className="sui-datatable__group-head">
+ <div className="sui-datatable__group-title">
+ <strong>{group.title}</strong>
+ <GroupMeta meta={group.meta} />
+ </div>
+ <GroupActions actions={group.actions} />
</div>
- </div>
- </div>
+ </td>
+ </tr>
+ );
+}
+
+function GroupMeta({ meta }: { meta?: string }) {
+ if (!meta) return null;
+ return <span className="sui-datatable__group-meta">{meta}</span>;
+}
+
+function GroupActions({ actions }: { actions?: CellAction[] }) {
+ if (!actions || actions.length === 0) return null;
+ return renderCellActions(actions);
+}
+
+interface GroupToggleRowProps {
+ overflow: boolean;
+ open: boolean;
+ total: number;
+ colCount: number;
+ labels: CollapseLabels;
+ onToggle: () => void;
+}
+
+function GroupToggleRow({
+ overflow,
+ open,
+ total,
+ colCount,
+ labels,
+ onToggle,
+}: GroupToggleRowProps) {
+ if (!overflow) return null;
+ return (
+ <tr>
+ <td colSpan={colCount} className="sui-datatable__group-more">
+ <button
+ type="button"
+ className="sui-datatable__show-all"
+ onClick={onToggle}
+ >
+ {open ? labels.showLess : labels.showAll(total)}
+ </button>
+ </td>
+ </tr>
+ );
+}
+
+function FlatRows<T extends RowData>({
+ rows,
+ rowProps,
+}: {
+ rows: Row<DataTableFeatures, T>[];
+ rowProps: RowPropsFn<T>;
+}) {
+ return (
+ <>
+ {rows.map((row) => (
+ <tr key={row.id} data-row-key={row.id} {...rowProps(row.original)}>
+ {row.getAllCells().map((cell) => {
+ const meta = cell.column.columnDef.meta;
+ return (
+ <td
+ key={cell.id}
+ className={cellClass(
+ meta?.align ?? "left",
+ meta?.nowrap ?? false,
+ meta?.fit ?? false,
+ )}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </>
);
}
diff --git a/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx
index 1f0b64c1f3..ae024276c1 100644
--- a/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx
+++ b/frontend/editor/src/proprietary/components/account-link/CreditPromptPipelines.tsx
@@ -1,6 +1,7 @@
import { useEffect, useId, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
+import { type TFunction } from "i18next";
import { Button, ToggleSwitch } from "@app/ui";
import { Icon } from "@app/ui/Icon";
import { Tooltip } from "@app/ui/Tooltip";
@@ -11,6 +12,10 @@ import {
} from "@app/services/creditPromptPipelines";
import { pipelineQueryKeys } from "@app/policies/queryKeys";
+const VISIBLE_PIPELINES = 5;
+
+type PipelineError = "load" | "save" | null;
+
interface Props {
onManagePipeline?: (id?: string) => void;
affectedPipelineId?: string;
@@ -29,7 +34,7 @@ export function CreditPromptPipelines({
const [canManage, setCanManage] = useState(false);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState<string | null>(null);
- const [error, setError] = useState<"load" | "save" | null>(null);
+ const [error, setError] = useState<PipelineError>(null);
useEffect(() => {
let active = true;
fetchCreditPromptPipelines()
@@ -79,28 +84,6 @@ export function CreditPromptPipelines({
}
}
- function sourceLabel(pipeline: CreditPromptPipeline) {
- const labels = pipeline.sources.map((source) => source.name);
- if (pipeline.editor?.allowed || pipeline.trigger.startsWith("editor-")) {
- labels.unshift(
- pipeline.editor?.runOn === "export" ||
- pipeline.trigger === "editor-export"
- ? t(
- "portal.accountLink.pipelines.editorExport",
- "Editor · before download",
- )
- : t(
- "portal.accountLink.pipelines.editorUpload",
- "Editor · on upload",
- ),
- );
- }
- return (
- labels.join(", ") ||
- t("portal.accountLink.pipelines.manual", "Manual runs")
- );
- }
-
return (
<section className="portal-connect__pipelines">
<div className="portal-connect__pipeline-header">
@@ -115,124 +98,263 @@ export function CreditPromptPipelines({
<span>
{t("portal.accountLink.pipelines.title", "Active pipelines")}
</span>
- {!loading && error !== "load" && (
- <span className="portal-connect__pipeline-count">
- {" "}
- {pipelines.filter((pipeline) => pipeline.enabled).length}
- </span>
- )}
+ <EnabledCount
+ loaded={!loading && error !== "load"}
+ pipelines={pipelines}
+ />
</button>
- {onManagePipeline && (
- <Button
- size="sm"
- px="none"
- variant="quiet"
- accent="neutral"
- onClick={() =>
- onManagePipeline(
- pipelines.length > 5 ? undefined : affectedPipelineId,
- )
- }
- >
- {pipelines.length > 5
- ? t("portal.accountLink.pipelines.viewAll", "View all pipelines")
- : t(
- "portal.accountLink.failure.manage",
- "Open pipeline settings",
- )}
- </Button>
- )}
+ <ManagePipelinesButton
+ pipelines={pipelines}
+ affectedPipelineId={affectedPipelineId}
+ onManagePipeline={onManagePipeline}
+ />
</div>
- {expanded && (
- <div id={listId} className="portal-connect__pipeline-choices">
- {loading ? (
- <p className="portal-connect__lede">
- {t("portal.accountLink.pipelines.loading", "Loading pipelines…")}
- </p>
- ) : (
- <>
- {!error && pipelines.length === 0 && (
- <p className="portal-connect__lede">
- {t(
- "portal.accountLink.pipelines.empty",
- "No active pipelines.",
- )}
- </p>
- )}
- <ul className="portal-connect__pipeline-list">
- {pipelines.slice(0, 5).map((pipeline) => (
- <li key={pipeline.id}>
- <div className="portal-connect__pipeline-details">
- <span className="portal-connect__row-label">
- {pipeline.name}
- {pipeline.id === affectedPipelineId && (
- <Tooltip
- content={t(
- "portal.accountLink.pipelines.triggered",
- "Triggered this prompt",
- )}
- >
- <button
- type="button"
- className="portal-connect__trigger-info"
- aria-label={t(
- "portal.accountLink.pipelines.triggered",
- "Triggered this prompt",
- )}
- >
- <Icon name="info" size={14} />
- </button>
- </Tooltip>
- )}
- </span>
- <span className="portal-connect__pipeline-source">
- {sourceLabel(pipeline)}
-
- {pipeline.required && (
- <span className="portal-connect__pipeline-note">
- {t(
- "portal.accountLink.pipelines.required",
- "Required policy · manage in pipeline settings",
- )}
- </span>
- )}
- {!pipeline.enabled && (
- <span className="portal-connect__pipeline-note">
- {t("portal.accountLink.pipelines.paused", "Paused")}
- </span>
- )}
- </span>
- </div>
- <ToggleSwitch
- aria-label={pipeline.name}
- checked={pipeline.enabled}
- disabled={
- !canManage || pipeline.required || busy !== null
- }
- onChange={(enabled) =>
- void changeEnabled(pipeline, enabled)
- }
- />
- </li>
- ))}
- </ul>
- </>
- )}
- {error && (
- <p role="alert" className="portal-connect__lede">
- {error === "load"
- ? t(
- "portal.accountLink.pipelines.loadFailed",
- "Could not load pipelines. Open pipeline settings to try again.",
- )
- : t(
- "portal.accountLink.pipelines.saveFailed",
- "Could not change this pipeline. Open pipeline settings to review it.",
- )}
- </p>
- )}
- </div>
- )}
+ <PipelineChoices
+ expanded={expanded}
+ id={listId}
+ loading={loading}
+ error={error}
+ pipelines={pipelines}
+ affectedPipelineId={affectedPipelineId}
+ togglesDisabled={!canManage || busy !== null}
+ onChangeEnabled={changeEnabled}
+ />
</section>
);
}
+
+function EnabledCount({
+ loaded,
+ pipelines,
+}: {
+ loaded: boolean;
+ pipelines: CreditPromptPipeline[];
+}) {
+ if (!loaded) return null;
+ return (
+ <span className="portal-connect__pipeline-count">
+ {" "}
+ {pipelines.filter((pipeline) => pipeline.enabled).length}
+ </span>
+ );
+}
+
+function ManagePipelinesButton({
+ pipelines,
+ affectedPipelineId,
+ onManagePipeline,
+}: {
+ pipelines: CreditPromptPipeline[];
+ affectedPipelineId?: string;
+ onManagePipeline?: (id?: string) => void;
+}) {
+ const { t } = useTranslation();
+ if (!onManagePipeline) return null;
+ const showsAll = pipelines.length > VISIBLE_PIPELINES;
+ return (
+ <Button
+ size="sm"
+ px="none"
+ variant="quiet"
+ accent="neutral"
+ onClick={() =>
+ onManagePipeline(showsAll ? undefined : affectedPipelineId)
+ }
+ >
+ {showsAll
+ ? t("portal.accountLink.pipelines.viewAll", "View all pipelines")
+ : t("portal.accountLink.failure.manage", "Open pipeline settings")}
+ </Button>
+ );
+}
+
+interface PipelineListProps {
+ loading: boolean;
+ error: PipelineError;
+ pipelines: CreditPromptPipeline[];
+ affectedPipelineId?: string;
+ togglesDisabled: boolean;
+ onChangeEnabled: (
+ pipeline: CreditPromptPipeline,
+ enabled: boolean,
+ ) => Promise<void>;
+}
+
+interface PipelineChoicesProps extends PipelineListProps {
+ expanded: boolean;
+ id: string;
+}
+
+function PipelineChoices({ expanded, id, ...list }: PipelineChoicesProps) {
+ if (!expanded) return null;
+ return (
+ <div id={id} className="portal-connect__pipeline-choices">
+ <PipelineList {...list} />
+ <PipelineErrorMessage error={list.error} />
+ </div>
+ );
+}
+
+function PipelineList({
+ loading,
+ error,
+ pipelines,
+ affectedPipelineId,
+ togglesDisabled,
+ onChangeEnabled,
+}: PipelineListProps) {
+ const { t } = useTranslation();
+ if (loading) {
+ return (
+ <p className="portal-connect__lede">
+ {t("portal.accountLink.pipelines.loading", "Loading pipelines…")}
+ </p>
+ );
+ }
+ return (
+ <>
+ <NoPipelinesNote show={!error && pipelines.length === 0} />
+ <ul className="portal-connect__pipeline-list">
+ {pipelines.slice(0, VISIBLE_PIPELINES).map((pipeline) => (
+ <PipelineRow
+ key={pipeline.id}
+ pipeline={pipeline}
+ triggered={pipeline.id === affectedPipelineId}
+ toggleDisabled={togglesDisabled || pipeline.required}
+ onToggle={(enabled) => void onChangeEnabled(pipeline, enabled)}
+ />
+ ))}
+ </ul>
+ </>
+ );
+}
+
+function NoPipelinesNote({ show }: { show: boolean }) {
+ const { t } = useTranslation();
+ if (!show) return null;
+ return (
+ <p className="portal-connect__lede">
+ {t("portal.accountLink.pipelines.empty", "No active pipelines.")}
+ </p>
+ );
+}
+
+interface PipelineRowProps {
+ pipeline: CreditPromptPipeline;
+ triggered: boolean;
+ toggleDisabled: boolean;
+ onToggle: (enabled: boolean) => void;
+}
+
+function PipelineRow({
+ pipeline,
+ triggered,
+ toggleDisabled,
+ onToggle,
+}: PipelineRowProps) {
+ const { t } = useTranslation();
+ return (
+ <li>
+ <div className="portal-connect__pipeline-details">
+ <span className="portal-connect__row-label">
+ {pipeline.name}
+ <TriggeredInfo triggered={triggered} />
+ </span>
+ <span className="portal-connect__pipeline-source">
+ {sourceLabel(t, pipeline)}
+ <PipelineNotes pipeline={pipeline} />
+ </span>
+ </div>
+ <ToggleSwitch
+ aria-label={pipeline.name}
+ checked={pipeline.enabled}
+ disabled={toggleDisabled}
+ onChange={onToggle}
+ />
+ </li>
+ );
+}
+
+function TriggeredInfo({ triggered }: { triggered: boolean }) {
+ const { t } = useTranslation();
+ if (!triggered) return null;
+ const label = t(
+ "portal.accountLink.pipelines.triggered",
+ "Triggered this prompt",
+ );
+ return (
+ <Tooltip content={label}>
+ <button
+ type="button"
+ className="portal-connect__trigger-info"
+ aria-label={label}
+ >
+ <Icon name="info" size={14} />
+ </button>
+ </Tooltip>
+ );
+}
+
+function PipelineNotes({ pipeline }: { pipeline: CreditPromptPipeline }) {
+ const { t } = useTranslation();
+ const notes = [
+ {
+ key: "required",
+ shown: pipeline.required,
+ text: t(
+ "portal.accountLink.pipelines.required",
+ "Required policy · manage in pipeline settings",
+ ),
+ },
+ {
+ key: "paused",
+ shown: !pipeline.enabled,
+ text: t("portal.accountLink.pipelines.paused", "Paused"),
+ },
+ ].filter((note) => note.shown);
+ return (
+ <>
+ {notes.map((note) => (
+ <span key={note.key} className="portal-connect__pipeline-note">
+ {note.text}
+ </span>
+ ))}
+ </>
+ );
+}
+
+function PipelineErrorMessage({ error }: { error: PipelineError }) {
+ const { t } = useTranslation();
+ if (!error) return null;
+ return (
+ <p role="alert" className="portal-connect__lede">
+ {error === "load"
+ ? t(
+ "portal.accountLink.pipelines.loadFailed",
+ "Could not load pipelines. Open pipeline settings to try again.",
+ )
+ : t(
+ "portal.accountLink.pipelines.saveFailed",
+ "Could not change this pipeline. Open pipeline settings to review it.",
+ )}
+ </p>
+ );
+}
+
+function sourceLabel(t: TFunction, pipeline: CreditPromptPipeline) {
+ const labels = pipeline.sources.map((source) => source.name);
+ if (pipeline.editor?.allowed || pipeline.trigger.startsWith("editor-")) {
+ labels.unshift(
+ pipeline.editor?.runOn === "export" ||
+ pipeline.trigger === "editor-export"
+ ? t(
+ "portal.accountLink.pipelines.editorExport",
+ "Editor · before download",
+ )
+ : t("portal.accountLink.pipelines.editorUpload", "Editor · on upload"),
+ );
+ }
+ return (
+ labels.join(", ") || t("portal.accountLink.pipelines.manual", "Manual runs")
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx
index 854737f0ec..709c1b924f 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx
@@ -33,9 +33,151 @@ import { useLoginRequired } from "@app/hooks/useLoginRequired";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import EnterpriseRequiredBanner from "@app/components/shared/config/EnterpriseRequiredBanner";
import { Icon } from "@app/ui/Icon";
-const AdminAuditSection: React.FC = () => {
+
+type TimePeriod = "day" | "week" | "month";
+
+const ConfigureAuditBanner = ({ show }: { show: boolean }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ if (!show) return null;
+ return (
+ <Alert
+ icon={<Icon name="info" size="1.2rem" />}
+ title={t("audit.configureAudit", "Configure Audit Logging")}
+ color="blue"
+ variant="light"
+ >
+ <Stack gap="xs">
+ <Text size="sm">
+ {t(
+ "audit.configureAuditMessage",
+ "Adjust audit logging level, retention period, and other settings in the Security & Authentication section.",
+ )}
+ </Text>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => navigate("/settings/adminSecurity#auditLogging")}
+ rightSection={<Icon name="arrow-right" size="0.9rem" />}
+ >
+ {t("audit.goToSettings", "Go to Audit Settings")}
+ </Button>
+ </Stack>
+ </Alert>
+ );
+};
+
+interface AuditDashboardProps {
+ isEnabled: boolean;
+ timePeriod: TimePeriod;
+ onTimePeriodChange: (period: TimePeriod) => void;
+}
+
+const AuditDashboard = ({
+ isEnabled,
+ timePeriod,
+ onTimePeriodChange,
+}: AuditDashboardProps) => {
+ const { t } = useTranslation();
+ return (
+ <Stack gap="lg">
+ {/* Stats Cards - Always Visible */}
+ <AuditStatsCards loginEnabled={isEnabled} timePeriod={timePeriod} />
+
+ {/* Charts in Accordion - Collapsible */}
+ <Accordion defaultValue={["events-over-time"]} multiple>
+ <Accordion.Item value="events-over-time">
+ <Accordion.Control>
+ {t("audit.charts.overTime", "Events Over Time")}
+ </Accordion.Control>
+ <Accordion.Panel>
+ <Suspense
+ fallback={
+ <Center style={{ padding: "2rem" }}>
+ <Loader />
+ </Center>
+ }
+ >
+ <AuditChartsSection
+ loginEnabled={isEnabled}
+ timePeriod={timePeriod}
+ onTimePeriodChange={onTimePeriodChange}
+ />
+ </Suspense>
+ </Accordion.Panel>
+ </Accordion.Item>
+ </Accordion>
+ </Stack>
+ );
+};
+
+interface AuditTabsProps extends AuditDashboardProps {
+ status: AuditStatus;
+}
+
+const AuditTabs = ({ status, ...dashboard }: AuditTabsProps) => {
+ const { t } = useTranslation();
+ const { isEnabled } = dashboard;
+ if (!status.enabled) {
+ return (
+ <Alert
+ color="blue"
+ title={t("audit.disabled", "Audit logging is disabled")}
+ >
+ {t(
+ "audit.disabledMessage",
+ "Enable audit logging in your application configuration to track system events.",
+ )}
+ </Alert>
+ );
+ }
+ return (
+ <Tabs defaultValue="dashboard">
+ <Tabs.List>
+ <Tabs.Tab value="dashboard" disabled={!isEnabled}>
+ {t("audit.tabs.dashboard", "Dashboard")}
+ </Tabs.Tab>
+ <Tabs.Tab value="events" disabled={!isEnabled}>
+ {t("audit.tabs.events", "Audit Events")}
+ </Tabs.Tab>
+ <Tabs.Tab value="export" disabled={!isEnabled}>
+ {t("audit.tabs.export", "Export")}
+ </Tabs.Tab>
+ <Tabs.Tab value="clearData" disabled={!isEnabled}>
+ {t("audit.tabs.clearData", "Clear Data")}
+ </Tabs.Tab>
+ </Tabs.List>
+
+ <Tabs.Panel value="dashboard" pt="md">
+ <AuditDashboard {...dashboard} />
+ </Tabs.Panel>
+
+ <Tabs.Panel value="events" pt="md">
+ <AuditEventsTable
+ loginEnabled={isEnabled}
+ captureFileHash={status.captureFileHash}
+ capturePdfAuthor={status.capturePdfAuthor}
+ />
+ </Tabs.Panel>
+
+ <Tabs.Panel value="export" pt="md">
+ <AuditExportSection
+ loginEnabled={isEnabled}
+ captureFileHash={status.captureFileHash}
+ capturePdfAuthor={status.capturePdfAuthor}
+ captureOperationResults={status.captureOperationResults}
+ />
+ </Tabs.Panel>
+
+ <Tabs.Panel value="clearData" pt="md">
+ <AuditClearDataSection loginEnabled={isEnabled} />
+ </Tabs.Panel>
+ </Tabs>
+ );
+};
+
+const AdminAuditSection: React.FC = () => {
+ const { t } = useTranslation();
const { loginEnabled } = useLoginRequired();
const { config } = useAppConfig();
const licenseType = config?.license ?? "NORMAL";
@@ -44,9 +186,7 @@ const AdminAuditSection: React.FC = () => {
const [systemStatus, setSystemStatus] = useState<AuditStatus | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [timePeriod, setTimePeriod] = useState<"day" | "week" | "month">(
- "week",
- );
+ const [timePeriod, setTimePeriod] = useState<TimePeriod>("week");
useEffect(() => {
const fetchSystemStatus = async () => {
@@ -159,118 +299,16 @@ const AdminAuditSection: React.FC = () => {
featureName={t("settings.licensingAnalytics.audit", "Audit")}
/>
- {/* Info banner about audit settings */}
- {isEnabled && (
- <Alert
- icon={<Icon name="info" size="1.2rem" />}
- title={t("audit.configureAudit", "Configure Audit Logging")}
- color="blue"
- variant="light"
- >
- <Stack gap="xs">
- <Text size="sm">
- {t(
- "audit.configureAuditMessage",
- "Adjust audit logging level, retention period, and other settings in the Security & Authentication section.",
- )}
- </Text>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => navigate("/settings/adminSecurity#auditLogging")}
- rightSection={<Icon name="arrow-right" size="0.9rem" />}
- >
- {t("audit.goToSettings", "Go to Audit Settings")}
- </Button>
- </Stack>
- </Alert>
- )}
+ <ConfigureAuditBanner show={isEnabled} />
<AuditSystemStatus status={systemStatus} />
- {systemStatus?.enabled ? (
- <Tabs defaultValue="dashboard">
- <Tabs.List>
- <Tabs.Tab value="dashboard" disabled={!isEnabled}>
- {t("audit.tabs.dashboard", "Dashboard")}
- </Tabs.Tab>
- <Tabs.Tab value="events" disabled={!isEnabled}>
- {t("audit.tabs.events", "Audit Events")}
- </Tabs.Tab>
- <Tabs.Tab value="export" disabled={!isEnabled}>
- {t("audit.tabs.export", "Export")}
- </Tabs.Tab>
- <Tabs.Tab value="clearData" disabled={!isEnabled}>
- {t("audit.tabs.clearData", "Clear Data")}
- </Tabs.Tab>
- </Tabs.List>
-
- <Tabs.Panel value="dashboard" pt="md">
- <Stack gap="lg">
- {/* Stats Cards - Always Visible */}
- <AuditStatsCards
- loginEnabled={isEnabled}
- timePeriod={timePeriod}
- />
-
- {/* Charts in Accordion - Collapsible */}
- <Accordion defaultValue={["events-over-time"]} multiple>
- <Accordion.Item value="events-over-time">
- <Accordion.Control>
- {t("audit.charts.overTime", "Events Over Time")}
- </Accordion.Control>
- <Accordion.Panel>
- <Suspense
- fallback={
- <Center style={{ padding: "2rem" }}>
- <Loader />
- </Center>
- }
- >
- <AuditChartsSection
- loginEnabled={isEnabled}
- timePeriod={timePeriod}
- onTimePeriodChange={setTimePeriod}
- />
- </Suspense>
- </Accordion.Panel>
- </Accordion.Item>
- </Accordion>
- </Stack>
- </Tabs.Panel>
-
- <Tabs.Panel value="events" pt="md">
- <AuditEventsTable
- loginEnabled={isEnabled}
- captureFileHash={systemStatus?.captureFileHash}
- capturePdfAuthor={systemStatus?.capturePdfAuthor}
- />
- </Tabs.Panel>
-
- <Tabs.Panel value="export" pt="md">
- <AuditExportSection
- loginEnabled={isEnabled}
- captureFileHash={systemStatus?.captureFileHash}
- capturePdfAuthor={systemStatus?.capturePdfAuthor}
- captureOperationResults={systemStatus?.captureOperationResults}
- />
- </Tabs.Panel>
-
- <Tabs.Panel value="clearData" pt="md">
- <AuditClearDataSection loginEnabled={isEnabled} />
- </Tabs.Panel>
- </Tabs>
- ) : (
- <Alert
- color="blue"
- title={t("audit.disabled", "Audit logging is disabled")}
- >
- {t(
- "audit.disabledMessage",
- "Enable audit logging in your application configuration to track system events.",
- )}
- </Alert>
- )}
+ <AuditTabs
+ status={systemStatus}
+ isEnabled={isEnabled}
+ timePeriod={timePeriod}
+ onTimePeriodChange={setTimePeriod}
+ />
</Stack>
);
};
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx
index 7af0a30f79..42bd24a68f 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx
@@ -13,6 +13,11 @@ import {
import PendingBadge from "@app/components/shared/config/PendingBadge";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
import type { SecurityCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";
+import type { SecuritySettingsData } from "@app/components/shared/config/configSections/security/securitySettingsTypes";
+
+type UrlSecurity = NonNullable<
+ NonNullable<SecuritySettingsData["html"]>["urlSecurity"]
+>;
/** Where HTML-to-PDF conversions are allowed to fetch from (SSRF guard). */
export function HtmlUrlSecurityCard({
@@ -22,6 +27,17 @@ export function HtmlUrlSecurityCard({
loginEnabled,
}: SecurityCardProps) {
const { t } = useTranslation();
+ const urlSecurity = settings?.html?.urlSecurity;
+
+ function updateUrlSecurity(patch: Partial<UrlSecurity>) {
+ setSettings({
+ ...settings,
+ html: {
+ ...settings?.html,
+ urlSecurity: { ...urlSecurity, ...patch },
+ },
+ });
+ }
return (
<Paper withBorder p="md" radius="md">
@@ -36,19 +52,8 @@ export function HtmlUrlSecurityCard({
"Enable URL security restrictions for HTML to PDF conversions",
)}
pending={isFieldPending("html.urlSecurity.enabled")}
- checked={settings?.html?.urlSecurity?.enabled || false}
- onChange={(checked) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- enabled: checked,
- },
- },
- })
- }
+ checked={urlSecurity?.enabled || false}
+ onChange={(checked) => updateUrlSecurity({ enabled: checked })}
disabled={!loginEnabled}
/>
@@ -56,34 +61,21 @@ export function HtmlUrlSecurityCard({
<Select
name="html_urlSecurity_level"
label={
- <Group component="span" gap="xs">
- <span>
- {t(
- "admin.settings.security.htmlUrlSecurity.level.label",
- "Security Level",
- )}
- </span>
- <PendingBadge show={isFieldPending("html.urlSecurity.level")} />
- <InfoTooltip
- label={t(
- "admin.settings.security.htmlUrlSecurity.level.description",
- "MAX: whitelist only, MEDIUM: block internal networks, OFF: no restrictions",
- )}
- />
- </Group>
+ <UrlSecurityFieldLabel
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.level.label",
+ "Security Level",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.level.description",
+ "MAX: whitelist only, MEDIUM: block internal networks, OFF: no restrictions",
+ )}
+ pending={isFieldPending("html.urlSecurity.level")}
+ />
}
- value={settings?.html?.urlSecurity?.level || "MEDIUM"}
+ value={urlSecurity?.level || "MEDIUM"}
onChange={(value) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- level: value || "MEDIUM",
- },
- },
- })
+ updateUrlSecurity({ level: value || "MEDIUM" })
}
data={[
{
@@ -125,285 +117,212 @@ export function HtmlUrlSecurityCard({
)}
</Accordion.Control>
<Accordion.Panel>
- <Stack gap="md">
- {/* Allowed Domains */}
- <div>
- <Textarea
- name="html_urlSecurity_allowedDomains"
- label={
- <Group component="span" gap="xs">
- <span>
- {t(
- "admin.settings.security.htmlUrlSecurity.allowedDomains.label",
- "Allowed Domains (Whitelist)",
- )}
- </span>
- <PendingBadge
- show={isFieldPending(
- "html.urlSecurity.allowedDomains",
- )}
- />
- <InfoTooltip
- label={t(
- "admin.settings.security.htmlUrlSecurity.allowedDomains.description",
- "One domain per line (e.g., cdn.example.com). Only these domains allowed when level is MAX",
- )}
- />
- </Group>
- }
- value={
- settings?.html?.urlSecurity?.allowedDomains?.join("\n") ||
- ""
- }
- onChange={(e) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- allowedDomains: e.target.value
- ? e.target.value
- .split("\n")
- .filter((d) => d.trim())
- : [],
- },
- },
- })
- }
- placeholder="cdn.example.com&#10;images.google.com"
- minRows={3}
- autosize
- disabled={!loginEnabled}
- />
- </div>
+ <AdvancedUrlSecurityFields
+ urlSecurity={urlSecurity}
+ onChange={updateUrlSecurity}
+ isFieldPending={isFieldPending}
+ disabled={!loginEnabled}
+ />
+ </Accordion.Panel>
+ </Accordion.Item>
+ </Accordion>
+ </Stack>
+ </Paper>
+ );
+}
- {/* Blocked Domains */}
- <div>
- <Textarea
- name="html_urlSecurity_blockedDomains"
- label={
- <Group component="span" gap="xs">
- <span>
- {t(
- "admin.settings.security.htmlUrlSecurity.blockedDomains.label",
- "Blocked Domains (Blacklist)",
- )}
- </span>
- <PendingBadge
- show={isFieldPending(
- "html.urlSecurity.blockedDomains",
- )}
- />
- <InfoTooltip
- label={t(
- "admin.settings.security.htmlUrlSecurity.blockedDomains.description",
- "One domain per line (e.g., malicious.com). Additional domains to block",
- )}
- />
- </Group>
- }
- value={
- settings?.html?.urlSecurity?.blockedDomains?.join("\n") ||
- ""
- }
- onChange={(e) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- blockedDomains: e.target.value
- ? e.target.value
- .split("\n")
- .filter((d) => d.trim())
- : [],
- },
- },
- })
- }
- placeholder="malicious.com&#10;evil.org"
- minRows={3}
- autosize
- disabled={!loginEnabled}
- />
- </div>
+interface AdvancedUrlSecurityFieldsProps {
+ urlSecurity: UrlSecurity | undefined;
+ onChange: (patch: Partial<UrlSecurity>) => void;
+ isFieldPending: (field: string) => boolean;
+ disabled: boolean;
+}
- {/* Internal TLDs */}
- <div>
- <Textarea
- name="html_urlSecurity_internalTlds"
- label={
- <Group component="span" gap="xs">
- <span>
- {t(
- "admin.settings.security.htmlUrlSecurity.internalTlds.label",
- "Internal TLDs",
- )}
- </span>
- <PendingBadge
- show={isFieldPending("html.urlSecurity.internalTlds")}
- />
- <InfoTooltip
- label={t(
- "admin.settings.security.htmlUrlSecurity.internalTlds.description",
- "One TLD per line (e.g., .local, .internal). Block domains with these TLD patterns",
- )}
- />
- </Group>
- }
- value={
- settings?.html?.urlSecurity?.internalTlds?.join("\n") ||
- ""
- }
- onChange={(e) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- internalTlds: e.target.value
- ? e.target.value
- .split("\n")
- .filter((d) => d.trim())
- : [],
- },
- },
- })
- }
- placeholder=".local&#10;.internal&#10;.corp&#10;.home"
- minRows={3}
- autosize
- disabled={!loginEnabled}
- />
- </div>
+function AdvancedUrlSecurityFields({
+ urlSecurity,
+ onChange,
+ isFieldPending,
+ disabled,
+}: AdvancedUrlSecurityFieldsProps) {
+ const { t } = useTranslation();
+ return (
+ <Stack gap="md">
+ <DomainListField
+ name="html_urlSecurity_allowedDomains"
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.allowedDomains.label",
+ "Allowed Domains (Whitelist)",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.allowedDomains.description",
+ "One domain per line (e.g., cdn.example.com). Only these domains allowed when level is MAX",
+ )}
+ pending={isFieldPending("html.urlSecurity.allowedDomains")}
+ value={urlSecurity?.allowedDomains}
+ onChange={(allowedDomains) => onChange({ allowedDomains })}
+ placeholder="cdn.example.com&#10;images.google.com"
+ disabled={disabled}
+ />
- {/* Network Blocking Options */}
- <Text fw={600} size="sm" mt="md">
- {t(
- "admin.settings.security.htmlUrlSecurity.networkBlocking",
- "Network Blocking",
- )}
- </Text>
+ <DomainListField
+ name="html_urlSecurity_blockedDomains"
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.blockedDomains.label",
+ "Blocked Domains (Blacklist)",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.blockedDomains.description",
+ "One domain per line (e.g., malicious.com). Additional domains to block",
+ )}
+ pending={isFieldPending("html.urlSecurity.blockedDomains")}
+ value={urlSecurity?.blockedDomains}
+ onChange={(blockedDomains) => onChange({ blockedDomains })}
+ placeholder="malicious.com&#10;evil.org"
+ disabled={disabled}
+ />
- <SettingsToggleRow
- label={t(
- "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.label",
- "Block Private Networks",
- )}
- info={t(
- "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.description",
- "Block RFC 1918 private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x)",
- )}
- pending={isFieldPending(
- "html.urlSecurity.blockPrivateNetworks",
- )}
- checked={
- settings?.html?.urlSecurity?.blockPrivateNetworks || false
- }
- onChange={(checked) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- blockPrivateNetworks: checked,
- },
- },
- })
- }
- disabled={!loginEnabled}
- />
+ <DomainListField
+ name="html_urlSecurity_internalTlds"
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.internalTlds.label",
+ "Internal TLDs",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.internalTlds.description",
+ "One TLD per line (e.g., .local, .internal). Block domains with these TLD patterns",
+ )}
+ pending={isFieldPending("html.urlSecurity.internalTlds")}
+ value={urlSecurity?.internalTlds}
+ onChange={(internalTlds) => onChange({ internalTlds })}
+ placeholder=".local&#10;.internal&#10;.corp&#10;.home"
+ disabled={disabled}
+ />
- <SettingsToggleRow
- label={t(
- "admin.settings.security.htmlUrlSecurity.blockLocalhost.label",
- "Block Localhost",
- )}
- info={t(
- "admin.settings.security.htmlUrlSecurity.blockLocalhost.description",
- "Block localhost and loopback addresses (127.x.x.x, ::1)",
- )}
- pending={isFieldPending("html.urlSecurity.blockLocalhost")}
- checked={settings?.html?.urlSecurity?.blockLocalhost || false}
- onChange={(checked) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- blockLocalhost: checked,
- },
- },
- })
- }
- disabled={!loginEnabled}
- />
+ <Text fw={600} size="sm" mt="md">
+ {t(
+ "admin.settings.security.htmlUrlSecurity.networkBlocking",
+ "Network Blocking",
+ )}
+ </Text>
- <SettingsToggleRow
- label={t(
- "admin.settings.security.htmlUrlSecurity.blockLinkLocal.label",
- "Block Link-Local Addresses",
- )}
- info={t(
- "admin.settings.security.htmlUrlSecurity.blockLinkLocal.description",
- "Block link-local addresses (169.254.x.x, fe80::/10)",
- )}
- pending={isFieldPending("html.urlSecurity.blockLinkLocal")}
- checked={settings?.html?.urlSecurity?.blockLinkLocal || false}
- onChange={(checked) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- blockLinkLocal: checked,
- },
- },
- })
- }
- disabled={!loginEnabled}
- />
+ <SettingsToggleRow
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.label",
+ "Block Private Networks",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.description",
+ "Block RFC 1918 private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x)",
+ )}
+ pending={isFieldPending("html.urlSecurity.blockPrivateNetworks")}
+ checked={urlSecurity?.blockPrivateNetworks || false}
+ onChange={(checked) => onChange({ blockPrivateNetworks: checked })}
+ disabled={disabled}
+ />
- <SettingsToggleRow
- label={t(
- "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.label",
- "Block Cloud Metadata Endpoints",
- )}
- info={t(
- "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.description",
- "Block cloud provider metadata endpoints (169.254.169.254)",
- )}
- pending={isFieldPending(
- "html.urlSecurity.blockCloudMetadata",
- )}
- checked={
- settings?.html?.urlSecurity?.blockCloudMetadata || false
- }
- onChange={(checked) =>
- setSettings({
- ...settings,
- html: {
- ...settings?.html,
- urlSecurity: {
- ...settings?.html?.urlSecurity,
- blockCloudMetadata: checked,
- },
- },
- })
- }
- disabled={!loginEnabled}
- />
- </Stack>
- </Accordion.Panel>
- </Accordion.Item>
- </Accordion>
- </Stack>
- </Paper>
+ <SettingsToggleRow
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.blockLocalhost.label",
+ "Block Localhost",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.blockLocalhost.description",
+ "Block localhost and loopback addresses (127.x.x.x, ::1)",
+ )}
+ pending={isFieldPending("html.urlSecurity.blockLocalhost")}
+ checked={urlSecurity?.blockLocalhost || false}
+ onChange={(checked) => onChange({ blockLocalhost: checked })}
+ disabled={disabled}
+ />
+
+ <SettingsToggleRow
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.blockLinkLocal.label",
+ "Block Link-Local Addresses",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.blockLinkLocal.description",
+ "Block link-local addresses (169.254.x.x, fe80::/10)",
+ )}
+ pending={isFieldPending("html.urlSecurity.blockLinkLocal")}
+ checked={urlSecurity?.blockLinkLocal || false}
+ onChange={(checked) => onChange({ blockLinkLocal: checked })}
+ disabled={disabled}
+ />
+
+ <SettingsToggleRow
+ label={t(
+ "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.label",
+ "Block Cloud Metadata Endpoints",
+ )}
+ info={t(
+ "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.description",
+ "Block cloud provider metadata endpoints (169.254.169.254)",
+ )}
+ pending={isFieldPending("html.urlSecurity.blockCloudMetadata")}
+ checked={urlSecurity?.blockCloudMetadata || false}
+ onChange={(checked) => onChange({ blockCloudMetadata: checked })}
+ disabled={disabled}
+ />
+ </Stack>
+ );
+}
+
+function UrlSecurityFieldLabel({
+ label,
+ info,
+ pending,
+}: {
+ label: string;
+ info: string;
+ pending: boolean;
+}) {
+ return (
+ <Group component="span" gap="xs">
+ <span>{label}</span>
+ <PendingBadge show={pending} />
+ <InfoTooltip label={info} />
+ </Group>
+ );
+}
+
+interface DomainListFieldProps {
+ name: string;
+ label: string;
+ info: string;
+ pending: boolean;
+ value: string[] | undefined;
+ onChange: (value: string[]) => void;
+ placeholder: string;
+ disabled: boolean;
+}
+
+function DomainListField({
+ name,
+ label,
+ info,
+ pending,
+ value,
+ onChange,
+ placeholder,
+ disabled,
+}: DomainListFieldProps) {
+ return (
+ <div>
+ <Textarea
+ name={name}
+ label={
+ <UrlSecurityFieldLabel label={label} info={info} pending={pending} />
+ }
+ value={value?.join("\n") || ""}
+ onChange={(e) =>
+ onChange(e.target.value.split("\n").filter((line) => line.trim()))
+ }
+ placeholder={placeholder}
+ minRows={3}
+ autosize
+ disabled={disabled}
+ />
+ </div>
);
}
diff --git a/frontend/oxlint.config.ts b/frontend/oxlint.config.ts
index fc20e9b31a..48c0d6bd6b 100644
--- a/frontend/oxlint.config.ts
+++ b/frontend/oxlint.config.ts
@@ -199,7 +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: 9 }],
+ "react/jsx-max-depth": ["error", { max: 8 }],
},
overrides: [
{
@@ -389,6 +389,7 @@ export default defineConfig({
// depth counts providers rather than measuring how hard the tree is to read.
files: [
"editor/src/core/components/AppProviders.tsx",
+ "editor/src/portal/PortalProviders.tsx",
".storybook/preview.tsx",
],
rules: {