Merge remote-tracking branch 'origin/frontend'
ci / docker (frontend, frontend/Dockerfile, frontend) (push) Successful in 18m2s
ci / docker (backend, backend/Dockerfile, backend) (push) Successful in 18m23s

This commit is contained in:
2025-10-27 00:22:00 +01:00
13 changed files with 2234 additions and 966 deletions
+10
View File
@@ -8,6 +8,7 @@
"name": "papercrate-frontend",
"version": "0.1.0",
"dependencies": {
"@fontsource/inter": "^5.2.8",
"@tabler/icons-react": "3.11.0",
"axios": "1.7.7",
"react": "18.3.1",
@@ -1852,6 +1853,15 @@
"node": ">=10.0.0"
}
},
"node_modules/@fontsource/inter": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.2.8.tgz",
"integrity": "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+3 -2
View File
@@ -9,6 +9,7 @@
"lint": "echo \"No linting configured\""
},
"dependencies": {
"@fontsource/inter": "^5.2.8",
"@tabler/icons-react": "3.11.0",
"axios": "1.7.7",
"react": "18.3.1",
@@ -19,6 +20,7 @@
"@babel/core": "7.26.0",
"@babel/preset-env": "7.26.0",
"@babel/preset-react": "7.26.3",
"@svgr/webpack": "8.1.0",
"babel-loader": "9.2.1",
"css-loader": "7.1.2",
"dotenv": "16.4.5",
@@ -26,7 +28,6 @@
"style-loader": "4.0.0",
"webpack": "5.95.0",
"webpack-cli": "5.1.4",
"webpack-dev-server": "5.1.0",
"@svgr/webpack": "8.1.0"
"webpack-dev-server": "5.1.0"
}
}
@@ -118,11 +118,11 @@ function CorrespondentsPanel({
}, []);
return (
<section className="correspondents-panel column">
<div className="column-header">
<div className="column-header__titles">
<section className="correspondents-panel">
<div className="panel-section__header">
<div className="panel-section__titles">
<h2>Correspondents</h2>
<div className="column-subtitle">{correspondents.length} total</div>
<div className="panel-section__subtitle">{correspondents.length} total</div>
</div>
<div className="header-actions correspondents-actions">
<form className="correspondents-actions__form" onSubmit={handleCreate}>
@@ -147,7 +147,7 @@ function CorrespondentsPanel({
</button>
</div>
</div>
<div className="column-body tags-panel__body">
<div className="panel-section__body tags-panel__body">
{correspondents.length === 0 ? (
<div className="empty-state">No correspondents created yet.</div>
) : (
+322 -61
View File
@@ -1,11 +1,20 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { DownloadIcon, EditIcon, ArrowLeftIcon, ArrowRightIcon } from '../ui/icons';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
DownloadIcon,
EditIcon,
ArrowLeftIcon,
ArrowRightIcon,
ChevronsRightIcon,
AnalyzeIcon,
WindowMaximizeIcon,
TextScanIcon,
} from '../ui/icons';
import { getTagColorStyle } from '../utils/colors';
import { formatFileSize } from '../utils/format';
import { resolveDocumentAssetUrl, createAssetView } from '../asset_manager';
import { useAssetNavigator } from '../hooks/useAssetNavigator';
import { CORRESPONDENT_ROLES } from '../constants/correspondents';
import PreviewZoomOverlay from './PreviewZoomOverlay';
const MAX_PREVIEW_STACK_ITEMS = 15;
@@ -208,6 +217,7 @@ const PreviewStack = ({
emptyMessage = 'Preview unavailable',
onItemActivate,
onOpenPreview,
onZoomPreview,
activeItemId = null,
}) => {
if (!items.length) {
@@ -240,7 +250,11 @@ const PreviewStack = ({
zIndex: preparedItems.length - index,
transform,
}}
aria-hidden={hasMultiple && !onItemActivate && !onOpenPreview ? 'true' : undefined}
aria-hidden={
hasMultiple && !onItemActivate && !onOpenPreview && !onZoomPreview
? 'true'
: undefined
}
>
<img
src={entry.url}
@@ -248,19 +262,31 @@ const PreviewStack = ({
className="preview-stack__image"
onClick={(event) => {
event.stopPropagation();
if (isFront && onOpenPreview) {
onOpenPreview(entry.id);
if (isFront) {
if (onZoomPreview) {
onZoomPreview(entry);
} else if (onOpenPreview) {
onOpenPreview(entry.id);
} else if (onItemActivate) {
onItemActivate(entry.id);
}
} else if (onItemActivate) {
onItemActivate(entry.id);
}
}}
onKeyDown={(event) => {
if (!onItemActivate && !onOpenPreview) return;
if (!onItemActivate && !onOpenPreview && !onZoomPreview) return;
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
event.stopPropagation();
if (isFront && onOpenPreview) {
onOpenPreview(entry.id);
if (isFront) {
if (onZoomPreview) {
onZoomPreview(entry);
} else if (onOpenPreview) {
onOpenPreview(entry.id);
} else {
onItemActivate?.(entry.id);
}
} else {
onItemActivate?.(entry.id);
}
@@ -297,9 +323,24 @@ const DetailPanel = ({
onCorrespondentAdd,
onCorrespondentRemove,
resolveApiPath,
onClose = () => {},
}) => {
const selectedCount = selectedDocuments.length;
const singleDoc = selectedCount === 1 ? selectedDocuments[0] : null;
const singleDocId = singleDoc?.id || null;
const selectionKey = useMemo(
() => selectedDocuments.map((doc) => doc?.id ?? '').join('|'),
[selectedDocuments],
);
const singleDownloadHref = useMemo(() => {
if (!singleDoc) return null;
const downloadPath = singleDoc.current_version?.download_path;
if (!downloadPath || !resolveApiPath) {
return null;
}
return resolveApiPath(downloadPath);
}, [singleDoc, resolveApiPath]);
const [titleEditDocId, setTitleEditDocId] = useState(null);
const [titleDraft, setTitleDraft] = useState('');
@@ -309,6 +350,7 @@ const DetailPanel = ({
const [ocrUrl, setOcrUrl] = useState(null);
const [ocrLoading, setOcrLoading] = useState(false);
const [ocrError, setOcrError] = useState(null);
const [zoomedPreview, setZoomedPreview] = useState(null);
useEffect(() => {
if (!singleDoc) {
@@ -338,6 +380,10 @@ const DetailPanel = ({
setOcrUrl(null);
}, [singleDoc?.id]);
useEffect(() => {
setZoomedPreview(null);
}, [selectionKey]);
const startTitleEdit = useCallback(() => {
if (!singleDoc) return;
setTitleEditDocId(singleDoc.id);
@@ -500,6 +546,7 @@ const DetailPanel = ({
}, [selectedDocuments]);
const stackTopDocument = stackDocuments[0] || null;
const stackTopDocId = stackTopDocument?.id || null;
const stackPreviewNavigator = useAssetNavigator({
document: stackTopDocument,
assetType: 'preview',
@@ -699,15 +746,178 @@ const DetailPanel = ({
[bulkCorrespondents, onBulkCorrespondentRemove, onCorrespondentRemove, selectedDocuments],
);
const openZoomPreview = useCallback((config) => {
if (!config) return;
setZoomedPreview({
mode: config.mode,
docId: config.docId ?? null,
});
}, []);
const closeZoomPreview = useCallback(() => {
setZoomedPreview(null);
}, []);
const handleSingleZoom = useCallback(
(entry) => {
if (!singleHasPreview) return;
const targetId = entry?.id ?? singleDocId;
if (!targetId) return;
openZoomPreview({ mode: 'single', docId: targetId });
},
[openZoomPreview, singleHasPreview, singleDocId],
);
const handleStackZoom = useCallback(
(entry) => {
if (!stackTopDocId || entry?.id !== stackTopDocId) return;
if (!topHasPreview) return;
openZoomPreview({ mode: 'stack', docId: stackTopDocId });
},
[openZoomPreview, stackTopDocId, topHasPreview],
);
const zoomDisplay = useMemo(() => {
if (!zoomedPreview) {
return null;
}
if (
zoomedPreview.mode === 'single' &&
singleDocId &&
singleDoc &&
singleHasPreview &&
zoomedPreview.docId === singleDocId
) {
return {
url: singlePreviewNavigator.currentUrl,
alt: singleDoc.title || singleDoc.original_name || 'Document preview',
canGoPrev:
singleEffectiveCardinality > 1 && Boolean(singlePreviewNavigator.canGoPrev),
canGoNext:
singleEffectiveCardinality > 1 && Boolean(singlePreviewNavigator.canGoNext),
goPrev: singlePreviewNavigator.goPrev,
goNext: singlePreviewNavigator.goNext,
};
}
if (
zoomedPreview.mode === 'stack' &&
stackTopDocId &&
stackTopDocument &&
zoomedPreview.docId === stackTopDocId &&
topHasPreview
) {
return {
url: stackPreviewNavigator.currentUrl,
alt: stackTopDocument.title || stackTopDocument.original_name || 'Document preview',
canGoPrev:
topEffectiveCardinality > 1 && Boolean(stackPreviewNavigator.canGoPrev),
canGoNext:
topEffectiveCardinality > 1 && Boolean(stackPreviewNavigator.canGoNext),
goPrev: stackPreviewNavigator.goPrev,
goNext: stackPreviewNavigator.goNext,
};
}
return null;
}, [
zoomedPreview,
singleDoc,
singleDocId,
singleHasPreview,
singlePreviewNavigator.currentUrl,
singlePreviewNavigator.canGoPrev,
singlePreviewNavigator.canGoNext,
singlePreviewNavigator.goPrev,
singlePreviewNavigator.goNext,
singleEffectiveCardinality,
stackTopDocument,
stackTopDocId,
topHasPreview,
stackPreviewNavigator.currentUrl,
stackPreviewNavigator.canGoPrev,
stackPreviewNavigator.canGoNext,
stackPreviewNavigator.goPrev,
stackPreviewNavigator.goNext,
topEffectiveCardinality,
]);
useEffect(() => {
if (zoomedPreview && !zoomDisplay) {
setZoomedPreview(null);
}
}, [zoomedPreview, zoomDisplay]);
useEffect(() => {
if (typeof ensureAssetUrl !== 'function') {
return;
}
const warmNavigator = (navigator) => {
const {
documentId,
asset,
ordinal,
canGoPrev,
canGoNext,
cardinality,
} = navigator;
if (!documentId || !asset || !Number.isFinite(ordinal)) {
return;
}
const requests = [];
if (canGoPrev) {
const prevOrdinal = Math.max(1, ordinal - 1);
if (!cardinality || prevOrdinal <= cardinality) {
requests.push(
ensureAssetUrl(documentId, asset, {
start: prevOrdinal,
limit: 1,
objectOrdinal: prevOrdinal,
}),
);
}
}
if (canGoNext) {
const nextOrdinal = ordinal + 1;
if (!cardinality || nextOrdinal <= cardinality) {
requests.push(
ensureAssetUrl(documentId, asset, {
start: nextOrdinal,
limit: 1,
objectOrdinal: nextOrdinal,
}),
);
}
}
requests.forEach((promise) => promise?.catch?.(() => {}));
};
warmNavigator(singlePreviewNavigator);
warmNavigator(stackPreviewNavigator);
}, [
ensureAssetUrl,
singlePreviewNavigator.documentId,
singlePreviewNavigator.asset,
singlePreviewNavigator.ordinal,
singlePreviewNavigator.canGoPrev,
singlePreviewNavigator.canGoNext,
stackPreviewNavigator.documentId,
stackPreviewNavigator.asset,
stackPreviewNavigator.ordinal,
stackPreviewNavigator.canGoPrev,
stackPreviewNavigator.canGoNext,
]);
const renderSingle = () => {
if (!singleDoc) {
return <p className="meta">Select a document to view metadata, tags and actions.</p>;
}
const displayName = singleDoc.title || singleDoc.original_name;
const downloadHref = singleDoc.current_version?.download_path
? resolveApiPath?.(singleDoc.current_version.download_path)
: null;
const isEditingTitle = titleEditDocId === singleDoc.id;
const sizeBytes = Number(singleDoc.current_version?.size_bytes) || 0;
const sizeLabel = sizeBytes > 0 ? formatFileSize(sizeBytes) : '—';
@@ -743,6 +953,7 @@ const DetailPanel = ({
emptyMessage="Preview loading…"
onItemActivate={handlePreviewActivate}
onOpenPreview={onOpenPreview}
onZoomPreview={handleSingleZoom}
activeItemId={activePreviewId}
/>
{hasPreviewImage && (effectiveCardinality > 1 || canGoPrev || canGoNext) ? (
@@ -857,44 +1068,6 @@ const DetailPanel = ({
{singleDoc.original_name}
</div>
</div>
<div className="detail-actions">
<a
className="button-link with-icon"
href={downloadHref || '#'}
target="_blank"
rel="noopener noreferrer"
aria-disabled={!downloadHref}
onClick={(event) => {
if (!downloadHref) {
event.preventDefault();
}
}}
>
<DownloadIcon className="icon-inline" />
<span>Download</span>
</a>
<button
type="button"
className="secondary"
onClick={() => onOpenPreview(singleDoc.id)}
>
Open preview
</button>
<button
type="button"
className="secondary"
onClick={() => onRegenerateThumbnails(singleDoc.id)}
>
Re-run analysis
</button>
</div>
{hasOcrAsset ? (
<div className="detail-ocr-trigger">
<button type="button" className="secondary" onClick={openOcrModal}>
View OCR text
</button>
</div>
) : null}
<TagSection
title="Tags"
tags={tagsForDoc.map((tag) => ({
@@ -931,7 +1104,7 @@ const DetailPanel = ({
{metadata && (
<div>
<dt>Metadata</dt>
<pre>{JSON.stringify(metadata, null, 2)}</pre>
<pre className="detail-metadata__block">{JSON.stringify(metadata, null, 2)}</pre>
</div>
)}
{hasOcrAsset && ocrOpen
@@ -1002,6 +1175,7 @@ const DetailPanel = ({
emptyMessage="No previews available."
onItemActivate={handlePreviewActivate}
onOpenPreview={onOpenPreview}
onZoomPreview={handleStackZoom}
activeItemId={activePreviewId}
/>
{topDocIdLocal && topHasPreview && (topCardinalityLocal > 1 || topCanGoPrev || topCanGoNext) ? (
@@ -1074,23 +1248,110 @@ const DetailPanel = ({
showCount
className="bulk-correspondents"
/>
<button
type="button"
className="secondary"
onClick={() => onBulkReanalyze?.()}
>
Re-analyze selection
</button>
</>
);
};
const isBulkSelection = selectedCount > 1;
const showOcrAction = Boolean(singleDoc && hasOcrAsset);
return (
<aside className="detail-panel column">
<div className="column-body scrollable">
<>
<aside className="detail-panel panel">
<div className="panel-header">
<div className="panel-actions">
<button
type="button"
className="icon-button ghost"
onClick={onClose}
aria-label="Close detail panel"
title="Close detail panel"
>
<ChevronsRightIcon />
</button>
<div className="spacer" />
{isBulkSelection && onBulkReanalyze ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onBulkReanalyze();
}}
aria-label="Re-run analysis for selection"
title="Re-run analysis for selection"
>
<AnalyzeIcon />
</button>
) : null}
{singleDoc && singleDownloadHref ? (
<a
className="icon-button"
href={singleDownloadHref}
target="_blank"
rel="noopener noreferrer"
aria-label="Download document"
title="Download document"
onClick={(event) => event.stopPropagation()}
>
<DownloadIcon />
</a>
) : null}
{singleDoc ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onOpenPreview(singleDoc.id);
}}
aria-label="Open preview"
title="Open preview"
disabled={!singleHasPreview}
>
<WindowMaximizeIcon />
</button>
) : null}
{showOcrAction ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
openOcrModal();
}}
aria-label="View OCR text"
title="View OCR text"
>
<TextScanIcon />
</button>
) : null}
{singleDoc ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onRegenerateThumbnails(singleDoc.id);
}}
aria-label="Re-run analysis"
title="Re-run analysis"
>
<AnalyzeIcon />
</button>
) : null}
</div>
</div>
<div className="panel-body">
{selectedCount <= 1 ? renderSingle() : renderBulk()}
</div>
</aside>
</aside>
<PreviewZoomOverlay
open={Boolean(zoomDisplay?.url)}
display={zoomDisplay}
onClose={closeZoomPreview}
/>
</>
);
};
+262
View File
@@ -0,0 +1,262 @@
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ArrowLeftIcon, ArrowRightIcon } from '../ui/icons';
const noop = () => {};
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
};
const ensureDocumentRoot = () => {
if (typeof document === 'undefined') {
return null;
}
return document.body;
};
const PreviewZoomOverlay = ({
open = false,
display = null,
onClose = noop,
}) => {
const portalTarget = ensureDocumentRoot();
const [isNativeScale, setIsNativeScale] = useState(false);
const [naturalSize, setNaturalSize] = useState({ width: null, height: null });
const scrollRef = useRef(null);
const imageRef = useRef(null);
const focusRef = useRef(null);
const previouslyFocusedRef = useRef(null);
useEffect(() => {
setIsNativeScale(false);
setNaturalSize({ width: null, height: null });
focusRef.current = null;
const scrollEl = scrollRef.current;
if (scrollEl) {
scrollEl.scrollLeft = 0;
scrollEl.scrollTop = 0;
}
}, [open]);
useEffect(() => {
if (!open || !isNativeScale) {
return;
}
const scrollEl = scrollRef.current;
const imageEl = imageRef.current;
if (!scrollEl || !imageEl) {
return;
}
const imageWidth = imageEl.naturalWidth || imageEl.clientWidth;
const imageHeight = imageEl.naturalHeight || imageEl.clientHeight;
if (!(imageWidth > 0 && imageHeight > 0)) {
return;
}
const target = focusRef.current || { xRatio: 0.5, yRatio: 0.5 };
const maxScrollLeft = Math.max(0, imageWidth - scrollEl.clientWidth);
const maxScrollTop = Math.max(0, imageHeight - scrollEl.clientHeight);
const desiredLeft = target.xRatio * imageWidth - scrollEl.clientWidth / 2;
const desiredTop = target.yRatio * imageHeight - scrollEl.clientHeight / 2;
scrollEl.scrollLeft = clamp(desiredLeft, 0, maxScrollLeft);
scrollEl.scrollTop = clamp(desiredTop, 0, maxScrollTop);
}, [open, isNativeScale, naturalSize.width, naturalSize.height]);
useEffect(() => {
if (!open) {
if (previouslyFocusedRef.current && typeof previouslyFocusedRef.current.focus === 'function') {
previouslyFocusedRef.current.focus();
}
previouslyFocusedRef.current = null;
return undefined;
}
if (typeof document !== 'undefined') {
const active = document.activeElement;
if (active && typeof active.focus === 'function') {
previouslyFocusedRef.current = active;
} else {
previouslyFocusedRef.current = null;
}
}
const scrollEl = scrollRef.current;
if (!scrollEl) {
return undefined;
}
const frame = requestAnimationFrame(() => {
scrollEl.focus();
});
return () => {
cancelAnimationFrame(frame);
if (previouslyFocusedRef.current && typeof previouslyFocusedRef.current.focus === 'function') {
previouslyFocusedRef.current.focus();
previouslyFocusedRef.current = null;
}
};
}, [open]);
const handleKeyDown = (event) => {
event.stopPropagation();
if (!open) {
return;
}
if (event.key === 'Escape') {
event.preventDefault();
onClose();
return;
}
if (event.key === 'ArrowLeft') {
if (display?.canGoPrev && display?.goPrev) {
event.preventDefault();
display.goPrev();
}
return;
}
if (event.key === 'ArrowRight') {
if (display?.canGoNext && display?.goNext) {
event.preventDefault();
display.goNext();
}
}
};
if (!open || !display?.url || !portalTarget) {
return null;
}
const navVisible = Boolean(display?.canGoPrev || display?.canGoNext);
const stageClassName = [
'preview-zoom__stage',
]
.filter(Boolean)
.join(' ');
const containerClassName = [
'preview-zoom__scroll',
isNativeScale ? 'preview-zoom__scroll--native' : '',
]
.filter(Boolean)
.join(' ');
const imageStyle = isNativeScale
? {
cursor: 'zoom-out',
width: naturalSize.width ? `${naturalSize.width}px` : 'auto',
height: naturalSize.height ? `${naturalSize.height}px` : 'auto',
maxWidth: 'none',
maxHeight: 'none',
}
: {
cursor: 'zoom-in',
maxWidth: '95vw',
maxHeight: '95vh',
};
return createPortal(
(
<div
className="preview-zoom-backdrop"
role="dialog"
aria-modal="true"
aria-label="Enlarged document preview"
onClick={onClose}
>
<div
className={stageClassName}
onClick={(event) => event.stopPropagation()}
onKeyDown={handleKeyDown}
>
<div
className={containerClassName}
ref={scrollRef}
tabIndex={-1}
>
<img
src={display.url}
alt={display.alt || 'Document preview'}
className="preview-zoom__image"
ref={imageRef}
draggable={false}
onLoad={(event) => {
setNaturalSize({
width: event.currentTarget.naturalWidth || null,
height: event.currentTarget.naturalHeight || null,
});
}}
onClick={(event) => {
event.stopPropagation();
if (!isNativeScale) {
const img = imageRef.current;
if (img) {
const rect = img.getBoundingClientRect();
const xRatio = rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0.5;
const yRatio = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;
focusRef.current = {
xRatio: clamp(xRatio, 0, 1),
yRatio: clamp(yRatio, 0, 1),
};
} else {
focusRef.current = null;
}
} else {
focusRef.current = null;
}
setIsNativeScale((current) => !current);
}}
style={imageStyle}
/>
</div>
{navVisible ? (
<div className="preview-zoom__nav">
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.canGoPrev && display?.goPrev) {
display.goPrev();
}
}}
aria-label="Previous preview"
disabled={!display?.canGoPrev}
>
<ArrowLeftIcon />
</button>
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.canGoNext && display?.goNext) {
display.goNext();
}
}}
aria-label="Next preview"
disabled={!display?.canGoNext}
>
<ArrowRightIcon />
</button>
</div>
) : null}
</div>
</div>
),
portalTarget,
);
};
export default PreviewZoomOverlay;
+189 -131
View File
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getAssetFromVersion, resolveDocumentAssetUrl, createAssetView } from '../asset_manager';
import { getTagColorStyle } from '../utils/colors';
import { DownloadIcon, EditIcon, ViewListIcon, ViewGridIcon, FolderIcon } from '../ui/icons';
import { DownloadIcon, EditIcon, ViewListIcon, ViewGridIcon, FolderIcon, TrashIcon } from '../ui/icons';
const TAG_MIME_TYPES = ['application/x-papercrate-tag', 'text/papercrate-tag'];
const DEFAULT_GRID_ICON_SIZE = 96;
@@ -13,13 +13,62 @@ const getPageCount = (doc) =>
? doc.current_version.metadata.page_count
: null;
// Detects when an element becomes visible within a scroll container.
const useLazyVisibility = (rootRef, resetKey) => {
const targetRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
setIsVisible(false);
}, [resetKey]);
const rootNode = rootRef?.current || null;
useEffect(() => {
if (isVisible) {
return undefined;
}
const element = targetRef.current;
if (!element) {
return undefined;
}
if (typeof window === 'undefined' || typeof IntersectionObserver === 'undefined') {
setIsVisible(true);
return undefined;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.disconnect();
}
});
},
{
root: rootNode,
rootMargin: '200px 0px',
threshold: 0.01,
},
);
observer.observe(element);
return () => observer.disconnect();
}, [isVisible, rootNode, resetKey]);
return { ref: targetRef, isVisible };
};
const DocumentThumbnailImage = ({
document,
ensureAssetUrl,
getDocumentAsset,
alt,
maxSize = LIST_ICON_SIZE,
scrollRootRef = null,
}) => {
const { ref: visibilityRef, isVisible } = useLazyVisibility(scrollRootRef, document?.id);
const resolvedMaxSize = Math.max(1, Math.round(maxSize || 1));
const thumbnailAsset = useMemo(
() => getAssetFromVersion(document?.current_version, 'thumbnail'),
@@ -45,14 +94,15 @@ const DocumentThumbnailImage = ({
() => ({ width: `${dimensions.width}px`, height: `${dimensions.height}px` }),
[dimensions.height, dimensions.width],
);
const url = useMemo(
() =>
resolveDocumentAssetUrl(document, 'thumbnail', {
ensureAssetUrl,
getAsset: getDocumentAsset,
}),
[document, ensureAssetUrl, getDocumentAsset],
);
const url = useMemo(() => {
if (!isVisible) {
return null;
}
return resolveDocumentAssetUrl(document, 'thumbnail', {
ensureAssetUrl,
getAsset: getDocumentAsset,
});
}, [document, ensureAssetUrl, getDocumentAsset, isVisible]);
const pageCount = getPageCount(document);
const showMultiPageBadge = Number.isFinite(pageCount) && pageCount > 1;
@@ -62,13 +112,15 @@ const DocumentThumbnailImage = ({
}
return (
<div className="document-thumbnail-wrapper">
<div className="document-thumbnail-wrapper" ref={visibilityRef}>
<div className={innerClasses.join(' ')} style={innerStyle}>
{url ? (
<img
src={url}
alt={alt || ''}
className="document-thumbnail"
loading="lazy"
decoding="async"
draggable={false}
onDragStart={(event) => event.preventDefault()}
/>
@@ -125,6 +177,7 @@ const DocumentsTable = ({
viewMode = 'list',
onViewModeChange,
onClearSelection,
showHeader = true,
}) => {
const showingSearchResults = searchResults !== null;
const rows = showingSearchResults ? searchResults : documents;
@@ -142,6 +195,18 @@ const DocumentsTable = ({
[draggingDocumentIds],
);
const scrollRef = useRef(null);
const [, forceVisibilityTick] = useState(0);
const lastScrollNodeRef = useRef(null);
const assignScrollRef = useCallback((node) => {
if (lastScrollNodeRef.current === node) {
return;
}
lastScrollNodeRef.current = node;
scrollRef.current = node;
if (node) {
forceVisibilityTick((value) => value + 1);
}
}, []);
const isGridView = viewMode === 'grid';
const gridIconSize = DEFAULT_GRID_ICON_SIZE;
const handleSetViewMode = useCallback(
@@ -156,6 +221,11 @@ const DocumentsTable = ({
},
[onViewModeChange],
);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = 0;
}
}, [viewMode]);
const isTagDragEvent = useCallback((event) => {
const types = Array.from(event.dataTransfer?.types || []);
return TAG_MIME_TYPES.some((type) => types.includes(type));
@@ -263,16 +333,6 @@ const DocumentsTable = ({
[isTagDragEvent, onDocumentTagDrop],
);
const handleGridBackgroundClick = useCallback(
(event) => {
if (event.target !== event.currentTarget) {
return;
}
onClearSelection?.();
},
[onClearSelection],
);
const showDefaultEmptyState = !showingSearchResults && !subfolders.length && rows.length === 0;
const showListSearchEmptyState =
showingSearchResults && rows.length === 0 && !isGridView && !isSearchLoading;
@@ -282,73 +342,53 @@ const DocumentsTable = ({
return (
<section
className={`documents-panel column documents-panel--view-${isGridView ? 'grid' : 'list'}`}
className={`documents-panel documents-panel--view-${isGridView ? 'grid' : 'list'}`}
>
<div className="column-header">
<div className="column-header__titles">
<nav className="breadcrumb" aria-label="Folder breadcrumbs">
{breadcrumbs.map((crumb, index) => {
const isLast = index === breadcrumbs.length - 1;
return (
<span key={crumb.id} className="breadcrumb-item">
{isLast ? (
<span className="breadcrumb-current">{crumb.name}</span>
) : (
<a
href="#"
onClick={(event) => {
event.preventDefault();
onFolderSelect(crumb.id);
}}
>
{crumb.name}
</a>
)}
{!isLast && <span className="breadcrumb-separator"></span>}
</span>
);
})}
</nav>
{showingSearchResults && (
<div className="column-subtitle">Search results</div>
)}
</div>
<div className="header-actions">
<div className="view-toggle" role="group" aria-label="Change view">
{showHeader ? (
<div className="panel-section__header">
<div className="panel-section__titles">
<h2>{currentFolderName}</h2>
{showingSearchResults && (
<div className="panel-section__subtitle">Search results</div>
)}
</div>
<div className="header-actions">
<div className="view-toggle" role="group" aria-label="Change view">
<button
type="button"
className={`view-toggle__button${isGridView ? '' : ' active'}`}
onClick={() => handleSetViewMode('list')}
aria-pressed={!isGridView}
title="List view"
>
<ViewListIcon className="view-toggle__icon" size={18} />
</button>
<button
type="button"
className={`view-toggle__button${isGridView ? ' active' : ''}`}
onClick={() => handleSetViewMode('grid')}
aria-pressed={isGridView}
title="Icons view"
>
<ViewGridIcon className="view-toggle__icon" size={18} />
</button>
</div>
<button
type="button"
className={`view-toggle__button${isGridView ? '' : ' active'}`}
onClick={() => handleSetViewMode('list')}
aria-pressed={!isGridView}
title="List view"
onClick={onRequestCreateFolder}
disabled={creatingFolder}
>
<ViewListIcon className="view-toggle__icon" size={18} />
{creatingFolder ? 'Creating…' : 'New folder'}
</button>
<button
type="button"
className={`view-toggle__button${isGridView ? ' active' : ''}`}
onClick={() => handleSetViewMode('grid')}
aria-pressed={isGridView}
title="Icons view"
>
<ViewGridIcon className="view-toggle__icon" size={18} />
<button className="secondary" onClick={onRefresh}>
Refresh
</button>
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
Desk View
</button>
</div>
<button
type="button"
onClick={onRequestCreateFolder}
disabled={creatingFolder}
>
{creatingFolder ? 'Creating…' : 'New folder'}
</button>
<button className="secondary" onClick={onRefresh}>
Refresh
</button>
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
Desk View
</button>
</div>
</div>
) : null}
{showDefaultEmptyState && (
<div className="empty-state">
Drop files anywhere or onto a folder to upload documents.
@@ -359,9 +399,9 @@ const DocumentsTable = ({
No documents match the current filters.
</div>
)}
<div className="column-body">
<div className="panel-section__body">
<div
ref={scrollRef}
ref={assignScrollRef}
className="documents-scroll"
onFocus={(event) => {
if (event.target === scrollRef.current) {
@@ -376,13 +416,22 @@ const DocumentsTable = ({
onDocumentListKeyDown(event);
}
}}
onClick={(event) => {
if (event.target === event.currentTarget) {
onClearSelection?.();
}
}}
aria-activedescendant={isGridView ? undefined : activeDescendantId}
>
{showDefaultEmptyState ? null : isGridView ? (
<div
className="documents-grid"
role="list"
onClick={handleGridBackgroundClick}
onClick={(event) => {
if (event.target === event.currentTarget) {
onClearSelection?.();
}
}}
style={{ '--documents-grid-icon-size': `${gridIconSize}px` }}
>
{!showingSearchResults &&
@@ -477,6 +526,7 @@ const DocumentsTable = ({
getDocumentAsset={getDocumentAsset}
alt={`Thumbnail for ${doc.title || doc.original_name}`}
maxSize={gridIconSize}
scrollRootRef={scrollRef}
/>
<div className="document-card__meta">
<div
@@ -619,13 +669,20 @@ const DocumentsTable = ({
<td className="doc-list__name">
<div className="doc-list__name-content">
<span>{folder.name}</span>
{folder.id !== 'root' && (
</div>
</td>
<td>Folder</td>
<td></td>
<td className="actions">
<div className="action-buttons">
{folder.id !== 'root' && onFolderRename && (
<button
type="button"
className="icon-button ghost doc-list__icon-button"
className="icon-button ghost"
title="Rename"
aria-label={`Rename folder ${folder.name}`}
onClick={(event) => {
event.stopPropagation();
if (!onFolderRename) return;
const nextName = window.prompt('Rename folder', folder.name || '');
if (!nextName) {
return;
@@ -636,28 +693,24 @@ const DocumentsTable = ({
}
onFolderRename(folder.id, trimmed);
}}
title="Rename folder"
aria-label={`Rename folder ${folder.name}`}
>
<EditIcon className="doc-list__icon" size={16} />
<EditIcon className="icon-inline" />
</button>
)}
<button
type="button"
className="icon-button danger"
title="Delete"
aria-label={`Delete folder ${folder.name}`}
onClick={(event) => {
event.stopPropagation();
onFolderDelete(folder.id);
}}
>
<TrashIcon className="icon-inline" />
</button>
</div>
</td>
<td>Folder</td>
<td></td>
<td className="actions">
<button
type="button"
className="icon-button danger"
onClick={(event) => {
event.stopPropagation();
onFolderDelete(folder.id);
}}
>
Delete
</button>
</td>
</tr>
);
})}
@@ -690,36 +743,13 @@ const DocumentsTable = ({
ensureAssetUrl={ensureAssetUrl}
getDocumentAsset={getDocumentAsset}
alt={`Thumbnail for ${doc.title || doc.original_name}`}
scrollRootRef={scrollRef}
/>
</td>
<td className="doc-list__name">
<div className="doc-name">
<div className="doc-list__name-content">
<span className="doc-name__title">{doc.title || doc.original_name}</span>
<button
type="button"
className="icon-button ghost doc-list__icon-button"
onClick={(event) => {
event.stopPropagation();
if (!onDocumentRename) return;
const nextName = window.prompt(
'Rename document',
doc.title || doc.original_name || '',
);
if (!nextName) {
return;
}
const trimmed = nextName.trim();
if (!trimmed || trimmed === (doc.title || doc.original_name)) {
return;
}
onDocumentRename(doc.id, trimmed);
}}
title="Rename document"
aria-label={`Rename document ${doc.title || doc.original_name}`}
>
<EditIcon className="doc-list__icon" size={16} />
</button>
</div>
{(doc.tags || []).length > 0 && (
<div className="doc-name__tags">
@@ -788,31 +818,59 @@ const DocumentsTable = ({
</td>
<td className="actions">
<div className="action-buttons">
{onDocumentRename && (
<button
type="button"
className="icon-button ghost"
title="Rename"
aria-label={`Rename document ${doc.title || doc.original_name}`}
onClick={(event) => {
event.stopPropagation();
const nextName = window.prompt(
'Rename document',
doc.title || doc.original_name || '',
);
if (!nextName) {
return;
}
const trimmed = nextName.trim();
if (!trimmed || trimmed === (doc.title || doc.original_name)) {
return;
}
onDocumentRename(doc.id, trimmed);
}}
>
<EditIcon className="icon-inline" />
</button>
)}
{downloadHref ? (
<a
className="button-link with-icon"
className="icon-button"
href={downloadHref}
target="_blank"
rel="noopener noreferrer"
title="Download"
aria-label="Download document"
onClick={(event) => event.stopPropagation()}
onAuxClick={(event) => event.stopPropagation()}
onContextMenu={(event) => event.stopPropagation()}
>
<DownloadIcon className="icon-inline" />
<span>Download</span>
</a>
) : (
<span className="meta">No download</span>
)}
<button
type="button"
className="danger"
className="icon-button danger"
title="Delete"
aria-label="Delete document"
onClick={(event) => {
event.stopPropagation();
onDocumentDelete?.(doc.id);
}}
>
Delete
<TrashIcon className="icon-inline" />
</button>
</div>
</td>
+358 -152
View File
@@ -1,3 +1,5 @@
import '@fontsource/inter/400.css';
import React, {
useCallback,
useContext,
@@ -30,6 +32,16 @@ import CorrespondentsPanel from './correspondents/CorrespondentsPanel';
import { CORRESPONDENT_ROLES } from './constants/correspondents';
import TagManager from './tag_manager';
import Sidebar from './sidebar/Sidebar';
import {
ChevronsRightIcon,
ChevronsLeftIcon,
ViewListIcon,
ViewGridIcon,
FolderPlusIcon,
RefreshIcon,
ArrowUpIcon,
MinusVerticalIcon,
} from './ui/icons';
import DocumentsTable from './documents/DocumentsTable';
import { AppShellContext, useAppShell } from './appShellContext';
import DocumentViewerRoute from './routes/DocumentViewerRoute';
@@ -309,9 +321,9 @@ const LoginView = ({
const DocumentsLayout = ({ sidebarProps, children }) => (
<main className="documents-main">
<Sidebar {...sidebarProps} />
const DocumentsLayout = ({ sidebarProps, children, sidebarCollapsed }) => (
<main className={`documents-main${sidebarCollapsed ? ' documents-main--sidebar-collapsed' : ''}`}>
{!sidebarCollapsed ? <Sidebar {...sidebarProps} /> : null}
{children}
</main>
);
@@ -335,6 +347,9 @@ const AppLayout = () => {
({ message, variant }) => setStatusMessage(message, variant),
[setStatusMessage],
);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const collapseSidebar = useCallback(() => setSidebarCollapsed(true), []);
const expandSidebar = useCallback(() => setSidebarCollapsed(false), []);
const reportApiError = useApiError({
onReport: handleApiReport,
});
@@ -345,6 +360,8 @@ const AppLayout = () => {
);
const [loading, setLoading] = useState(false);
const [isCreateFolderModalOpen, setCreateFolderModalOpen] = useState(false);
const [isTagsModalOpen, setTagsModalOpen] = useState(false);
const [isCorrespondentsModalOpen, setCorrespondentsModalOpen] = useState(false);
const [newFolderName, setNewFolderName] = useState('');
const [createFolderError, setCreateFolderError] = useState('');
const [creatingFolder, setCreatingFolder] = useState(false);
@@ -366,15 +383,11 @@ const AppLayout = () => {
const stored = window.localStorage.getItem('papercrate_view_mode');
return stored === 'grid' ? 'grid' : 'list';
});
const initialRowSelection = routeDocumentId
? [resolveDocumentRowKey(routeDocumentId)]
: [];
const initialRowSelection = [];
const [selectedRowKeys, setSelectedRowKeys] = useState(initialRowSelection);
const [selectionOrder, setSelectionOrder] = useState(initialRowSelection);
const [focusedDocumentId, setFocusedDocumentId] = useState(routeDocumentId);
const [focusedRowKey, setFocusedRowKey] = useState(() =>
routeDocumentId ? resolveDocumentRowKey(routeDocumentId) : null,
);
const [focusedDocumentId, setFocusedDocumentId] = useState(null);
const [focusedRowKey, setFocusedRowKey] = useState(null);
const tokenRef = useRef(token);
const refreshPromiseRef = useRef(null);
const breadcrumbFetchRef = useRef(new Set());
@@ -423,13 +436,9 @@ const AppLayout = () => {
const documentsRouteMatch = useMatch('/documents');
const documentsFolderRouteMatch = useMatch('/documents/folder/:folderId');
const documentsDetailRouteMatch = useMatch('/documents/:documentId');
const tagsRouteMatch = useMatch('/tags');
const correspondentsRouteMatch = useMatch('/correspondents');
const isDocumentsRoute = Boolean(
documentsRouteMatch || documentsFolderRouteMatch || documentsDetailRouteMatch,
);
const isTagsRoute = Boolean(tagsRouteMatch);
const isCorrespondentsRoute = Boolean(correspondentsRouteMatch);
const toggleTagFilter = useCallback((tagId) => {
if (!tagId) return;
setActiveTagFilters((previous) =>
@@ -455,6 +464,10 @@ const AppLayout = () => {
setSearchLoading(false);
}, []);
const handleSearchChange = useCallback((value) => {
setSearchQuery(value);
}, []);
const handleSearchSubmit = useCallback(() => {
if (!navigate) return;
const targetFolder = selectedFolder && selectedFolder !== 'root' ? selectedFolder : 'root';
@@ -814,14 +827,7 @@ const AppLayout = () => {
if (selectionInitializedRef.current) {
nextDocKeys = previousDocKeys.filter((key) => availableDocKeySet.has(key));
} else {
const filtered = previousDocKeys.filter((key) => availableDocKeySet.has(key));
if (filtered.length) {
nextDocKeys = filtered;
} else if (availableDocKeys.length) {
nextDocKeys = [availableDocKeys[0]];
} else {
nextDocKeys = [];
}
nextDocKeys = previousDocKeys.filter((key) => availableDocKeySet.has(key));
}
mergedSelection = [...previousFolderKeys, ...nextDocKeys];
@@ -3682,6 +3688,24 @@ const AppLayout = () => {
setCreateFolderError('');
}, [creatingFolder]);
const openTagsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
setTagsModalOpen(true);
}, []);
const closeTagsModal = useCallback(() => {
setTagsModalOpen(false);
}, []);
const openCorrespondentsModal = useCallback(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(true);
}, []);
const closeCorrespondentsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
}, []);
const handleCreateFolderSubmit = useCallback(
async (event) => {
event.preventDefault();
@@ -3742,6 +3766,31 @@ const AppLayout = () => {
};
}, [isCreateFolderModalOpen, closeCreateFolderModal]);
useEffect(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(false);
}, [location.pathname]);
useEffect(() => {
if (!isTagsModalOpen && !isCorrespondentsModalOpen) {
return;
}
const handleKeyDown = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
if (isTagsModalOpen) {
closeTagsModal();
} else if (isCorrespondentsModalOpen) {
closeCorrespondentsModal();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [isTagsModalOpen, isCorrespondentsModalOpen, closeTagsModal, closeCorrespondentsModal]);
useEffect(() => {
if (!token) return undefined;
@@ -4442,6 +4491,17 @@ const AppLayout = () => {
correspondents,
activeCorrespondentIds: activeCorrespondentFilters,
onToggleCorrespondentFilter: toggleCorrespondentFilter,
appStatus,
loading,
previewActive,
searchQuery,
onSearchChange: handleSearchChange,
onSearchSubmit: handleSearchSubmit,
onSearchClear: clearFilters,
isFilterActive,
onLogout: handleLogout,
status,
onCollapse: collapseSidebar,
};
const resolveThumbnailUrlForDoc = useCallback(
@@ -4538,6 +4598,7 @@ const AppLayout = () => {
onCorrespondentAdd: handleCorrespondentAdd,
onCorrespondentRemove: handleCorrespondentRemove,
resolveApiPath,
onClose: clearDocumentSelection,
};
const skeuoWorkspaceProps = useMemo(
@@ -4585,7 +4646,6 @@ const AppLayout = () => {
tags,
refreshTags,
handleTagUpdate,
handleTagCreate,
handleTagDelete,
handleDocumentTagAttach,
correspondents,
@@ -4610,6 +4670,8 @@ const AppLayout = () => {
ensurePreviewData,
notifyApiError,
resolveApiPath,
openTagsModal,
openCorrespondentsModal,
}),
[
token,
@@ -4622,7 +4684,6 @@ const AppLayout = () => {
tags,
refreshTags,
handleTagUpdate,
handleTagCreate,
handleTagDelete,
handleDocumentTagAttach,
correspondents,
@@ -4647,15 +4708,22 @@ const AppLayout = () => {
ensurePreviewData,
notifyApiError,
resolveApiPath,
openTagsModal,
openCorrespondentsModal,
],
);
if (['logged-out', 'authenticating', 'selecting-tenant'].includes(appStatus)) {
const shouldRememberLastLocation = appStatus !== 'logged-out';
return (
<Navigate
to="/account/login"
replace
state={{ from: location.pathname + location.search }}
state={
shouldRememberLastLocation
? { from: location.pathname + location.search }
: undefined
}
/>
);
}
@@ -4667,81 +4735,6 @@ const AppLayout = () => {
active={dropOverlayState.active}
folderName={dropOverlayState.folderName}
/>
<header className="app-bar">
<div className="app-bar__main">
<div className="app-bar__meta">
<h1>Papercrate</h1>
<span className="app-bar__hint">
{appStatus === 'bootstrapping' && loading
? 'Loading your library…'
: previewActive
? 'Viewing document preview. Press ← Back to return to the library.'
: 'Drag files here to upload.'}
</span>
</div>
<div className="app-bar__search">
<input
type="search"
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search documents"
aria-label="Search documents"
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleSearchSubmit();
}
}}
/>
{isFilterActive && (
<button
type="button"
className="app-bar__search-clear"
onClick={clearFilters}
>
Clear
</button>
)}
</div>
<div className="app-bar__right">
<div className="app-bar__links">
<button
type="button"
className={`app-bar__link${isDocumentsRoute ? ' active' : ''}`}
onClick={() => navigate('/documents')}
>
Documents
</button>
<button
type="button"
className={`app-bar__link${isTagsRoute ? ' active' : ''}`}
onClick={() => navigate('/tags')}
>
Tags
<span className="app-bar__link-count">{tags.length}</span>
</button>
<button
type="button"
className={`app-bar__link${isCorrespondentsRoute ? ' active' : ''}`}
onClick={() => navigate('/correspondents')}
>
Correspondents
<span className="app-bar__link-count">{correspondents.length}</span>
</button>
</div>
{status && (
<div className="app-bar__status">
<StatusBanner status={status} />
</div>
)}
<div className="app-bar__actions">
<button className="secondary" onClick={handleLogout}>
Log out
</button>
</div>
</div>
</div>
</header>
<Outlet />
{isCreateFolderModalOpen && (
<div
@@ -4791,6 +4784,74 @@ const AppLayout = () => {
</div>
</div>
)}
{isTagsModalOpen && (
<div
className="modal-backdrop"
role="presentation"
onClick={closeTagsModal}
>
<div
className="modal modal--panel"
role="dialog"
aria-modal="true"
aria-labelledby="tags-modal-title"
onClick={(event) => event.stopPropagation()}
>
<div className="panel-modal__header">
<h3 id="tags-modal-title">Manage Tags</h3>
<button type="button" className="secondary" onClick={closeTagsModal}>
Close
</button>
</div>
<div className="panel-modal__body">
<TagsPanel
tags={tags}
onRefresh={refreshTags}
onCreateTag={handleTagCreate}
onUpdateTag={handleTagUpdate}
onDeleteTag={handleTagDelete}
onNotify={setStatusMessage}
/>
</div>
</div>
</div>
)}
{isCorrespondentsModalOpen && (
<div
className="modal-backdrop"
role="presentation"
onClick={closeCorrespondentsModal}
>
<div
className="modal modal--panel"
role="dialog"
aria-modal="true"
aria-labelledby="correspondents-modal-title"
onClick={(event) => event.stopPropagation()}
>
<div className="panel-modal__header">
<h3 id="correspondents-modal-title">Manage Correspondents</h3>
<button
type="button"
className="secondary"
onClick={closeCorrespondentsModal}
>
Close
</button>
</div>
<div className="panel-modal__body">
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
onNotify={setStatusMessage}
/>
</div>
</div>
</div>
)}
</div>
</AppShellContext.Provider>
);
@@ -4803,20 +4864,212 @@ const DocumentsRoute = () => {
detailPanelProps,
workspaceMode,
skeuoWorkspaceProps,
openTagsModal,
openCorrespondentsModal,
exitSkeuoWorkspace,
} = useAppShell();
const navigate = useNavigate();
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const collapseSidebar = useCallback(() => setSidebarCollapsed(true), []);
const expandSidebar = useCallback(() => setSidebarCollapsed(false), []);
const sidebarPropsWithActions = useMemo(
() => ({
...sidebarProps,
onManageTags: openTagsModal,
onManageCorrespondents: openCorrespondentsModal,
onCollapse: collapseSidebar,
}),
[sidebarProps, openTagsModal, openCorrespondentsModal, collapseSidebar],
);
const {
currentFolderName,
viewMode,
onViewModeChange,
onRequestCreateFolder,
creatingFolder,
onRefresh,
onShowSkeuoWorkspace,
searchResults,
breadcrumbs,
} = documentsTableProps;
const isGridView = viewMode === 'grid';
const showingSearchResults = Array.isArray(searchResults);
const headerTitle = showingSearchResults ? 'Search results' : currentFolderName;
const headerSubtitle = showingSearchResults
? `${searchResults.length} matching document${searchResults.length === 1 ? '' : 's'}`
: null;
const parentBreadcrumb = breadcrumbs && breadcrumbs.length > 1 ? breadcrumbs[breadcrumbs.length - 2] : null;
const handleNavigateParent = parentBreadcrumb
? () => {
const target = parentBreadcrumb.id === 'root'
? '/documents'
: `/documents/folder/${parentBreadcrumb.id}`;
navigate(target);
}
: null;
const detailHasContent = detailPanelProps.selectedDocuments?.length > 0;
const toggleSidebar = sidebarCollapsed ? expandSidebar : collapseSidebar;
const ToggleIcon = sidebarCollapsed ? ChevronsRightIcon : ChevronsLeftIcon;
const toggleLabel = sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar';
if (workspaceMode === 'skeuo') {
return (
<DocumentsLayout sidebarProps={sidebarProps}>
<SkeuomorphicWorkspace {...skeuoWorkspaceProps} />
<DocumentsLayout
sidebarProps={sidebarPropsWithActions}
sidebarCollapsed={sidebarCollapsed}
>
<div className="main-content">
<div className="panel-header main-content__header">
<div className="panel-actions main-content__actions">
{sidebarCollapsed ? (
<button
type="button"
className="icon-button ghost"
onClick={toggleSidebar}
aria-label={toggleLabel}
title={toggleLabel}
>
<ToggleIcon />
</button>
) : null}
{parentBreadcrumb ? (
<button
type="button"
className="icon-button ghost"
onClick={handleNavigateParent}
aria-label="Go to parent folder"
title="Go to parent folder"
>
<ArrowUpIcon />
</button>
) : null}
<h2 className="main-content__title">
{headerTitle}
{headerSubtitle ? (
<span className="main-content__subtitle">{headerSubtitle}</span>
) : null}
</h2>
<div className="spacer" />
<button
type="button"
className="icon-button ghost"
onClick={skeuoWorkspaceProps.onRefresh}
aria-label="Refresh"
title="Refresh"
>
<RefreshIcon />
</button>
<button type="button" className="secondary" onClick={exitSkeuoWorkspace}>
Back to List
</button>
</div>
</div>
<div className="main-content__body">
<SkeuomorphicWorkspace {...skeuoWorkspaceProps} />
</div>
</div>
</DocumentsLayout>
);
}
return (
<DocumentsLayout sidebarProps={sidebarProps}>
<DocumentsTable {...documentsTableProps} />
<DetailPanel {...detailPanelProps} />
<DocumentsLayout
sidebarProps={sidebarPropsWithActions}
sidebarCollapsed={sidebarCollapsed}
>
<div className={`main-content main-content--documents${detailHasContent ? ' main-content--has-detail' : ''}`}>
<div className="panel-header main-content__header">
<div className="panel-actions main-content__actions">
{sidebarCollapsed ? (
<button
type="button"
className="icon-button ghost"
onClick={toggleSidebar}
aria-label={toggleLabel}
title={toggleLabel}
>
<ToggleIcon />
</button>
) : null}
{parentBreadcrumb ? (
<button
type="button"
className="icon-button ghost"
onClick={handleNavigateParent}
aria-label="Go to parent folder"
title="Go to parent folder"
>
<ArrowUpIcon />
</button>
) : null}
<h2 className="main-content__title">
{headerTitle}
{headerSubtitle ? (
<span className="main-content__subtitle">{headerSubtitle}</span>
) : null}
</h2>
<div className="spacer" />
<div className="view-toggle" role="group" aria-label="Change view">
<button
type="button"
className={`view-toggle__button${isGridView ? '' : ' active'}`}
onClick={() => onViewModeChange?.('list')}
aria-pressed={!isGridView}
title="List view"
>
<ViewListIcon className="view-toggle__icon" size={18} />
</button>
<button
type="button"
className={`view-toggle__button${isGridView ? ' active' : ''}`}
onClick={() => onViewModeChange?.('grid')}
aria-pressed={isGridView}
title="Icons view"
>
<ViewGridIcon className="view-toggle__icon" size={18} />
</button>
</div>
<span className="main-content__actions-divider" aria-hidden="true">
<MinusVerticalIcon />
</span>
<button
type="button"
className="icon-button ghost"
onClick={onRequestCreateFolder}
disabled={creatingFolder}
aria-label={creatingFolder ? 'Creating folder…' : 'Create folder'}
title={creatingFolder ? 'Creating folder…' : 'Create folder'}
>
<FolderPlusIcon />
</button>
<button
type="button"
className="icon-button ghost"
onClick={onRefresh}
aria-label="Refresh"
title="Refresh"
>
<RefreshIcon />
</button>
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
Desk View
</button>
</div>
</div>
<div
className={`main-content__body main-content__body--documents${detailHasContent ? ' main-content__body--has-detail' : ''}`}
>
<DocumentsTable {...documentsTableProps} showHeader={false} />
</div>
{detailHasContent ? (
<DetailPanel {...detailPanelProps} />
) : null}
</div>
</DocumentsLayout>
);
};
@@ -4951,51 +5204,6 @@ const LoginRoute = () => {
);
};
function TagsRoute() {
const {
tags,
refreshTags,
handleTagUpdate,
handleTagDelete,
setStatusMessage,
} = useAppShell();
return (
<main className="panels-main">
<TagsPanel
tags={tags}
onRefresh={refreshTags}
onUpdateTag={handleTagUpdate}
onDeleteTag={handleTagDelete}
onNotify={setStatusMessage}
/>
</main>
);
}
function CorrespondentsRoute() {
const {
correspondents,
refreshCorrespondents,
handleCorrespondentCreate,
handleCorrespondentUpdate,
handleCorrespondentDelete,
setStatusMessage,
} = useAppShell();
return (
<main className="panels-main">
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
onNotify={setStatusMessage}
/>
</main>
);
}
const AppRouter = () => (
<Routes>
<Route path="/account/login" element={<LoginRoute />} />
@@ -5004,8 +5212,6 @@ const AppRouter = () => (
<Route path="/documents" element={<DocumentsRoute />} />
<Route path="/documents/folder/:folderId" element={<DocumentsRoute />} />
<Route path="/documents/:documentId" element={<DocumentViewerRoute />} />
<Route path="/tags" element={<TagsRoute />} />
<Route path="/correspondents" element={<CorrespondentsRoute />} />
<Route path="*" element={<Navigate to="/documents" replace />} />
</Route>
</Routes>
+127 -38
View File
@@ -1,5 +1,5 @@
import React, { useCallback, useMemo } from 'react';
import { ChevronIcon, TrashIcon, EditIcon, FolderIcon } from '../ui/icons';
import { ChevronIcon, TrashIcon, EditIcon, FolderIcon, ChevronsLeftIcon } from '../ui/icons';
import { getTagColorStyle } from '../utils/colors';
@@ -136,6 +136,19 @@ const Sidebar = ({
correspondents = [],
activeCorrespondentIds = [],
onToggleCorrespondentFilter,
onManageTags,
onManageCorrespondents,
searchQuery = '',
onSearchChange,
onSearchSubmit,
onSearchClear,
isFilterActive,
appStatus,
loading,
previewActive,
onLogout,
status,
onCollapse,
}) => {
const sortedCorrespondents = useMemo(
() =>
@@ -150,6 +163,27 @@ const Sidebar = ({
);
const handleToggleTag = onToggleTagFilter || (() => {});
const activeTagSet = new Set(activeTagIds);
const handleManageTags = onManageTags || (() => {});
const handleManageCorrespondents = onManageCorrespondents || (() => {});
const handleSearchInputChange = useCallback(
(event) => {
onSearchChange?.(event.target.value);
},
[onSearchChange],
);
const handleSearchFormSubmit = useCallback(
(event) => {
event.preventDefault();
onSearchSubmit?.();
},
[onSearchSubmit],
);
const handleSearchClear = useCallback(() => {
onSearchClear?.();
}, [onSearchClear]);
const handleLogoutClick = useCallback(() => {
onLogout?.();
}, [onLogout]);
const renderNodes = useCallback(
(ids, depth) =>
@@ -193,30 +227,80 @@ const Sidebar = ({
);
const rootNode = folderNodes.get('root');
const hintText = appStatus === 'bootstrapping' && loading
? 'Loading your library…'
: previewActive
? 'Viewing document preview. Press ← Back to return to the library.'
: 'Drag files here to upload.';
return (
<aside className="sidebar column">
<div className="sidebar-section sidebar-section--folders">
<div className="sidebar-section__header">
<h3>Folders</h3>
<aside className="sidebar">
<div className="panel-header sidebar__header">
<div className="panel-actions">
<h1 className="sidebar__title">Papercrate</h1>
<div className="spacer" />
{onCollapse ? (
<button
type="button"
className="icon-button ghost"
onClick={onCollapse}
aria-label="Collapse sidebar"
title="Collapse sidebar"
>
<ChevronsLeftIcon />
</button>
) : null}
</div>
<ul className="folder-tree">
{rootNode && renderNodes([rootNode.id], 0)}
</ul>
</div>
<div className="sidebar-section">
<div className="sidebar-section__header">
<h3>Tags</h3>
<span className="meta">{tags.length}</span>
<div className="panel-body sidebar__body">
<span className="sidebar__hint">{hintText}</span>
{status && (
<div className="sidebar__status">
<div className={`status-banner ${status.variant}`}>{status.message}</div>
</div>
)}
{onSearchChange && (
<form className="sidebar__search" onSubmit={handleSearchFormSubmit}>
<input
type="search"
value={searchQuery}
onChange={handleSearchInputChange}
placeholder="Search documents"
aria-label="Search documents"
/>
{isFilterActive && (
<button type="button" onClick={handleSearchClear}>
Clear
</button>
)}
</form>
)}
<div className="sidebar-section sidebar-section--folders">
<div className="sidebar-section__header">
<h3>Folders</h3>
</div>
<ul className="folder-tree">
{rootNode && renderNodes([rootNode.id], 0)}
</ul>
</div>
<div
className={`sidebar-tag-cloud${
activeTagSet.size ? ' sidebar-tag-cloud--has-active' : ''
}`}
role="list"
>
{tags.length ? (
tags.map((tag) => {
<div className="sidebar-section">
<div className="sidebar-section__header">
<button
type="button"
className="sidebar-section__title"
onClick={handleManageTags}
>
<h3>Tags</h3>
<span className="meta">{tags.length}</span>
</button>
</div>
<div
className={`sidebar-tag-cloud${
activeTagSet.size ? ' sidebar-tag-cloud--has-active' : ''
}`}
role="list"
>
{tags.map((tag) => {
const isActive = activeTagSet.has(tag.id);
const style = getTagColorStyle(tag.color);
const className = `sidebar-tag-pill${isActive ? ' active' : ''}`;
@@ -249,20 +333,22 @@ const Sidebar = ({
{tag.label}
</button>
);
})
) : (
<span className="meta">No tags yet</span>
)}
})}
</div>
</div>
</div>
<div className="sidebar-section">
<div className="sidebar-section__header">
<h3>Correspondents</h3>
<span className="meta">{correspondents.length}</span>
</div>
<ul className="sidebar-correspondent-list">
{sortedCorrespondents.length ? (
sortedCorrespondents.map((correspondent) => {
<div className="sidebar-section">
<div className="sidebar-section__header">
<button
type="button"
className="sidebar-section__title"
onClick={handleManageCorrespondents}
>
<h3>Correspondents</h3>
<span className="meta">{correspondents.length}</span>
</button>
</div>
<ul className="sidebar-correspondent-list">
{sortedCorrespondents.map((correspondent) => {
const isActive = activeCorrespondentSet.has(correspondent.id);
const className = `sidebar-correspondent-item${isActive ? ' active' : ''}`;
const label = correspondent.name || 'Unnamed';
@@ -287,11 +373,14 @@ const Sidebar = ({
</span>
</li>
);
})
) : (
<li className="meta">No correspondents yet</li>
)}
</ul>
})}
</ul>
</div>
<div className="sidebar__footer">
<button className="secondary" type="button" onClick={handleLogoutClick}>
Log out
</button>
</div>
</div>
</aside>
);
-55
View File
@@ -13,57 +13,6 @@
grid-column: 2 / -1;
min-height: 0;
position: relative;
background-color: var(--surface-subtle);
}
.skeuo-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem 0.5rem;
background-color: var(--surface-subtle);
}
.skeuo-header__meta {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.skeuo-header__meta h2 {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
}
.skeuo-breadcrumbs {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
font-size: 0.85rem;
color: var(--muted);
}
.skeuo-crumb {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.skeuo-crumb.is-current {
color: var(--fg);
font-weight: 600;
}
.skeuo-crumb-separator {
opacity: 0.4;
}
.skeuo-header__actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.skeuo-canvas {
@@ -119,10 +68,6 @@
transition: none;
}
.skeuo-item.is-zoomed {
cursor: pointer;
}
.skeuo-item.is-tag-target .skeuo-item__card {
outline: 1em dashed var(--accent);
outline-offset: 1.41em;
+185 -151
View File
@@ -9,6 +9,7 @@ import React, {
import { resolveDocumentAssetUrl, createAssetView } from './asset_manager';
import { useAssetNavigator } from './hooks/useAssetNavigator';
import { ArrowLeftIcon, ArrowRightIcon } from './ui/icons';
import PreviewZoomOverlay from './detail/PreviewZoomOverlay';
import { getReadableTextColor } from './utils/colors';
import './skeuomorphic_ws.css';
@@ -28,9 +29,6 @@ const resolveSizeKey = (doc) =>
const CARD_MIN = 240;
const CARD_MAX = 340;
const EMPTY_CARD_ASPECT = 1.4;
const ZOOM_FILL_RATIO = 0.99;
const ZOOM_MIN_SCALE = 1.05;
const ZOOM_MAX_SCALE = 5;
const TAG_REMOVE_DISTANCE = 160;
const DEBUG_DRAG = false;
@@ -52,6 +50,7 @@ const SkeuoPreviewCard = ({
getDocumentAsset,
navScale = 1,
prefetch = 3,
onNavigatorSnapshot,
}) => {
const navigator = useAssetNavigator({
document: doc,
@@ -62,6 +61,32 @@ const SkeuoPreviewCard = ({
});
const { currentUrl, cardinality, canGoPrev, canGoNext } = navigator;
const docId = doc?.id ?? null;
useEffect(() => {
if (!onNavigatorSnapshot || !docId) {
return undefined;
}
const snapshot = {
url: currentUrl || null,
alt: title,
canGoPrev,
canGoNext,
goPrev: navigator.goPrev,
goNext: navigator.goNext,
};
onNavigatorSnapshot(docId, snapshot);
return () => onNavigatorSnapshot(docId, null);
}, [
docId,
currentUrl,
title,
canGoPrev,
canGoNext,
navigator.goPrev,
navigator.goNext,
onNavigatorSnapshot,
]);
const hasPreview = Boolean(currentUrl);
const cardClasses = ['skeuo-item__card'];
if (!hasPreview) cardClasses.push('skeuo-item__card--empty');
@@ -303,7 +328,7 @@ const useDocumentDrag = ({
setDraggingId,
syncLayoutSnapshot,
canvasSize,
toggleZoom,
openOverlayForDoc,
}) => {
const dragStateRef = useRef(null);
@@ -330,7 +355,7 @@ const useDocumentDrag = ({
);
const handlePointerDown = useCallback(
(event, docId, { lockWhenZoomed = false } = {}) => {
(event, docId) => {
if (DEBUG_DRAG) {
console.log(
'[skeuo] handlePointerDown fired for doc',
@@ -376,7 +401,7 @@ const useDocumentDrag = ({
startY: event.clientY,
rotation: entry?.rotation ?? 0,
moved: false,
locked: Boolean(lockWhenZoomed),
locked: false,
width: docWidth,
height: docHeight,
scale: baseScale,
@@ -475,13 +500,19 @@ const useDocumentDrag = ({
const docId = state.docId;
finishDrag(event.pointerId);
if (!moved) {
toggleZoom(docId);
const originInfo = {
rotation: state.rotation || 0,
scale: state.scale || 1,
width: state.width,
height: state.height,
};
openOverlayForDoc(docId, originInfo);
}
return;
}
finishDrag(event.pointerId);
},
[finishDrag, toggleZoom],
[finishDrag, openOverlayForDoc],
);
const handlePointerCancel = useCallback(
@@ -547,10 +578,6 @@ const getContrastingTextColor = (hex) => getReadableTextColor(hex, { light: '#1f
const SkeuomorphicWorkspace = ({
documents = [],
searchResults = null,
breadcrumbs = [],
currentFolderName = 'Folder',
onExit,
onRefresh,
onDocumentOpen,
resolveThumbnailUrl,
onAssignTagToDocument = null,
@@ -560,7 +587,6 @@ const SkeuomorphicWorkspace = ({
activeTagIds = [],
}) => {
const items = useMemo(() => (searchResults ? searchResults : documents), [documents, searchResults]);
const showingSearchResults = searchResults !== null;
const containerRef = useRef(null);
@@ -572,7 +598,10 @@ const SkeuomorphicWorkspace = ({
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
const [draggingId, setDraggingId] = useState(null);
const [zoomedId, setZoomedId] = useState(null);
const [overlayDocId, setOverlayDocId] = useState(null);
const [overlayOriginRect, setOverlayOriginRect] = useState(null);
const [overlayOriginTransform, setOverlayOriginTransform] = useState(null);
const [previewSnapshots, setPreviewSnapshots] = useState(() => new Map());
const [tagDropTargetId, setTagDropTargetId] = useState(null);
const [pendingTagDocId, setPendingTagDocId] = useState(null);
const [pendingRemovalTag, setPendingRemovalTag] = useState(null);
@@ -580,6 +609,36 @@ const SkeuomorphicWorkspace = ({
const pendingDocTagDragRef = useRef(null);
const docSizeMapRef = useRef(new Map());
const removalCursorActiveRef = useRef(false);
const handleNavigatorSnapshot = useCallback((docId, snapshot) => {
if (!docId) {
return;
}
setPreviewSnapshots((previous) => {
const prevSnapshot = previous.get(docId);
if (!snapshot) {
if (!previous.has(docId)) {
return previous;
}
const next = new Map(previous);
next.delete(docId);
return next;
}
const next = new Map(previous);
const sameSnapshot =
prevSnapshot &&
prevSnapshot.url === snapshot.url &&
prevSnapshot.alt === snapshot.alt &&
prevSnapshot.canGoPrev === snapshot.canGoPrev &&
prevSnapshot.canGoNext === snapshot.canGoNext &&
prevSnapshot.goPrev === snapshot.goPrev &&
prevSnapshot.goNext === snapshot.goNext;
if (sameSnapshot) {
return previous;
}
next.set(docId, snapshot);
return next;
});
}, []);
const activeTagSet = useMemo(() => {
if (!Array.isArray(activeTagIds) || activeTagIds.length === 0) {
return new Set();
@@ -779,70 +838,39 @@ const SkeuomorphicWorkspace = ({
docSizeMapRef.current = new Map();
}, [items]);
const resolveZoomMetrics = useCallback(
(doc, cardWidth, cardHeight) => {
const canvasWidth = canvasSize.width || DEFAULT_CANVAS_WIDTH;
const canvasHeight = canvasSize.height || DEFAULT_CANVAS_HEIGHT;
const safeCardWidth = cardWidth || CARD_MIN;
const safeCardHeight = cardHeight || CARD_MIN;
const usableWidth = Math.max(canvasWidth - CANVAS_PADDING * 2, safeCardWidth);
const usableHeight = Math.max(canvasHeight - CANVAS_PADDING * 2, safeCardHeight);
const viewportTargetWidth = usableWidth * ZOOM_FILL_RATIO;
const viewportTargetHeight = usableHeight * ZOOM_FILL_RATIO;
const overlayDisplay = useMemo(() => {
if (!overlayDocId) {
return null;
}
const snapshot = previewSnapshots.get(overlayDocId);
if (!snapshot || !snapshot.url) {
return null;
}
const doc = documentLookup.get(overlayDocId);
const alt = snapshot.alt || doc?.title || doc?.original_name || 'Document preview';
return {
url: snapshot.url,
alt,
canGoPrev: snapshot.canGoPrev,
canGoNext: snapshot.canGoNext,
goPrev: snapshot.goPrev,
goNext: snapshot.goNext,
};
}, [overlayDocId, previewSnapshots, documentLookup]);
let zoomWidth = safeCardWidth;
let zoomHeight = safeCardHeight;
const closeOverlay = useCallback(() => {
setOverlayDocId(null);
setOverlayOriginRect(null);
setOverlayOriginTransform(null);
}, []);
const previewDims = doc ? resolvePreviewDimensions(doc) : null;
if (previewDims?.width && previewDims?.height) {
const previewWidth = previewDims.width;
const previewHeight = previewDims.height;
const widthScaleLimit = previewWidth > 0 ? viewportTargetWidth / previewWidth : 1;
const heightScaleLimit = previewHeight > 0 ? viewportTargetHeight / previewHeight : 1;
const scaleToFit = Math.min(1, widthScaleLimit || 1, heightScaleLimit || 1);
zoomWidth = previewWidth * scaleToFit;
zoomHeight = previewHeight * scaleToFit;
} else {
const rawScale = Math.min(
viewportTargetWidth / safeCardWidth,
viewportTargetHeight / safeCardHeight,
);
const boundedScale =
rawScale >= 1
? clamp(Math.max(rawScale, ZOOM_MIN_SCALE), ZOOM_MIN_SCALE, ZOOM_MAX_SCALE)
: rawScale;
zoomWidth = safeCardWidth * boundedScale;
zoomHeight = safeCardHeight * boundedScale;
}
if (!Number.isFinite(zoomWidth) || zoomWidth <= 0) {
zoomWidth = safeCardWidth;
}
if (!Number.isFinite(zoomHeight) || zoomHeight <= 0) {
zoomHeight = safeCardHeight;
}
zoomWidth = Math.max(zoomWidth, safeCardWidth);
zoomHeight = Math.max(zoomHeight, safeCardHeight);
const zoomTargetX = (canvasWidth - zoomWidth) / 2;
const zoomTargetY = (canvasHeight - zoomHeight) / 2;
const maxX = Math.max(CANVAS_PADDING, canvasWidth - zoomWidth - CANVAS_PADDING);
const maxY = Math.max(CANVAS_PADDING, canvasHeight - zoomHeight - CANVAS_PADDING);
const clampedX = clamp(zoomTargetX, CANVAS_PADDING, maxX);
const clampedY = clamp(zoomTargetY, CANVAS_PADDING, maxY);
const zoomCenterX = clampedX + zoomWidth / 2;
const zoomCenterY = clampedY + zoomHeight / 2;
return {
zoomWidth,
zoomHeight,
zoomCenterX,
zoomCenterY,
};
},
[canvasSize.width, canvasSize.height, resolvePreviewDimensions],
);
useEffect(() => {
if (overlayDocId && !documentLookup.has(overlayDocId)) {
setOverlayDocId(null);
setOverlayOriginRect(null);
setOverlayOriginTransform(null);
}
}, [overlayDocId, documentLookup]);
const resolveBaseMetrics = useCallback(
(doc, cardWidth, cardHeight) => {
@@ -1014,17 +1042,62 @@ const SkeuomorphicWorkspace = ({
[syncLayoutSnapshot],
);
const toggleZoom = useCallback(
(docId) => {
setZoomedId((current) => {
if (current === docId) {
return null;
}
bringToFront(docId);
return docId;
});
const openOverlayForDoc = useCallback(
(docId, originInfo = null) => {
if (!docId) {
return;
}
const snapshot = previewSnapshots.get(docId);
if (!snapshot || !snapshot.url) {
return;
}
const container = itemRefs.current.get(docId);
const imageNode = container?.querySelector?.('.skeuo-item__card img');
if (!container || !imageNode) {
return;
}
const rect = imageNode.getBoundingClientRect();
let originTransform = null;
if (originInfo) {
const { rotation = 0, scale = 1, width: originWidth, height: originHeight } = originInfo;
originTransform = {
rotation,
scaleX: scale,
scaleY: scale,
baseWidth: originWidth,
baseHeight: originHeight,
};
}
if (!originTransform) {
const entry = layoutRef.current.get(docId) || null;
const doc = documentLookup.get(docId) || null;
const { width: cardWidth, height: cardHeight } = ensureDocumentSize(doc);
const { baseWidth, baseHeight, baseScale } = resolveBaseMetrics(doc, cardWidth, cardHeight);
const effectiveWidth = baseWidth * baseScale;
const effectiveHeight = baseHeight * baseScale;
originTransform = {
rotation: entry?.rotation ?? 0,
scaleX: baseScale,
scaleY: baseScale,
baseWidth: Number.isFinite(effectiveWidth) && effectiveWidth > 0 ? effectiveWidth : cardWidth,
baseHeight: Number.isFinite(effectiveHeight) && effectiveHeight > 0 ? effectiveHeight : cardHeight,
};
}
bringToFront(docId);
setOverlayOriginRect(rect);
setOverlayOriginTransform(originTransform);
setOverlayDocId(docId);
},
[bringToFront],
[
bringToFront,
previewSnapshots,
itemRefs,
setOverlayOriginTransform,
ensureDocumentSize,
resolveBaseMetrics,
documentLookup,
layoutRef,
],
);
const { handlePointerDown, handlePointerMove, handlePointerUp, handlePointerCancel } = useDocumentDrag({
layoutRef,
@@ -1036,7 +1109,7 @@ const SkeuomorphicWorkspace = ({
setDraggingId,
syncLayoutSnapshot,
canvasSize,
toggleZoom,
openOverlayForDoc,
});
const handleTagDragEnterDoc = useCallback(
@@ -1489,47 +1562,16 @@ const SkeuomorphicWorkspace = ({
[queueFocusCanvas, handleTagDragEnd, onRemoveTagFromDocument, updateRemovalCursor],
);
const renderBreadcrumbs = () => {
if (!breadcrumbs.length) return null;
return (
<nav className="skeuo-breadcrumbs" aria-label="Folder breadcrumbs">
{breadcrumbs.map((crumb, index) => {
const isLast = index === breadcrumbs.length - 1;
return (
<span key={crumb.id} className={`skeuo-crumb${isLast ? ' is-current' : ''}`}>
{crumb.name}
{!isLast && <span className="skeuo-crumb-separator"></span>}
</span>
);
})}
</nav>
);
};
return (
<div className="skeuo-shell">
<header className="skeuo-header">
<div className="skeuo-header__meta">
<h2>{currentFolderName}</h2>
{renderBreadcrumbs()}
{showingSearchResults && <span className="meta">Showing search results</span>}
</div>
<div className="skeuo-header__actions">
<button type="button" className="secondary" onClick={onRefresh}>
Refresh
</button>
<button type="button" onClick={onExit}>
Back to List
</button>
</div>
</header>
<div
className="skeuo-canvas"
ref={containerRef}
onDragOver={handleCanvasDragOver}
onDragLeave={handleCanvasDragLeave}
onDrop={handleCanvasDrop}
>
<>
<div className="skeuo-shell">
<div
className="skeuo-canvas"
ref={containerRef}
onDragOver={handleCanvasDragOver}
onDragLeave={handleCanvasDragLeave}
onDrop={handleCanvasDrop}
>
{items.length === 0 ? (
<div className="skeuo-empty">
<p>No documents to show here yet. Drop files to make this space come alive.</p>
@@ -1550,31 +1592,17 @@ const SkeuomorphicWorkspace = ({
typeof layout.centerX === 'number' ? layout.centerX : fallbackLayout.centerX;
const layoutCenterY =
typeof layout.centerY === 'number' ? layout.centerY : fallbackLayout.centerY;
const isZoomed = zoomedId === doc.id;
const { zoomWidth, zoomHeight, zoomCenterX, zoomCenterY } = resolveZoomMetrics(
doc,
cardWidth,
cardHeight,
);
const targetCenterX = isZoomed ? zoomCenterX : layoutCenterX;
const targetCenterY = isZoomed ? zoomCenterY : layoutCenterY;
const rotation = isZoomed ? 0 : layout.rotation || 0;
const zoomScale = isZoomed
? Math.min(
1,
Number.isFinite(zoomWidth / baseWidth) ? zoomWidth / baseWidth : 1,
Number.isFinite(zoomHeight / baseHeight) ? zoomHeight / baseHeight : 1,
)
: baseScale;
const rotation = layout.rotation || 0;
const zoomScale = baseScale;
const transform = formatTransform(
Math.round(targetCenterX),
Math.round(targetCenterY),
Math.round(layoutCenterX),
Math.round(layoutCenterY),
rotation,
zoomScale,
);
const style = {
transform,
zIndex: isZoomed ? 9999 : layout.z ?? 1,
zIndex: layout.z ?? 1,
};
const bodyStyle = {
width: Math.round(baseWidth),
@@ -1595,7 +1623,6 @@ const SkeuomorphicWorkspace = ({
const dropPending = pendingTagDocId === doc.id;
const itemClasses = ['skeuo-item'];
if (dragging) itemClasses.push('is-dragging');
if (isZoomed) itemClasses.push('is-zoomed');
if (dropActive) itemClasses.push('is-tag-target');
if (dropPending) itemClasses.push('is-tag-pending');
if (!matchesFilter) itemClasses.push('is-filtered-out');
@@ -1616,9 +1643,7 @@ const SkeuomorphicWorkspace = ({
itemRefs.current.delete(doc.id);
}
}}
onPointerDown={(event) =>
handlePointerDown(event, doc.id, { lockWhenZoomed: isZoomed })
}
onPointerDown={(event) => handlePointerDown(event, doc.id)}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
@@ -1640,6 +1665,7 @@ const SkeuomorphicWorkspace = ({
ensureAssetUrl={ensureAssetUrl}
getDocumentAsset={getDocumentAsset}
navScale={inverseTagScale}
onNavigatorSnapshot={handleNavigatorSnapshot}
/>
{tags.length > 0 && (
<div className="skeuo-item__tags" aria-hidden="true" style={tagsStyle}>
@@ -1685,8 +1711,16 @@ const SkeuomorphicWorkspace = ({
);
})
)}
</div>
</div>
</div>
<PreviewZoomOverlay
open={Boolean(overlayDisplay?.url)}
display={overlayDisplay}
onClose={closeOverlay}
originRect={overlayOriginRect}
originTransform={overlayOriginTransform}
/>
</>
);
};
+589 -363
View File
File diff suppressed because it is too large Load Diff
+86 -8
View File
@@ -1,12 +1,22 @@
import React, { useCallback, useMemo, useState } from 'react';
import { getTagColorStyle, HEX_COLOR_PATTERN } from '../utils/colors';
function TagsPanel({ tags, onRefresh, onUpdateTag, onDeleteTag, onNotify }) {
function TagsPanel({
tags,
onRefresh,
onCreateTag,
onUpdateTag,
onDeleteTag,
onNotify,
}) {
const [editingId, setEditingId] = useState(null);
const [draftLabel, setDraftLabel] = useState('');
const [draftColor, setDraftColor] = useState('');
const [saving, setSaving] = useState(false);
const [deletingId, setDeletingId] = useState(null);
const [createLabel, setCreateLabel] = useState('');
const [createColor, setCreateColor] = useState('');
const [creating, setCreating] = useState(false);
const startEdit = useCallback((tag) => {
setEditingId(tag.id);
@@ -98,25 +108,93 @@ function TagsPanel({ tags, onRefresh, onUpdateTag, onDeleteTag, onNotify }) {
[onDeleteTag, editingId, cancelEdit, onNotify],
);
const handleCreate = useCallback(
async (event) => {
event.preventDefault();
if (typeof onCreateTag !== 'function') {
return;
}
const trimmedLabel = createLabel.trim();
if (!trimmedLabel) {
onNotify?.('Tag label cannot be empty.', 'error');
return;
}
const trimmedColor = createColor.trim();
const colorPattern = /^#([0-9a-fA-F]{6})$/;
if (trimmedColor && !colorPattern.test(trimmedColor)) {
onNotify?.('Colors must use the #RRGGBB format.', 'error');
return;
}
setCreating(true);
try {
await onCreateTag({
label: trimmedLabel,
color: trimmedColor ? trimmedColor : null,
});
setCreateLabel('');
setCreateColor('');
} catch (createError) {
const message = createError?.message || 'Failed to create tag.';
onNotify?.(message, 'error');
} finally {
setCreating(false);
}
},
[createLabel, createColor, onCreateTag, onNotify],
);
return (
<section className="tags-panel column">
<div className="column-header">
<div className="column-header__titles">
<section className="tags-panel">
<div className="panel-section__header">
<div className="panel-section__titles">
<h2>Tags</h2>
<div className="column-subtitle">{tags.length} total</div>
<div className="panel-section__subtitle">{tags.length} total</div>
</div>
<div className="header-actions">
<div className="header-actions tags-actions">
<form className="tags-actions__form" onSubmit={handleCreate}>
<input
type="text"
placeholder="New tag label"
value={createLabel}
onChange={(event) => setCreateLabel(event.target.value)}
disabled={creating}
/>
<input
type="color"
className="tags-table__color-picker"
value={createColor || '#3366ff'}
onChange={(event) => setCreateColor(event.target.value)}
disabled={creating}
aria-label="Tag color (optional)"
/>
{createColor && (
<button
type="button"
className="secondary"
onClick={() => setCreateColor('')}
disabled={creating}
>
Clear
</button>
)}
<button type="submit" disabled={creating || !createLabel.trim()}>
{creating ? 'Creating…' : 'Create'}
</button>
</form>
<button
className="secondary"
type="button"
onClick={onRefresh}
disabled={saving || Boolean(deletingId)}
disabled={saving || creating || Boolean(deletingId)}
>
Refresh
</button>
</div>
</div>
<div className="column-body tags-panel__body">
<div className="panel-section__body tags-panel__body">
{tags.length === 0 ? (
<div className="empty-state">No tags created yet.</div>
) : (
+98
View File
@@ -9,6 +9,15 @@ import {
IconLayoutGrid,
IconArrowLeft,
IconArrowRight,
IconArrowUp,
IconChevronsRight,
IconChevronsLeft,
IconAnalyze,
IconWindowMaximize,
IconTextScan2,
IconFolderPlus,
IconRefresh,
IconMinusVertical,
} from '@tabler/icons-react';
import FolderSvg from '../assets/folder.svg';
@@ -120,6 +129,78 @@ export const ArrowRightIcon = ({ className, size = '1em', stroke = 1.6, ...rest
/>
);
export const ChevronsLeftIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconChevronsLeft
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const ChevronsRightIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconChevronsRight
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const FolderPlusIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconFolderPlus
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const RefreshIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconRefresh
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const ArrowUpIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconArrowUp
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const MinusVerticalIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconMinusVertical
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const AnalyzeIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconAnalyze
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const WindowMaximizeIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconWindowMaximize
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export default {
ChevronIcon,
TrashIcon,
@@ -130,4 +211,21 @@ export default {
DownloadIcon,
ViewListIcon,
ViewGridIcon,
ChevronsLeftIcon,
ChevronsRightIcon,
AnalyzeIcon,
WindowMaximizeIcon,
FolderPlusIcon,
RefreshIcon,
ArrowUpIcon,
MinusVerticalIcon,
};
export const TextScanIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconTextScan2
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);