diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md index 638b42cda..0352d38c2 100644 --- a/web/src/components/MemoEditor/README.md +++ b/web/src/components/MemoEditor/README.md @@ -39,7 +39,7 @@ Code blocks use lazy-loaded `@pierre/highlights` tokens as editor decorations, w ### State -A reducer (`edit/state/reducer.ts`) drives an external store; consumers subscribe to one slice via `useEditorSelector`, so typing re-renders only what reads `content`. `state.content` is the document as Markdown and the single source of truth. UI flags (focus mode, loading, pending inline images), metadata (visibility, Space, attachments, relations, location), timestamps, local files awaiting upload and accepted suggestions live beside it. +A reducer (`edit/state/reducer.ts`) drives an external store; consumers subscribe to one slice via `useEditorSelector`, so typing re-renders only what reads `content`. `state.content` is the document as Markdown and the single source of truth. UI flags (focus mode, loading, pending inline images), metadata (visibility, Space, attachments, relations, location), timestamps, local files awaiting upload, the shared order of saved attachments and new files (`attachmentOrder`) and accepted suggestions live beside it. ### The editor contract @@ -47,11 +47,15 @@ A reducer (`edit/state/reducer.ts`) drives an external store; consumers subscrib ### Formatting and source mode -Formatting is the editor's own: its toolbar appears over selected text, the slash menu and Markdown shortcuts change block types, and its keys cover the rest. The editor's `mode` option shows the whole memo as Markdown text, with its syntax highlighted, and edits it as text; `useSourceMode` (`@/hooks/useSourceMode`) keeps the choice in the account's `EDITOR` user setting (`source_mode`), so it follows the user to every device; a switch applies at once and reverts if saving fails, and Settings → Editor changes the same value. To people it is "Markdown mode", the + menu's item with the code glyph (Lucide `CodeXml`), checked while on; in code it keeps the editor's name, source mode. A small, noninteractive `Markdown` label sits inside the composer's top-right corner while source mode is on. Switching changes no text and emits no change. In source mode the toolbar, slash menu, block handle and link card do not show; the `#tag` and `:emoji` popups open as in rich mode, the formatting keys edit the Markdown, and the checklist chip toggles the task marker on the caret's line through the same `toggleTaskList` command. The controller reads tags and checklists from the text parsed as a memo. The source text is in the body font (the editor's `sourceFont` token is left at its default) so a switch keeps the text's rhythm; nothing in memos targets the editor's source classes. +Formatting is the editor's own: its toolbar appears over selected text, the slash menu and Markdown shortcuts change block types, and its keys cover the rest. The editor's `mode` option shows the whole memo as Markdown text, with its syntax highlighted, and edits it as text; `useSourceMode` (`@/hooks/useSourceMode`) keeps the choice in the account's `EDITOR` user setting (`source_mode`), so it follows the user to every device; a switch applies at once and reverts if saving fails, and Settings → Editor changes the same value. To people it is "Markdown mode", the + menu's item with the code glyph (Lucide `CodeXml`), checked while on; in code it keeps the editor's name, source mode. A small, noninteractive `Markdown` label sits beside the commit button while source mode is on, where it never covers the text. Switching changes no text and emits no change. In source mode the toolbar, slash menu, block handle and link card do not show; the `#tag` and `:emoji` popups open as in rich mode, the formatting keys edit the Markdown, and the checklist chip toggles the task marker on the caret's line through the same `toggleTaskList` command. The controller reads tags and checklists from the text parsed as a memo. The source text is in the body font (the editor's `sourceFont` token is left at its default) so a switch keeps the text's rhythm; nothing in memos targets the editor's source classes. ### Saving -`useMemoSave` validates the draft, uploads local files, and hands the save to `memoService.save` with the operations it runs: the server's current copy (fetched into the detail cache to diff against), `useUpdateMemo` and `useCreateMemo`. Hosts that close after saving (edit, comment) hold a brief "Saved" confirmation before the session resets; the in-place composer resets at once. Uploads that landed before a failed save stay on the draft as attachments so a retry does not upload them again. +`useMemoSave` validates the draft, uploads local files, and hands the save to `memoService.save` with the operations it runs: the server's current copy (fetched into the detail cache to diff against), `useUpdateMemo` and `useCreateMemo`. Hosts that close after saving (edit, comment) hold a brief "Saved" confirmation before the session resets; the in-place composer resets at once. Uploads that landed before a failed save stay on the draft as attachments so a retry does not upload them again. The save keeps the draft's attachment order (`edit/utils/attachmentOrder.ts`): new files land where they were dragged among the saved ones, not after them. + +### Attachments, links and place + +The draft's attachments take the saved memo's shape: images, videos and drawings are a gallery with the saved memo's arrangement at the composer's 10rem height (`resolveEditorGalleryLayout`), and audio and files are rows in one headerless list that continues with the draft's links and place. The rows' glyphs say what each is. Saved attachments and new files share one order, a list of keys (an attachment's name, a new file's preview URL, or for an edited drawing the name of the attachment it replaces); it stays empty until the first reorder. Tiles reorder by drag (a long press on touch) or Alt + arrow keys; rows by their grip (drag, or arrow keys on the focused grip). `useDragReorder` does this on pointer events, without a drag library. Links and the place have no order. A tile's actions (insert into the text, edit a drawing, remove) are dark keys in its corner on hover, or one More menu on touch; "New" and "Edited" labels mark files not saved yet. While a memo is edited in place, the memos that link to it stay listed, read-only. ### Drawings diff --git a/web/src/components/MemoEditor/edit/EditSession.tsx b/web/src/components/MemoEditor/edit/EditSession.tsx index 80f9f1933..9ea032736 100644 --- a/web/src/components/MemoEditor/edit/EditSession.tsx +++ b/web/src/components/MemoEditor/edit/EditSession.tsx @@ -347,8 +347,7 @@ export const EditSession: React.FC = ({ ref={editorContainerRef} className={cn( "group w-full flex flex-col justify-between items-start gap-2", - // A card that is the frame already supplies the background, border and padding, and - // positions the Markdown tag in its own corner; a session floating over the page in + // A card that is the frame already supplies the background, border and padding; a session floating over the page in // focus mode always brings its own. The bottom is 16px like the sides: the toolbar's // hard edge needs more room than the text's soft top. (!frameless || isFocusMode) && "relative bg-mu-surface px-4 pt-3 pb-4 rounded-mu-lg border border-mu-line/70", @@ -356,17 +355,6 @@ export const EditSession: React.FC = ({ !isFocusMode && className, )} > - {isSourceMode && ( - - Markdown - - )} {/* Formatting is the editor's own: its toolbar appears over selected text, and the slash menu and Markdown shortcuts change block types. Focus mode always shows the memo's time ("Now" before it has one) and adds diff --git a/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx b/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx index 3742b6213..68df31655 100644 --- a/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx +++ b/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx @@ -130,6 +130,12 @@ export const EditorToolbar: FC = ({
+ {/* Markdown mode is said beside the commit button, where it never covers the text. */} + {sourceMode.isSourceMode && ( + + Markdown + + )} {onCancel && ( ))} diff --git a/web/src/components/MemoEditor/edit/editor.css b/web/src/components/MemoEditor/edit/editor.css index f480f2fda..fdb1f3c20 100644 --- a/web/src/components/MemoEditor/edit/editor.css +++ b/web/src/components/MemoEditor/edit/editor.css @@ -72,16 +72,18 @@ } } +/* An upload started in the text: a rail on the left, then the progress or the failure in caption + type, and once it failed, Retry and Keep as kit ghost buttons (uploadAnchors.ts). */ .memo-upload-anchor { position: relative; display: flex; - min-height: 2.25rem; + flex-wrap: wrap; + min-height: 1.75rem; align-items: center; - gap: 0.375rem; + gap: 0.25rem 0.375rem; margin: 0.375rem 0; padding-left: 1rem; - font-family: inherit; - font-size: 0.6875rem; + font: 400 13px / 18px var(--mu-font-sans); } .memo-upload-anchor-rail { @@ -106,54 +108,27 @@ transform: translateY(-50%); } -.memo-upload-anchor-badge { +.memo-upload-anchor-message { display: inline-flex; align-items: center; gap: 0.375rem; - border-radius: var(--mu-radius-md); - background: color-mix(in oklab, var(--mu-primary) 8%, transparent); - padding: 0.25rem 0.5rem; - color: var(--mu-primary); - font-weight: 500; + margin-inline-end: 0.125rem; + color: var(--mu-ink-muted); } -.memo-upload-anchor[data-status="failed"] .memo-upload-anchor-badge { - background: color-mix(in oklab, var(--mu-danger) 8%, transparent); +.memo-upload-anchor[data-status="failed"] .memo-upload-anchor-message { color: var(--mu-danger); } -.memo-upload-anchor-spinner { - width: 0.75rem; - height: 0.75rem; - border: 1.5px solid currentColor; - border-right-color: transparent; - border-radius: 999px; - animation: spin 1s linear infinite; +.memo-upload-anchor-message svg { + width: var(--mu-icon-sm); + height: var(--mu-icon-sm); + flex: none; } -.memo-upload-anchor-actions { - display: inline-flex; - gap: 0.25rem; -} - -.memo-upload-anchor-action { - border-radius: var(--mu-radius-md); - padding: 0.25rem 0.5rem; - color: var(--mu-ink-muted); - font-weight: 500; -} - -.memo-upload-anchor-action:hover, -.memo-upload-anchor-action:focus-visible { - background: var(--mu-hover); - color: var(--mu-ink); - outline: none; -} - -@media (prefers-reduced-motion: reduce) { - .memo-upload-anchor-spinner { - animation: none; - } +.memo-upload-anchor-message svg * { + stroke-width: var(--mu-icon-stroke); + vector-effect: non-scaling-stroke; } /* The editor portals its own UI outside the composer. Its menus, toolbars and cards take the diff --git a/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts index 366dba161..8820e3b4f 100644 --- a/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts +++ b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts @@ -13,6 +13,7 @@ import { useTranslate } from "@/utils/i18n"; import { errorService, memoService, validationService } from "../services"; import { DrawingNotSavedError, type MemoSaveOperations, mergeUploadedAttachments } from "../services/memoService"; import { useEditorContext } from "../state"; +import { renameUploadedKeys } from "../utils/attachmentOrder"; import { restampDefaultCreateTime } from "../utils/deriveDefaultCreateTime"; /** How long a closing host shows "Saved" before it unmounts the editor. */ @@ -84,6 +85,7 @@ export function useMemoSave({ }), ); dispatch(actions.setLocalFiles(current.localFiles.filter((file) => !uploaded.has(file.previewUrl)))); + dispatch(actions.setAttachmentOrder(renameUploadedKeys(current.attachmentOrder, uploaded))); }; const operations: MemoSaveOperations = { diff --git a/web/src/components/MemoEditor/edit/services/memoService.ts b/web/src/components/MemoEditor/edit/services/memoService.ts index 6cae26ce7..2ab544c81 100644 --- a/web/src/components/MemoEditor/edit/services/memoService.ts +++ b/web/src/components/MemoEditor/edit/services/memoService.ts @@ -8,6 +8,7 @@ import type { Memo } from "@/types/proto/api/memo_service_pb"; import { MemoSchema } from "@/types/proto/api/memo_service_pb"; import type { EditorState } from "../state"; import type { LocalFile } from "../types/attachment"; +import { orderAttachments } from "../utils/attachmentOrder"; import { uploadService } from "./uploadService"; /** @@ -133,7 +134,13 @@ export const memoService = { const additions = state.localFiles.filter((file) => !file.replaces); const replacements = state.localFiles.filter((file) => file.replaces); const newAttachments = await uploadService.uploadFiles(additions, options.onFileUploaded); - let allAttachments = mergeUploadedAttachments(state.metadata.attachments, newAttachments); + // New files take the places the draft gave them among the saved ones. + const uploadedByPreviewUrl = new Map(additions.map((file, index) => [file.previewUrl, newAttachments[index]])); + let allAttachments = orderAttachments( + mergeUploadedAttachments(state.metadata.attachments, newAttachments), + uploadedByPreviewUrl, + state.attachmentOrder, + ); // 2. Update existing memo if (options.memoName) { diff --git a/web/src/components/MemoEditor/edit/state/actions.ts b/web/src/components/MemoEditor/edit/state/actions.ts index 1a4369bb3..4e1d7d771 100644 --- a/web/src/components/MemoEditor/edit/state/actions.ts +++ b/web/src/components/MemoEditor/edit/state/actions.ts @@ -32,6 +32,11 @@ export const editorActions = { payload: files, }), + setAttachmentOrder: (order: string[]): EditorAction => ({ + type: "SET_ATTACHMENT_ORDER", + payload: order, + }), + toggleFocusMode: (): EditorAction => ({ type: "TOGGLE_FOCUS_MODE", }), diff --git a/web/src/components/MemoEditor/edit/state/reducer.ts b/web/src/components/MemoEditor/edit/state/reducer.ts index 2f2082af2..6dcb3fcbb 100644 --- a/web/src/components/MemoEditor/edit/state/reducer.ts +++ b/web/src/components/MemoEditor/edit/state/reducer.ts @@ -48,6 +48,12 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS localFiles: action.payload, }; + case "SET_ATTACHMENT_ORDER": + return { + ...state, + attachmentOrder: action.payload, + }; + case "TOGGLE_FOCUS_MODE": return { ...state, diff --git a/web/src/components/MemoEditor/edit/state/types.ts b/web/src/components/MemoEditor/edit/state/types.ts index da511696b..5bc85392d 100644 --- a/web/src/components/MemoEditor/edit/state/types.ts +++ b/web/src/components/MemoEditor/edit/state/types.ts @@ -34,6 +34,9 @@ export interface EditorState { updateTime?: Date; }; localFiles: LocalFile[]; + /** The order of saved attachments and new files together, as keys (see utils/attachmentOrder). + * Empty until the user reorders; the save keeps it. */ + attachmentOrder: string[]; /** Whether an audio recording is in flight; gates save. The recorder's full * state lives in useAudioRecorder — only this shared bit reaches the store. */ recorderBusy: boolean; @@ -48,6 +51,7 @@ export type EditorAction = | { type: "ADD_LOCAL_FILE"; payload: LocalFile } | { type: "REMOVE_LOCAL_FILE"; payload: string } | { type: "SET_LOCAL_FILES"; payload: LocalFile[] } + | { type: "SET_ATTACHMENT_ORDER"; payload: string[] } | { type: "TOGGLE_FOCUS_MODE" } | { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } } | { type: "SET_PENDING_INLINE_IMAGE_INSERTIONS"; payload: number } @@ -82,6 +86,7 @@ const defaultState: EditorState = { updateTime: undefined, }, localFiles: [], + attachmentOrder: [], recorderBusy: false, acceptedSuggestionIds: [], }; diff --git a/web/src/components/MemoEditor/edit/types/attachment.ts b/web/src/components/MemoEditor/edit/types/attachment.ts index a8c30bc26..39cccda59 100644 --- a/web/src/components/MemoEditor/edit/types/attachment.ts +++ b/web/src/components/MemoEditor/edit/types/attachment.ts @@ -194,12 +194,16 @@ export function filterByCategory(items: AttachmentItem[], categories: FileCatego return items.filter((item) => categorySet.has(item.category)); } +/** Pictures and videos, shown in the gallery; everything else is a row. */ +export const isMediaItem = (item: AttachmentItem): boolean => + item.category === "image" || item.category === "video" || item.category === "motion"; + export function separateMediaAndDocs(items: AttachmentItem[]): { media: AttachmentItem[]; docs: AttachmentItem[] } { const media: AttachmentItem[] = []; const docs: AttachmentItem[] = []; for (const item of items) { - if (item.category === "image" || item.category === "video" || item.category === "motion") { + if (isMediaItem(item)) { media.push(item); } else { docs.push(item); diff --git a/web/src/components/MemoEditor/edit/uploadAnchors.ts b/web/src/components/MemoEditor/edit/uploadAnchors.ts index 83172a36f..d25603f21 100644 --- a/web/src/components/MemoEditor/edit/uploadAnchors.ts +++ b/web/src/components/MemoEditor/edit/uploadAnchors.ts @@ -1,4 +1,5 @@ import type { WidgetRender } from "@usememos/editor"; +import { buttonClasses } from "@usememos/ui"; export type UploadAnchorStatus = "uploading" | "failed"; @@ -14,18 +15,23 @@ export interface UploadAnchorDescriptor { onKeepAttachments?: () => void; } +/** Lucide's CircleAlert, inlined because the widget renders outside React. */ +const ALERT_ICON_SVG = + ''; + const actionButton = (label: string, onClick: () => void): HTMLButtonElement => { const button = document.createElement("button"); button.type = "button"; - button.className = "memo-upload-anchor-action"; + // The kit's ghost button, so it hovers, presses and shows keyboard focus like every other. + button.className = buttonClasses({ variant: "ghost", size: "sm" }); button.textContent = label; button.addEventListener("click", onClick); return button; }; /** - * Renders an upload anchor into an editor widget: a rail and a badge holding - * the progress or failure message, plus Retry / Keep actions once it failed. + * Renders an upload anchor into an editor widget: a rail and the progress or failure + * message (a spinner or an alert glyph before it), plus Retry / Keep actions once it failed. * The widget sits after the block the upload was started in; it is never saved * and is not part of undo history. */ @@ -41,20 +47,23 @@ export const renderUploadAnchor = const rail = document.createElement("span"); rail.className = "memo-upload-anchor-rail"; - const badge = document.createElement("span"); - badge.className = "memo-upload-anchor-badge"; + const message = document.createElement("span"); + message.className = "memo-upload-anchor-message"; if (descriptor.status === "uploading") { + // The kit's spinner, sized like a 14px glyph. const spinner = document.createElement("span"); - spinner.className = "memo-upload-anchor-spinner"; + spinner.className = "mu-spinner mu-icon-sm"; spinner.setAttribute("aria-hidden", "true"); - badge.appendChild(spinner); + message.appendChild(spinner); + } else { + message.insertAdjacentHTML("afterbegin", ALERT_ICON_SVG); } - badge.append(descriptor.message); - element.append(rail, badge); + message.append(descriptor.message); + element.append(rail, message); if (descriptor.status === "failed") { const actions = document.createElement("span"); - actions.className = "memo-upload-anchor-actions"; + actions.className = "flex gap-1"; if (descriptor.onRetry) actions.appendChild(actionButton(descriptor.retryLabel, descriptor.onRetry)); if (descriptor.onKeepAttachments) actions.appendChild(actionButton(descriptor.keepLabel, descriptor.onKeepAttachments)); element.appendChild(actions); diff --git a/web/src/components/MemoEditor/edit/utils/attachmentOrder.ts b/web/src/components/MemoEditor/edit/utils/attachmentOrder.ts new file mode 100644 index 000000000..392495340 --- /dev/null +++ b/web/src/components/MemoEditor/edit/utils/attachmentOrder.ts @@ -0,0 +1,68 @@ +import type { Attachment } from "@/types/proto/api/attachment_service_pb"; +import type { LocalFile } from "../types/attachment"; + +/* + * Saved attachments and new files share one order in the draft. The order is a list of keys: + * a saved attachment's name, or a new file's preview URL. An edited drawing keeps the key of the + * attachment it replaces, so it holds that attachment's place. A key the order doesn't list (a + * file added after the last reorder) keeps its natural place: saved first, then new, as added. + */ + +/** The key a new file holds in the order. */ +export const localFileOrderKey = (localFile: LocalFile): string => localFile.replaces ?? localFile.previewUrl; + +/** Sorts `items` by `order`; items whose keys it doesn't list follow, in their own order. */ +export function sortByOrder(items: readonly T[], keysOf: (item: T) => string[], order: readonly string[]): T[] { + if (order.length === 0) return [...items]; + const rank = new Map(order.map((key, index) => [key, index])); + const rankOf = (item: T, index: number) => { + const ranks = keysOf(item).flatMap((key) => (rank.has(key) ? [rank.get(key) as number] : [])); + return ranks.length > 0 ? Math.min(...ranks) : order.length + index; + }; + return items + .map((item, index) => ({ item, rank: rankOf(item, index) })) + .sort((a, b) => a.rank - b.rank) + .map(({ item }) => item); +} + +/** + * The order after moving the group at `from` to the place of the group at `to`, where each group + * is one item's keys (a Live Photo is two files moving together). Moving down lands after the + * target, moving up before it, so the dragged item always ends up where it was dropped. + */ +export function moveGroup(groups: readonly string[][], from: number, to: number): string[] { + if (from === to || from < 0 || to < 0 || from >= groups.length || to >= groups.length) return Array.from(new Set(groups.flat())); + const next = [...groups]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + // An edited drawing and the saved drawing it replaces share a key; list it once. + return Array.from(new Set(next.flat())); +} + +/** + * The order to sort by: the draft's, or before the first reorder the natural one, so an edited + * drawing already sits where the saved drawing it replaces was. + */ +export const effectiveOrder = ( + order: readonly string[], + attachments: readonly Attachment[], + localFiles: readonly LocalFile[], +): readonly string[] => + order.length > 0 ? order : [...attachments.map((attachment) => attachment.name), ...localFiles.map((localFile) => localFile.previewUrl)]; + +/** + * The memo's attachments in the draft's order, once the new files have uploaded. `uploaded` + * maps each new file's preview URL to the attachment it became. + */ +export function orderAttachments( + attachments: readonly Attachment[], + uploaded: ReadonlyMap, + order: readonly string[], +): Attachment[] { + return sortByOrder(attachments, (attachment) => [attachment.name], renameUploadedKeys(order, uploaded)); +} + +/** The order with each uploaded file's preview URL swapped for its attachment's name. */ +export function renameUploadedKeys(order: readonly string[], uploaded: ReadonlyMap): string[] { + return order.map((key) => uploaded.get(key)?.name ?? key); +} diff --git a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx index 48206a855..9c41f8c21 100644 --- a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx +++ b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx @@ -1,30 +1,48 @@ -import { Button, Tooltip } from "@usememos/ui"; +import { Button, Menu, Spinner, Tooltip } from "@usememos/ui"; import { - ChevronDownIcon, - ChevronUpIcon, + EllipsisIcon, FileAudioIcon, FileIcon, FileTextIcon, + GripVerticalIcon, ImagePlusIcon, PauseIcon, PencilLineIcon, PlayIcon, XIcon, } from "lucide-react"; -import { type FC, type MouseEvent, useMemo, useRef, useState } from "react"; -import { isDrawingFilename } from "@/components/DrawingSheet"; +import { + type FC, + type KeyboardEvent, + type MouseEvent, + type PointerEvent, + type ReactElement, + type ReactNode, + useMemo, + useRef, + useState, +} from "react"; +import { createPortal } from "react-dom"; +import { DRAWING_PAPER, isDrawingFilename } from "@/components/DrawingSheet"; import type { AttachmentItem, DrawingSource, LocalFile } from "@/components/MemoEditor/edit/types/attachment"; -import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/edit/types/attachment"; -import MetadataSection, { +import { + getAudioRecordingTimeLabel, + isMediaItem, + separateMediaAndDocs, + toAttachmentItems, +} from "@/components/MemoEditor/edit/types/attachment"; +import { effectiveOrder, localFileOrderKey, moveGroup, sortByOrder } from "@/components/MemoEditor/edit/utils/attachmentOrder"; +import { METADATA_ROW_BOX_CLASSES, METADATA_ROW_CONTENT_TEXT_CLASSES, METADATA_ROW_CONTROLS_CLASSES, + METADATA_ROW_LIST_CLASSES, METADATA_ROW_SLOT_BUTTON_CLASSES, METADATA_ROW_SLOT_CLASSES, MetadataRowDetail, } from "@/components/MemoMetadata/MetadataSection"; import PreviewImageDialog from "@/components/PreviewImageDialog"; -import useMediaQuery from "@/hooks/useMediaQuery"; +import VideoPoster from "@/components/VideoPoster"; import { cn } from "@/lib/utils"; import type { Attachment } from "@/types/proto/api/attachment_service_pb"; import { formatFileSize, getFileTypeLabel } from "@/utils/format"; @@ -32,10 +50,27 @@ import { useTranslate } from "@/utils/i18n"; import { canInlineAttachment, extractAttachmentUIDFromName } from "@/utils/managed-attachment"; import type { PreviewMediaItem } from "@/utils/media-item"; import { formatAudioTime, toggleAudioPlayback } from "./attachmentHelpers"; +import { COVER_MEDIA_CLASS, DRAWING_SHEET_CELL_MEDIA_CLASS, TILE_BADGE_CLASS, VISUAL_TILE_BUTTON_CLASS } from "./attachmentVisualClasses"; +import { previewOrder, useDragReorder } from "./useDragReorder"; +import { resolveEditorGalleryLayout } from "./visualGalleryLayout"; const collectMembers = (byId: ReadonlyMap, memberIds: string[]): T[] => memberIds.map((memberId) => byId.get(memberId)).filter((member): member is T => member !== undefined); +/** A dragged tile's place in the shown order: an empty dashed slot the item will settle into. */ +const TILE_PLACEHOLDER_CLASS = "border-dashed border-mu-edge bg-mu-well/50 shadow-none [&>*]:invisible"; +/** The same for a row: an outlined, empty row. */ +const ROW_PLACEHOLDER_CLASS = "bg-transparent shadow-[inset_0_0_0_1px_var(--mu-edge)] hover:bg-transparent [&>*]:invisible"; +/** The lifted copy that follows the pointer while an item is dragged. */ +const GHOST_CLASS = "pointer-events-none fixed start-0 top-0 z-(--mu-layer-popup) overflow-hidden rounded-mu-md shadow-mu-pop [scale:1.03]"; + +/** The attributes a reorderable item carries for `useDragReorder`. */ +interface ReorderAttributes { + "data-reorder-position": number; + "data-reorder-key": string; + "data-reorder-placeholder"?: boolean; +} + interface AttachmentListEditorProps { onTranscribeAttachment?: (attachment: Attachment) => void; transcribingAttachment?: string; @@ -45,6 +80,9 @@ interface AttachmentListEditorProps { onAttachmentsChange?: (attachments: Attachment[]) => void; onLocalFilesChange?: (localFiles: LocalFile[]) => void; onRemoveLocalFile?: (previewUrl: string) => void; + /** The draft's order of saved attachments and new files (see `attachmentOrder`). */ + order?: string[]; + onOrderChange?: (order: string[]) => void; inlineAttachmentUIDs?: ReadonlySet; onInsertAttachments?: (attachments: Attachment[]) => void; onInsertLocalFiles?: (localFiles: LocalFile[]) => void; @@ -54,187 +92,172 @@ interface AttachmentListEditorProps { onEditDrawing?: (source: DrawingSource) => void; /** The row whose drawing is being opened. */ openingDrawing?: string; + /** Rows that follow the attachments in the same list: the draft's links and place. */ + children?: ReactNode; } -interface RowAction { +interface ItemAction { label: string; onClick: () => void; disabled?: boolean; busy?: boolean; } -/** Trailing controls of an attachment row: quiet 24px squares that show once the row is engaged. */ -const AttachmentItemActions: FC<{ - transcriptionAction?: { label: string; onClick: () => void; disabled: boolean; busy: boolean }; - drawingAction?: RowAction; - placementAction?: { label: string; onClick: () => void; disabled?: boolean }; +interface ItemActions { + /** Inserts the image into the text. */ + placement?: ItemAction; + drawing?: ItemAction; + transcription?: ItemAction; onRemove?: () => void; - onMoveUp?: () => void; - onMoveDown?: () => void; - canMoveUp?: boolean; - canMoveDown?: boolean; -}> = ({ transcriptionAction, drawingAction, placementAction, onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true }) => { - const t = useTranslate(); - // A drawing row already carries Insert image; on narrow rows its edit action keeps only the glyph. - const isWide = useMediaQuery("md"); - const stopPropagation = (event: MouseEvent) => { - event.stopPropagation(); - }; - const drawingButton = drawingAction && ( - + onPreview?: () => void; + isUploadingInline: boolean; + /** "New" for a file not saved yet, "Edited" for an edit waiting to replace a saved drawing. */ + badge?: string; +} + +const stop = (event: MouseEvent) => event.stopPropagation(); + +/** A 24px dark key over a photo, labelled by its tooltip. */ +const TileKey = ({ icon, action }: { icon: ReactElement; action: ItemAction }) => ( + + { + stop(event); + action.onClick(); + }} + /> + } + /> + {action.label} + +); + +/** A tile's picture: a drawing on its paper, a video's poster, or the image itself. */ +const TileMedia = ({ item }: { item: AttachmentItem }) => + item.category === "image" && isDrawingFilename(item.filename) ? ( + + ) : item.category === "video" ? ( + + ) : ( + ); +/** + * One image, video or drawing in the gallery. The tile opens the preview and drags to reorder; + * its actions are dark keys in the corner that show on hover or focus. On touch screens, which + * have no hover, one "More" key holds the same actions. + */ +const AttachmentTile: FC<{ + item: AttachmentItem; + actions: ItemActions; + className?: string; + /** A drawing alone in the gallery is a raised sheet, as in the saved memo; among others it is framed like them. */ + alone: boolean; + /** The tile is being dragged: its place shows as an empty slot while a lifted copy follows the pointer. */ + placeholder: boolean; + dragProps: ReorderAttributes & { + onPointerDown: (event: PointerEvent) => void; + onKeyDown: (event: KeyboardEvent) => void; + }; +}> = ({ item, actions, className, alone, placeholder, dragProps }) => { + const t = useTranslate(); + const drawing = item.category === "image" && isDrawingFilename(item.filename); + const keyActions: { icon: ReactElement; action: ItemAction }[] = [ + ...(actions.drawing ? [{ icon: , action: actions.drawing }] : []), + ...(actions.placement ? [{ icon: , action: actions.placement }] : []), + ...(actions.onRemove ? [{ icon: , action: { label: t("editor.attachments.remove"), onClick: actions.onRemove } }] : []), + ]; + return ( -
- {transcriptionAction && ( - + // A tile is a div, not a - )} - {onMoveUp && ( - - { - stopPropagation(event); - onMoveUp(); - }} - disabled={!canMoveUp} - aria-label={t("editor.attachments.move-up")} - icon={} - /> - } - /> - {t("editor.attachments.move-up")} - + style={drawing && !placeholder ? { background: DRAWING_PAPER } : undefined} + onClick={actions.onPreview} + onKeyDown={(event) => { + if (event.target === event.currentTarget && (event.key === "Enter" || event.key === " ")) { + event.preventDefault(); + actions.onPreview?.(); + return; + } + // Alt + arrows reorder, so plain arrows keep scrolling the page. + if (event.altKey) dragProps.onKeyDown(event); + }} + > + + + {item.category === "motion" && {t("attachment-library.labels.live")}} + {actions.badge && {actions.badge}} + {actions.isUploadingInline && ( +
+ +
)} - {onMoveDown && ( - - { - stopPropagation(event); - onMoveDown(); - }} - disabled={!canMoveDown} - aria-label={t("editor.attachments.move-down")} - icon={} + {keyActions.length > 0 && ( + // Controls over a photo are dark keys in every theme. +
+
+ {keyActions.map(({ icon, action }) => ( + + ))} +
+
+ + } aria-label={t("common.more")} onClick={stop} />} /> - } - /> - {t("editor.attachments.move-down")} - - )} - - {onRemove && ( - - { - stopPropagation(event); - onRemove(); - }} - aria-label={t("editor.attachments.remove")} - icon={} - /> - } - /> - {t("editor.attachments.remove")} - + + {keyActions.map(({ icon, action }) => ( + + {action.label} + + ))} + + +
+
)}
); }; -const AttachmentItemCard: FC<{ - transcriptionAction?: { label: string; onClick: () => void; disabled: boolean; busy: boolean }; - drawingAction?: RowAction; +/** + * An audio or file attachment as a metadata row. Its actions are 24px ghost buttons that + * overlay the details once the row is engaged; the grip drags it, or moves it with the arrow keys. + */ +const AttachmentRow: FC<{ item: AttachmentItem; - onPreview?: () => void; - onRemove?: () => void; - onMoveUp?: () => void; - onMoveDown?: () => void; - canMoveUp?: boolean; - canMoveDown?: boolean; - isUploadingInline?: boolean; - placementAction?: { label: string; onClick: () => void; disabled?: boolean }; -}> = ({ - item, - onPreview, - onRemove, - onMoveUp, - onMoveDown, - canMoveUp = true, - canMoveDown = true, - isUploadingInline, - placementAction, - transcriptionAction, - drawingAction, -}) => { + actions: ItemActions; + canReorder: boolean; + placeholder: boolean; + rowProps: ReorderAttributes & { onPointerDown: (event: PointerEvent) => void }; + onGripKeyDown: (event: KeyboardEvent) => void; +}> = ({ item, actions, canReorder, placeholder, rowProps, onGripKeyDown }) => { const t = useTranslate(); - const { category, filename, thumbnailUrl, mimeType, size, sourceUrl, isVoiceNote, audioMeta } = item; + const { category, filename, mimeType, size, sourceUrl, isVoiceNote, audioMeta } = item; const audioRef = useRef(null); const [isPlaying, setIsPlaying] = useState(false); - const fileTypeLabel = item.category === "motion" ? t("attachment-library.labels.live-photo") : getFileTypeLabel(mimeType); - const isPreviewable = category === "image" || category === "video" || category === "motion"; const recordingTimeLabel = isVoiceNote ? getAudioRecordingTimeLabel(filename) : undefined; const titleLabel = isVoiceNote && recordingTimeLabel @@ -243,38 +266,23 @@ const AttachmentItemCard: FC<{ ? t("editor.audio-recorder.attachment-label") : filename; const detailParts = [ - isUploadingInline ? t("editor.insert-menu.uploading-inline-image") : undefined, + actions.badge, audioMeta?.durationSeconds ? formatAudioTime(audioMeta.durationSeconds) : undefined, - fileTypeLabel, + getFileTypeLabel(mimeType), size ? formatFileSize(size) : undefined, ]; const handleAudioToggle = async (event: MouseEvent) => { event.stopPropagation(); - const audio = audioRef.current; - if (!audio) { - return; - } - + if (!audio) return; await toggleAudioPlayback(audio, sourceUrl, () => setIsPlaying(false)); }; return ( -
-
- {(category === "image" || category === "motion") && thumbnailUrl ? ( -
{ - event.stopPropagation(); - onPreview?.(); - }} - className={cn("size-full overflow-hidden", isPreviewable ? "cursor-pointer" : "cursor-default")} - aria-label={t("common.preview-name", { name: filename })} - > - -
- ) : isVoiceNote ? ( +
+
+ {isVoiceNote ? ( <> ) : category === "audio" ? ( ) : ( )} - {category === "motion" && ( - - {t("attachment-library.labels.live")} - - )}
@@ -324,26 +315,78 @@ const AttachmentItemCard: FC<{ - +
+ {actions.transcription && ( + + )} + {actions.onRemove && ( + + { + stop(event); + actions.onRemove?.(); + }} + aria-label={t("editor.attachments.remove")} + icon={} + /> + } + /> + {t("editor.attachments.remove")} + + )} + {canReorder && ( + + } + /> + } + /> + {t("editor.attachments.reorder-hint")} + + )} +
); }; +/** + * The draft's attachments: images, videos and drawings as the saved memo's gallery (at the + * composer's height), then audio and files as rows in one list with the draft's links and place. + * Saved attachments and new files share one order; dragging a tile or a row's grip changes it. + */ const AttachmentListEditor: FC = ({ attachments, localFiles = [], onAttachmentsChange, onLocalFilesChange, onRemoveLocalFile, + order = [], + onOrderChange, inlineAttachmentUIDs = new Set(), onInsertAttachments, onInsertLocalFiles, @@ -354,109 +397,78 @@ const AttachmentListEditor: FC = ({ transcriptionDisabled = false, onEditDrawing, openingDrawing, + children, }) => { const t = useTranslate(); const [previewState, setPreviewState] = useState<{ open: boolean; initialIndex: number }>({ open: false, initialIndex: 0 }); const attachmentsByName = useMemo(() => new Map(attachments.map((attachment) => [attachment.name, attachment])), [attachments]); - const allItems = toAttachmentItems(attachments, localFiles); - // Saved drawings with an edit waiting to upload over them: the edit's row stands in for them. + // Items address their members by id, so index once instead of re-scanning both + // source arrays for every item on every render. + const localFilesByPreviewUrl = useMemo(() => new Map(localFiles.map((localFile) => [localFile.previewUrl, localFile])), [localFiles]); + const keysOf = (item: AttachmentItem) => + item.isLocal ? collectMembers(localFilesByPreviewUrl, item.memberIds).map(localFileOrderKey) : item.memberIds; + const allItems = sortByOrder(toAttachmentItems(attachments, localFiles), keysOf, effectiveOrder(order, attachments, localFiles)); + // Saved drawings with an edit waiting to upload over them: the edit stands in for them. const replacedAttachmentNames = new Set(localFiles.flatMap((localFile) => (localFile.replaces ? [localFile.replaces] : []))); - const isHiddenItem = (item: AttachmentItem) => - !item.isLocal && - collectMembers(attachmentsByName, item.memberIds).some((attachment) => { - if (replacedAttachmentNames.has(attachment.name)) return true; - const uid = extractAttachmentUIDFromName(attachment.name); - return uid ? inlineAttachmentUIDs.has(uid) : false; - }); // A managed image already has its placement represented in Markdown. Keep // the attachment bound to the memo, but do not repeat its logical media group - // in the attachment section. Removing the Markdown reference makes it - // visible here again on the next render. A replaced drawing stays bound too, - // and shows again if its pending edit is removed. - const items = allItems.filter((item) => !isHiddenItem(item)); - const allAttachmentItems = allItems.filter((item) => !item.isLocal); - const attachmentItems = items.filter((item) => !item.isLocal); - const localItems = items.filter((item) => item.isLocal); + // here. Removing the Markdown reference makes it visible again on the next + // render. A replaced drawing stays bound too, and shows again if its pending + // edit is removed. + const isReplaced = (item: AttachmentItem) => + !item.isLocal && collectMembers(attachmentsByName, item.memberIds).some((attachment) => replacedAttachmentNames.has(attachment.name)); + const isHiddenItem = (item: AttachmentItem) => + isReplaced(item) || + (!item.isLocal && + collectMembers(attachmentsByName, item.memberIds).some((attachment) => { + const uid = extractAttachmentUIDFromName(attachment.name); + return uid ? inlineAttachmentUIDs.has(uid) : false; + })); + const { media: visualItems, docs: rowItems } = separateMediaAndDocs(allItems.filter((item) => !isHiddenItem(item))); + const previewItems = useMemo( () => - items.reduce((acc, item) => { + visualItems.map((item): PreviewMediaItem => { const itemAttachments = item.isLocal ? undefined : collectMembers(attachmentsByName, item.memberIds); - if (item.category === "image") { - acc.push({ - id: item.id, - kind: "image", - sourceUrl: item.sourceUrl, - posterUrl: item.thumbnailUrl, - filename: item.filename, - attachments: itemAttachments, - }); - return acc; - } - - if (item.category === "video") { - acc.push({ - id: item.id, - kind: "video", - sourceUrl: item.sourceUrl, - posterUrl: item.thumbnailUrl, - filename: item.filename, - attachments: itemAttachments, - }); - return acc; - } - if (item.category === "motion") { - acc.push({ + return { id: item.id, kind: "motion", motionUrl: item.sourceUrl, posterUrl: item.thumbnailUrl, filename: item.filename, attachments: itemAttachments, - }); - return acc; + }; } - - return acc; - }, []), - [attachmentsByName, items], + return { + id: item.id, + kind: item.category === "video" ? "video" : "image", + sourceUrl: item.sourceUrl, + posterUrl: item.thumbnailUrl, + filename: item.filename, + attachments: itemAttachments, + }; + }), + [attachmentsByName, visualItems], ); - // Items address their members by id, so index once instead of re-scanning both - // source arrays for every item on every render. - const localFilesByPreviewUrl = useMemo(() => new Map(localFiles.map((localFile) => [localFile.previewUrl, localFile])), [localFiles]); - - const handleMoveAttachments = (itemId: string, direction: -1 | 1) => { - if (!onAttachmentsChange) return; - - const itemIndex = attachmentItems.findIndex((item) => item.id === itemId); - const targetIndex = itemIndex + direction; - if (itemIndex < 0 || targetIndex < 0 || targetIndex >= attachmentItems.length) { - return; - } - - const reorderedItems = [...attachmentItems]; - [reorderedItems[itemIndex], reorderedItems[targetIndex]] = [reorderedItems[targetIndex], reorderedItems[itemIndex]]; - - let visibleIndex = 0; - const mergedItems = allAttachmentItems.map((item) => (isHiddenItem(item) ? item : reorderedItems[visibleIndex++]!)); - onAttachmentsChange(mergedItems.flatMap((item) => collectMembers(attachmentsByName, item.memberIds))); - }; - - const handleMoveLocalFiles = (itemId: string, direction: -1 | 1) => { - if (!onLocalFilesChange) return; - - const itemIndex = localItems.findIndex((item) => item.id === itemId); - const targetIndex = itemIndex + direction; - if (itemIndex < 0 || targetIndex < 0 || targetIndex >= localItems.length) { - return; - } - - const reorderedItems = [...localItems]; - [reorderedItems[itemIndex], reorderedItems[targetIndex]] = [reorderedItems[targetIndex], reorderedItems[itemIndex]]; - - onLocalFilesChange(reorderedItems.flatMap((item) => collectMembers(localFilesByPreviewUrl, item.memberIds))); + // Moving within the gallery or the rows reorders the whole draft: the item takes its target's + // place among every attachment, hidden ones included, so their order is kept too. + // A saved drawing with a pending edit is left out: the edit holds its key and its place. + const orderedItems = allItems.filter((item) => !isReplaced(item)); + const moveWithin = (list: AttachmentItem[]) => (from: number, to: number) => { + const fromIndex = orderedItems.indexOf(list[from]); + const toIndex = orderedItems.indexOf(list[to]); + if (fromIndex < 0 || toIndex < 0) return; + onOrderChange?.(moveGroup(orderedItems.map(keysOf), fromIndex, toIndex)); }; + const galleryDrag = useDragReorder(visualItems.length, moveWithin(visualItems)); + const rowDrag = useDragReorder(rowItems.length, moveWithin(rowItems)); + // While an item is dragged, the list shows the order it would drop into. + const shownVisualItems = previewOrder(visualItems, galleryDrag.dragging, galleryDrag.over); + const shownRowItems = previewOrder(rowItems, rowDrag.dragging, rowDrag.over); + const draggedTile = galleryDrag.dragging !== null ? visualItems[galleryDrag.dragging] : undefined; + const draggedRow = rowDrag.dragging !== null ? rowItems[rowDrag.dragging] : undefined; const handleRemoveItem = (item: AttachmentItem) => { if (item.isLocal) { @@ -467,102 +479,182 @@ const AttachmentListEditor: FC = ({ } return; } - - if (onAttachmentsChange) { - onAttachmentsChange(attachments.filter((attachment) => !item.memberIds.includes(attachment.name))); - } + onAttachmentsChange?.(attachments.filter((attachment) => !item.memberIds.includes(attachment.name))); }; - const handlePreviewItem = (item: AttachmentItem) => { - const previewIndex = previewItems.findIndex((previewItem) => previewItem.id === item.id); - if (previewIndex < 0) { - return; - } + const actionsFor = (item: AttachmentItem): ItemActions => { + const itemAttachments = collectMembers(attachmentsByName, item.memberIds); + const itemLocalFiles = collectMembers(localFilesByPreviewUrl, item.memberIds); + const isUploadingInline = item.isLocal && item.memberIds.some((memberID) => uploadingLocalFileURLs.has(memberID)); + const isTranscribing = item.id === transcribingAttachment; + const isPendingReplacement = itemLocalFiles.some((localFile) => localFile.replaces); - setPreviewState({ open: true, initialIndex: previewIndex }); + // External links are fetched cross-origin by the browser, which most hosts refuse. + const transcribableAttachment = + !item.isLocal && item.category === "audio" && !itemAttachments[0]?.externalLink ? itemAttachments[0] : undefined; + const transcription = + transcribableAttachment && onTranscribeAttachment + ? { + label: t(isTranscribing ? "editor.audio-recorder.transcribing" : "editor.audio-recorder.transcribe"), + onClick: () => onTranscribeAttachment(transcribableAttachment), + disabled: transcriptionDisabled || Boolean(transcribingAttachment), + busy: isTranscribing, + } + : undefined; + + // A drawing opens from the original file: a saved one is downloaded, so it must live on this server. + const drawingSource: DrawingSource | undefined = + item.category !== "image" || !isDrawingFilename(item.filename) + ? undefined + : item.isLocal + ? itemLocalFiles[0] && { kind: "local", localFile: itemLocalFiles[0] } + : itemAttachments[0] && !itemAttachments[0].externalLink + ? { kind: "attachment", attachment: itemAttachments[0] } + : undefined; + const drawing = + drawingSource && onEditDrawing + ? { + label: t("editor.drawing.edit"), + onClick: () => onEditDrawing(drawingSource), + disabled: placementActionsDisabled || Boolean(openingDrawing), + busy: openingDrawing !== undefined && item.memberIds.includes(openingDrawing), + } + : undefined; + + // Inserting uploads at once, so a pending edit of a saved drawing would overwrite it before the memo is saved. + const canInsert = + (item.category === "image" || item.category === "motion") && + (item.isLocal ? !isPendingReplacement : itemAttachments.some(canInlineAttachment)); + const placement = canInsert + ? { + label: t("editor.insert-menu.insert-image"), + onClick: () => + item.isLocal ? onInsertLocalFiles?.(itemLocalFiles) : onInsertAttachments?.(itemAttachments.filter(canInlineAttachment)), + disabled: placementActionsDisabled, + } + : undefined; + + return { + placement, + drawing, + transcription, + isUploadingInline, + onRemove: isUploadingInline || isTranscribing ? undefined : () => handleRemoveItem(item), + onPreview: isMediaItem(item) + ? () => { + const previewIndex = previewItems.findIndex((previewItem) => previewItem.id === item.id); + if (previewIndex >= 0) setPreviewState({ open: true, initialIndex: previewIndex }); + } + : undefined, + badge: !item.isLocal ? undefined : isPendingReplacement ? t("editor.attachments.edited") : t("editor.attachments.new"), + }; }; - if (items.length === 0) { + const canReorder = Boolean(onOrderChange); + const gallery = resolveEditorGalleryLayout(visualItems.length); + const hasRows = rowItems.length > 0 || Boolean(children); + + if (visualItems.length === 0 && !hasRows) { return null; } return ( <> - - {items.map((item) => { - const itemList = item.isLocal ? localItems : attachmentItems; - const itemIndex = itemList.findIndex((entry) => entry.id === item.id); - const itemAttachments = collectMembers(attachmentsByName, item.memberIds); - const itemLocalFiles = collectMembers(localFilesByPreviewUrl, item.memberIds); - const isUploadingInline = item.isLocal && item.memberIds.some((memberID) => uploadingLocalFileURLs.has(memberID)); - const isTranscribing = item.id === transcribingAttachment; - // External links are fetched cross-origin by the browser, which most hosts refuse. - const transcribableAttachment = - !item.isLocal && item.category === "audio" && !itemAttachments[0]?.externalLink ? itemAttachments[0] : undefined; - const transcriptionAction = - transcribableAttachment && onTranscribeAttachment - ? { - label: t(isTranscribing ? "editor.audio-recorder.transcribing" : "editor.audio-recorder.transcribe"), - onClick: () => onTranscribeAttachment(transcribableAttachment), - disabled: transcriptionDisabled || Boolean(transcribingAttachment), - busy: isTranscribing, - } - : undefined; - // A drawing opens from the original file: a saved one is downloaded, so it must live on this server. - const drawingSource: DrawingSource | undefined = - item.category !== "image" || !isDrawingFilename(item.filename) - ? undefined - : item.isLocal - ? itemLocalFiles[0] && { kind: "local", localFile: itemLocalFiles[0] } - : itemAttachments[0] && !itemAttachments[0].externalLink - ? { kind: "attachment", attachment: itemAttachments[0] } - : undefined; - const isOpeningDrawing = openingDrawing !== undefined && item.memberIds.includes(openingDrawing); - const drawingAction = - drawingSource && onEditDrawing - ? { - label: t("editor.drawing.edit"), - onClick: () => onEditDrawing(drawingSource), - disabled: placementActionsDisabled || Boolean(openingDrawing), - busy: isOpeningDrawing, - } - : undefined; - // Inserting uploads at once, so a pending edit of a saved drawing would overwrite it before the memo is saved. - const isPendingReplacement = itemLocalFiles.some((localFile) => localFile.replaces); - const canInsert = - (item.category === "image" || item.category === "motion") && - (item.isLocal ? !isPendingReplacement : itemAttachments.some(canInlineAttachment)); - const placementAction = canInsert - ? { - label: t("editor.insert-menu.insert-image"), - onClick: () => - item.isLocal ? onInsertLocalFiles?.(itemLocalFiles) : onInsertAttachments?.(itemAttachments.filter(canInlineAttachment)), - disabled: placementActionsDisabled, - } - : undefined; + {visualItems.length > 0 && ( +
+ {shownVisualItems.map((item, position) => { + const index = visualItems.indexOf(item); + const placeholder = galleryDrag.dragging === index; + return ( + undefined, + onKeyDown: canReorder ? galleryDrag.keyDown(index) : () => undefined, + }} + /> + ); + })} +
+ )} - return ( - handlePreviewItem(item) - : undefined - } - onRemove={isUploadingInline || isTranscribing ? undefined : () => handleRemoveItem(item)} - onMoveUp={item.isLocal ? () => handleMoveLocalFiles(item.id, -1) : () => handleMoveAttachments(item.id, -1)} - onMoveDown={item.isLocal ? () => handleMoveLocalFiles(item.id, 1) : () => handleMoveAttachments(item.id, 1)} - canMoveUp={itemIndex > 0} - canMoveDown={itemIndex >= 0 && itemIndex < itemList.length - 1} - /> - ); - })} -
+ {hasRows && ( +
+ {shownRowItems.map((item, position) => { + const index = rowItems.indexOf(item); + const placeholder = rowDrag.dragging === index; + return ( + 1} + placeholder={placeholder} + rowProps={{ + "data-reorder-position": position, + "data-reorder-key": item.id, + "data-reorder-placeholder": placeholder || undefined, + onPointerDown: canReorder ? rowDrag.pointerDown(index) : () => undefined, + }} + onGripKeyDown={rowDrag.keyDown(index)} + /> + ); + })} + {children} +
+ )} + + {/* The lifted copy follows the pointer above everything, so it is portaled to the body. */} + {draggedTile && + galleryDrag.grab && + createPortal( +
+ +
, + document.body, + )} + {draggedRow && + rowDrag.grab && + createPortal( +
+ + {draggedRow.category === "audio" ? ( + + ) : ( + + )} + + {draggedRow.filename} +
, + document.body, + )} { /** * A drawing as a sheet of paper. The sheet extends the drawing's own paper beyond its edges, so - * it can be any size. The image is the original file at 2x: exports carry 2 pixels per drawn + * it can be any size. On its own it is a raised sheet; in a collage (`framed`) it takes the photos' + * hairline frame, so every cell of the grid has the same edge. The image is the original file at 2x: exports carry 2 pixels per drawn * pixel, so it shows at the size it was drawn and keeps strokes and text sharp. */ const DrawingTile = ({ @@ -113,16 +114,22 @@ const DrawingTile = ({ mediaClassName, onPreview, overlayLabel, + framed = false, }: { item: VisualItem; className: string; mediaClassName: string; onPreview?: () => void; overlayLabel?: string; + framed?: boolean; }) => { const [paper, setPaper] = useState(DRAWING_PAPER); return ( -
+
); } diff --git a/web/src/components/MemoMetadata/Attachment/attachmentVisualClasses.ts b/web/src/components/MemoMetadata/Attachment/attachmentVisualClasses.ts index 1c3f108b8..3f92e9912 100644 --- a/web/src/components/MemoMetadata/Attachment/attachmentVisualClasses.ts +++ b/web/src/components/MemoMetadata/Attachment/attachmentVisualClasses.ts @@ -8,9 +8,10 @@ export const VISUAL_TILE_BUTTON_CLASS = "relative block overflow-hidden rounded-mu-md border border-mu-line/70 bg-mu-well/30 p-0 text-left transition-colors mu-focus"; /** - * A drawing is a sheet of paper on the card rather than a photo in a frame: no tile border or + * A lone drawing is a sheet of paper on the card rather than a photo in a frame: no tile border or * well, just the package's raised edge, the same in both themes. Hover lifts it a little more - * instead of the photo scrim and zoom. + * instead of the photo scrim and zoom. In a collage a drawing takes the photos' hairline frame + * instead, so one grid never mixes two edges. */ export const DRAWING_SHEET_TILE_CLASS = "relative block overflow-hidden rounded-mu-md p-0 text-left shadow-mu-raised transition-shadow hover:shadow-mu-key mu-focus"; @@ -49,3 +50,10 @@ export const MEDIA_HOVER_GRADIENT_CLASS = `pointer-events-none absolute inset-0 export const COLLAGE_VIDEO_PLAY_BADGE_CLASS = `bottom-2 right-2 ${VISUAL_Z.badge} h-7 w-7 bg-mu-canvas/80 text-mu-ink/70`; export const OVERFLOW_TILE_OVERLAY_CLASS = `pointer-events-none absolute inset-0 ${VISUAL_Z.overflowMask} flex items-center justify-center bg-black/45 mu-heading text-white backdrop-blur-[2px]`; + +/** + * A state label on an editor tile ("Live", "New", "Edited"): the same frosted pill as a saved + * motion photo's Live badge, but not a control. + */ +export const TILE_BADGE_CLASS = + "pointer-events-none absolute select-none rounded-full border border-mu-line/45 bg-mu-canvas/65 px-2 py-0.5 mu-label-xs uppercase tracking-wide text-mu-ink backdrop-blur-sm"; diff --git a/web/src/components/MemoMetadata/Attachment/useDragReorder.ts b/web/src/components/MemoMetadata/Attachment/useDragReorder.ts new file mode 100644 index 000000000..e05d8409d --- /dev/null +++ b/web/src/components/MemoMetadata/Attachment/useDragReorder.ts @@ -0,0 +1,325 @@ +import { + type KeyboardEvent, + type MouseEvent as ReactMouseEvent, + type PointerEvent as ReactPointerEvent, + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, +} from "react"; + +/** Pointer travel before a press becomes a drag, so a click stays a click. */ +const DRAG_THRESHOLD_PX = 4; +/** A finger has to rest this long on a tile before it drags, so swiping still scrolls the page. */ +const LONG_PRESS_MS = 350; +/** A finger that moves this far before the long press lands is scrolling. */ +const LONG_PRESS_SLOP_PX = 8; +/** How long items take to slide aside, and the lifted copy to settle into its slot. */ +const MOTION_MS = 180; +const MOTION_EASING = "cubic-bezier(0.2, 0.9, 0.3, 1)"; + +const prefersReducedMotion = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; + +interface Pending { + index: number; + pointerId: number; + x: number; + y: number; + /** Where the press landed inside the item, so the lifted copy stays under the pointer at that spot. */ + offsetX: number; + offsetY: number; + width: number; + height: number; + /** Touch on a tile: dragging starts after a long press instead of after movement. */ + longPress: boolean; + timer?: number; +} + +/** The lifted copy's size and where it starts; the hook moves it from there through `ghostRef`. */ +export interface DragGrab { + width: number; + height: number; + left: number; + top: number; +} + +interface Slot { + position: number; + left: number; + top: number; + right: number; + bottom: number; +} + +/** `list` with the item at `from` moved to `to`: the order a drag shows before it's dropped. */ +export function previewOrder(list: readonly T[], from: number | null, to: number | null): T[] { + if (from === null || to === null || from === to || from >= list.length || to >= list.length) return [...list]; + const next = [...list]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + return next; +} + +/** + * Reorders a list by pointer or keyboard, without a drag library. While an item is dragged it + * lifts: a copy follows the pointer (`grab` and `ghostRef`), the list shows the order it would + * drop into (`dragging` and `over`, applied with {@link previewOrder}), the other items slide + * aside, and the item's own place is a placeholder. Dropping settles the copy into that place and + * calls `onMove(from, to)`. Each rendered item carries `data-reorder-position` (its place in the + * shown order) and `data-reorder-key` (stable, for the slide); the placeholder carries + * `data-reorder-placeholder`. Mouse and pen drag once they travel a few pixels; a finger on a tile + * drags after a long press, and on a row only from its grip. Arrow keys on a focused handle move + * its item by one. The click that ends a drag is swallowed, so dropping a tile doesn't preview it. + */ +export function useDragReorder(count: number, onMove: (from: number, to: number) => void) { + const containerRef = useRef(null); + const ghostRef = useRef(null); + const pending = useRef(null); + const suppressClick = useRef(false); + const settling = useRef(false); + const [dragging, setDragging] = useState(null); + const [over, setOver] = useState(null); + const [grab, setGrab] = useState(null); + const draggingRef = useRef(null); + const overRef = useRef(null); + // Where each item stood before the shown order last changed, for the slide. + const snapshot = useRef | null>(null); + // Each place in the list, relative to the container, measured when the drag starts. + const slots = useRef([]); + + const itemsIn = () => Array.from(containerRef.current?.querySelectorAll("[data-reorder-key]") ?? []); + const takeSnapshot = () => { + snapshot.current = new Map(itemsIn().map((element) => [element.dataset.reorderKey as string, element.getBoundingClientRect()])); + }; + + // Slide every item from where it stood to where the new order puts it. It runs after every + // render and acts only when a move took a snapshot, so keyboard moves slide too. + useLayoutEffect(() => { + const before = snapshot.current; + snapshot.current = null; + if (!before || prefersReducedMotion()) return; + for (const element of itemsIn()) { + const from = before.get(element.dataset.reorderKey as string); + if (!from) continue; + // A slide still running ends here: `from` already caught the item mid-way, so it carries on from there. + for (const animation of element.getAnimations?.() ?? []) animation.cancel(); + const to = element.getBoundingClientRect(); + const dx = from.left - to.left; + const dy = from.top - to.top; + const sx = to.width ? from.width / to.width : 1; + const sy = to.height ? from.height / to.height : 1; + if (dx === 0 && dy === 0 && sx === 1 && sy === 1) continue; + element.animate( + [ + { transformOrigin: "top left", transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, + { transformOrigin: "top left", transform: "none" }, + ], + { duration: MOTION_MS, easing: MOTION_EASING }, + ); + } + }); + + const setOverIndex = (index: number | null) => { + if (overRef.current === index) return; + takeSnapshot(); + overRef.current = index; + setOver(index); + }; + + const measureSlots = () => { + const container = containerRef.current; + const box = container?.getBoundingClientRect(); + if (!container || !box) { + slots.current = []; + return; + } + slots.current = Array.from(container.querySelectorAll("[data-reorder-position]")).flatMap((element) => { + const position = Number(element.dataset.reorderPosition); + if (!Number.isInteger(position)) return []; + const rect = element.getBoundingClientRect(); + return [ + { position, left: rect.left - box.left, top: rect.top - box.top, right: rect.right - box.left, bottom: rect.bottom - box.top }, + ]; + }); + }; + + const start = (press: Pending) => { + measureSlots(); + draggingRef.current = press.index; + overRef.current = press.index; + setDragging(press.index); + setOver(press.index); + setGrab({ width: press.width, height: press.height, left: press.x - press.offsetX, top: press.y - press.offsetY }); + }; + + const clear = () => { + draggingRef.current = null; + overRef.current = null; + settling.current = false; + setDragging(null); + setOver(null); + setGrab(null); + }; + + // The place under the pointer, by the slots measured at the start. The items themselves won't do: + // they move as the shown order changes and while they slide, so the item under a still pointer + // would keep changing and the order would flip back and forth. A place stays put whichever + // item fills it, since the layout depends only on how many items there are. + const positionAt = (x: number, y: number): number | null => { + const box = containerRef.current?.getBoundingClientRect(); + if (!box) return null; + const px = x - box.left; + const py = y - box.top; + return slots.current.find((slot) => px >= slot.left && px < slot.right && py >= slot.top && py < slot.bottom)?.position ?? null; + }; + + const end = (commit: boolean) => { + const from = draggingRef.current; + const to = overRef.current; + if (pending.current?.timer) window.clearTimeout(pending.current.timer); + pending.current = null; + if (from === null || settling.current) return; + // The click that follows this pointerup, if any, arrives before the timer runs. + suppressClick.current = true; + window.setTimeout(() => { + suppressClick.current = false; + }, 0); + + const finish = () => { + if (commit && to !== null && to !== from) onMove(from, to); + clear(); + }; + if (!commit) { + takeSnapshot(); + clear(); + return; + } + // The lifted copy settles into the placeholder, then the list takes the order it showed. + const ghost = ghostRef.current; + const slot = containerRef.current?.querySelector("[data-reorder-placeholder]"); + if (!ghost || !slot || prefersReducedMotion()) { + finish(); + return; + } + settling.current = true; + const target = slot.getBoundingClientRect(); + const animation = ghost.animate( + [ + { translate: ghost.style.translate, scale: "1.03" }, + { translate: `${target.left}px ${target.top}px`, scale: "1" }, + ], + { + duration: MOTION_MS, + easing: MOTION_EASING, + fill: "forwards", + }, + ); + // A page that paints no frames (a background tab) never finishes the animation; the timer drops anyway. + let done = false; + const settle = () => { + if (done) return; + done = true; + finish(); + }; + animation.onfinish = settle; + animation.oncancel = settle; + window.setTimeout(settle, MOTION_MS + 80); + }; + + // The window listeners stay put for the whole life of the list; this keeps `onMove` current in them. + const endDrag = useEffectEvent(end); + + useEffect(() => { + const handleMove = (event: PointerEvent) => { + const press = pending.current; + if (!press || event.pointerId !== press.pointerId || settling.current) return; + if (draggingRef.current === null) { + const distance = Math.hypot(event.clientX - press.x, event.clientY - press.y); + if (press.longPress) { + if (distance > LONG_PRESS_SLOP_PX) endDrag(false); + return; + } + if (distance < DRAG_THRESHOLD_PX) return; + start(press); + } + if (ghostRef.current) ghostRef.current.style.translate = `${event.clientX - press.offsetX}px ${event.clientY - press.offsetY}px`; + // The place under the pointer is where the item would drop; between places, the target stays. + const position = positionAt(event.clientX, event.clientY); + if (position !== null) setOverIndex(position); + }; + const handleUp = (event: PointerEvent) => { + if (pending.current && event.pointerId === pending.current.pointerId) endDrag(event.type === "pointerup"); + }; + const handleKey = (event: globalThis.KeyboardEvent) => { + if (event.key === "Escape" && draggingRef.current !== null) endDrag(false); + }; + // Once a finger drags, the page must not scroll under it. + const handleTouchMove = (event: TouchEvent) => { + if (draggingRef.current !== null) event.preventDefault(); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + window.addEventListener("keydown", handleKey); + window.addEventListener("touchmove", handleTouchMove, { passive: false }); + return () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + window.removeEventListener("keydown", handleKey); + window.removeEventListener("touchmove", handleTouchMove); + }; + }, []); + + /** Starts tracking a press on an item. `longPress` is for whole tiles, so touch scrolling still works. */ + const pointerDown = (index: number, options?: { longPress?: boolean }) => (event: ReactPointerEvent) => { + if (event.button !== 0 || count < 2 || draggingRef.current !== null) return; + // A press on one of the item's own controls is that control's, not a drag; the grip is the exception. + const control = (event.target as HTMLElement).closest("button, a, [role=menuitem]"); + if (control && control !== event.currentTarget && !control.hasAttribute("data-reorder-handle")) return; + const longPress = Boolean(options?.longPress) && event.pointerType === "touch"; + // A finger on a row scrolls the page; it drags only from the grip. + if (event.pointerType === "touch" && !longPress && !(event.target as HTMLElement).closest("[data-reorder-handle]")) return; + const rect = event.currentTarget.getBoundingClientRect(); + const press: Pending = { + index, + pointerId: event.pointerId, + x: event.clientX, + y: event.clientY, + offsetX: event.clientX - rect.left, + offsetY: event.clientY - rect.top, + width: rect.width, + height: rect.height, + longPress, + }; + if (longPress) { + press.timer = window.setTimeout(() => { + if (pending.current === press) start(press); + }, LONG_PRESS_MS); + } + pending.current = press; + }; + + /** Arrow keys move the focused item one place earlier or later. */ + const keyDown = (index: number) => (event: KeyboardEvent) => { + const step = + event.key === "ArrowUp" || event.key === "ArrowLeft" ? -1 : event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : 0; + if (step === 0) return; + const target = index + step; + if (target < 0 || target >= count) return; + event.preventDefault(); + takeSnapshot(); + onMove(index, target); + }; + + /** Swallows the click that ends a drag, so dropping a tile doesn't open its preview. */ + const clickCapture = (event: ReactMouseEvent) => { + if (!suppressClick.current) return; + suppressClick.current = false; + event.preventDefault(); + event.stopPropagation(); + }; + + return { containerRef, ghostRef, dragging, over, grab, pointerDown, keyDown, clickCapture }; +} diff --git a/web/src/components/MemoMetadata/Attachment/visualGalleryLayout.ts b/web/src/components/MemoMetadata/Attachment/visualGalleryLayout.ts index a15b7b5ab..677ab314f 100644 --- a/web/src/components/MemoMetadata/Attachment/visualGalleryLayout.ts +++ b/web/src/components/MemoMetadata/Attachment/visualGalleryLayout.ts @@ -70,3 +70,29 @@ export const resolveVisualGalleryLayout = (items: AttachmentVisualItem[]): Visua })), }; }; + +/** The composer's gallery height: the saved mosaic's arrangement, short enough to keep the toolbar near the text. */ +const EDITOR_GRID_HEIGHT_CLASS = "h-40"; + +/** + * The editor's gallery: the same arrangement as the saved memo's collage for up to six items, at + * the composer's height. Every item stays visible (no `+N`), since each one can be edited. + */ +export const resolveEditorGalleryLayout = ( + count: number, +): { containerClassName: string; cellClassName: (index: number) => string | undefined } => { + if (count <= 1) return { containerClassName: cn("grid grid-cols-1 gap-1.5", EDITOR_GRID_HEIGHT_CLASS), cellClassName: () => undefined }; + if (count === 2) return { containerClassName: cn("grid grid-cols-2 gap-1.5", EDITOR_GRID_HEIGHT_CLASS), cellClassName: () => undefined }; + if (count === 3) { + return { + containerClassName: cn("grid grid-cols-2 grid-rows-2 gap-1.5", EDITOR_GRID_HEIGHT_CLASS), + cellClassName: (index) => (index === 0 ? "row-span-2" : undefined), + }; + } + if (count === 4) + return { containerClassName: cn("grid grid-cols-2 grid-rows-2 gap-1.5", EDITOR_GRID_HEIGHT_CLASS), cellClassName: () => undefined }; + if (count <= COLLAGE_MAX_VISIBLE_CELLS) { + return { containerClassName: cn("grid grid-cols-3 grid-rows-2 gap-1.5", EDITOR_GRID_HEIGHT_CLASS), cellClassName: () => undefined }; + } + return { containerClassName: "grid grid-cols-3 auto-rows-[4.875rem] gap-1.5", cellClassName: () => undefined }; +}; diff --git a/web/src/components/MemoMetadata/Relation/RelationListEditor.tsx b/web/src/components/MemoMetadata/Relation/RelationListEditor.tsx index 59e2cd0a4..83f94f6f5 100644 --- a/web/src/components/MemoMetadata/Relation/RelationListEditor.tsx +++ b/web/src/components/MemoMetadata/Relation/RelationListEditor.tsx @@ -1,11 +1,12 @@ +import { LinkIcon, MilestoneIcon } from "lucide-react"; import type { FC } from "react"; import { useMemo } from "react"; -import MetadataSection, { METADATA_ROW_BOX_CLASSES, MetadataRowRemoveControl } from "@/components/MemoMetadata/MetadataSection"; +import { METADATA_ROW_BOX_CLASSES, MetadataRowDetail, MetadataRowRemoveControl } from "@/components/MemoMetadata/MetadataSection"; import type { MemoRelation } from "@/types/proto/api/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; import RelationRow from "./RelationRow"; -import { getEditorReferenceRelations } from "./relationHelpers"; -import { useResolvedRelationMemos } from "./useResolvedRelationMemos"; +import { getEditorBacklinkRelations, getEditorReferenceRelations } from "./relationHelpers"; +import { useRelationMemoDates, useResolvedRelationMemos } from "./useResolvedRelationMemos"; interface RelationListEditorProps { relations: MemoRelation[]; @@ -14,27 +15,31 @@ interface RelationListEditorProps { memoName?: string; } +/** + * The draft's links as rows in the editor's one list: the memos it links to, which can be + * removed, then the memos that link to it, read-only, so the memo keeps its shape while edited. + * Each row shows the memo's text and, in its details, when it was written. + */ const RelationListEditor: FC = ({ relations, onRelationsChange, parentPage, memoName }) => { const t = useTranslate(); const referenceRelations = useMemo(() => getEditorReferenceRelations(relations, memoName), [relations, memoName]); + const backlinkRelations = useMemo(() => getEditorBacklinkRelations(relations, memoName), [relations, memoName]); const relatedMemoNames = useMemo( - () => referenceRelations.flatMap((relation) => (relation.relatedMemo?.name ? [relation.relatedMemo.name] : [])), - [referenceRelations], + () => [ + ...referenceRelations.flatMap((relation) => (relation.relatedMemo?.name ? [relation.relatedMemo.name] : [])), + ...backlinkRelations.flatMap((relation) => (relation.memo?.name ? [relation.memo.name] : [])), + ], + [referenceRelations, backlinkRelations], ); const resolvedMemos = useResolvedRelationMemos(relatedMemoNames); + const dates = useRelationMemoDates(relatedMemoNames); - const handleDeleteRelation = (memoName: string) => { - if (onRelationsChange) { - onRelationsChange(relations.filter((relation) => relation.relatedMemo?.name !== memoName)); - } + const handleDeleteRelation = (name: string) => { + onRelationsChange?.(relations.filter((relation) => relation.relatedMemo?.name !== name)); }; - if (referenceRelations.length === 0) { - return null; - } - return ( - + <> {referenceRelations.map((relation) => { const relatedMemo = relation.relatedMemo!; if (resolvedMemos[relatedMemo.name] === null) return null; @@ -42,12 +47,35 @@ const RelationListEditor: FC = ({ relations, onRelation // A split row: the link is the focusable body, and the remove control overlays the trailing end once the row is engaged. return (
- - handleDeleteRelation(memo.name)} /> + } + /> + {onRelationsChange && ( + handleDeleteRelation(memo.name)} /> + )}
); })} -
+ {backlinkRelations.map((relation) => { + const linkingMemo = relation.memo!; + if (resolvedMemos[linkingMemo.name] === null) return null; + const memo = resolvedMemos[linkingMemo.name] || linkingMemo; + return ( + } + /> + ); + })} + ); }; diff --git a/web/src/components/MemoMetadata/Relation/RelationRow.tsx b/web/src/components/MemoMetadata/Relation/RelationRow.tsx index f4c45765d..63eddbfba 100644 --- a/web/src/components/MemoMetadata/Relation/RelationRow.tsx +++ b/web/src/components/MemoMetadata/Relation/RelationRow.tsx @@ -15,17 +15,20 @@ interface RelationRowProps { * of a row whose box is a wrapper carrying other controls (the editor's remove button). */ variant?: "row" | "label"; - /** Detail on the trailing rail, such as the relation's direction. */ + /** Detail on the trailing rail, such as the memo's date. */ trailing?: ReactNode; + /** Says what the glyph means, such as "Referenced by", for a pointer that rests on the row. */ + title?: string; } /** One related memo as a metadata row: a glyph in the leading slot and the snippet. */ -const RelationRow = ({ memo, parentPage, icon = LinkIcon, variant = "row", trailing }: RelationRowProps) => { +const RelationRow = ({ memo, parentPage, icon = LinkIcon, variant = "row", trailing, title }: RelationRowProps) => { const t = useTranslate(); return ( diff --git a/web/src/components/MemoMetadata/Relation/RelationRows.tsx b/web/src/components/MemoMetadata/Relation/RelationRows.tsx index e33eb7afd..3b170ea4e 100644 --- a/web/src/components/MemoMetadata/Relation/RelationRows.tsx +++ b/web/src/components/MemoMetadata/Relation/RelationRows.tsx @@ -2,10 +2,10 @@ import { LinkIcon, MilestoneIcon } from "lucide-react"; import { useMemo } from "react"; import type { MemoRelation } from "@/types/proto/api/memo_service_pb"; import { useTranslate } from "@/utils/i18n"; -import { METADATA_ROW_DETAIL_CLASSES } from "../MetadataSection"; +import { MetadataRowDetail } from "../MetadataSection"; import RelationRow from "./RelationRow"; import { getRelationBuckets, getRelationMemo, getRelationMemoName, type RelationDirection } from "./relationHelpers"; -import { useResolvedRelationMemos } from "./useResolvedRelationMemos"; +import { useRelationMemoDates, useResolvedRelationMemos } from "./useResolvedRelationMemos"; export interface RelationRowItem { relation: MemoRelation; @@ -31,9 +31,9 @@ interface RelationRowsProps { } /** - * Related memos are rows like the memo's files: a direction glyph in the slot, the - * snippet, and the direction spelled out on the detail rail. No header or tabs, so the - * list reads as part of the memo rather than a panel attached to it. + * Related memos are rows like the memo's files: a direction glyph in the slot (its title says + * which), the snippet, and the memo's date on the detail rail. No header or tabs, so the list + * reads as part of the memo rather than a panel attached to it. */ const RelationRows = ({ items, parentPage, enabled }: RelationRowsProps) => { const t = useTranslate(); @@ -46,6 +46,7 @@ const RelationRows = ({ items, parentPage, enabled }: RelationRowsProps) => { [items], ); const resolvedMemos = useResolvedRelationMemos(memoNames, { enabled }); + const dates = useRelationMemoDates(memoNames, { enabled }); const directionLabels: Record = { referencing: t("common.referencing"), referenced: t("common.referenced-by"), @@ -64,7 +65,8 @@ const RelationRows = ({ items, parentPage, enabled }: RelationRowsProps) => { memo={resolvedMemos[memo.name] ?? memo} parentPage={parentPage} icon={DIRECTION_ICONS[direction]} - trailing={{directionLabels[direction]}} + title={directionLabels[direction]} + trailing={} /> ); })} diff --git a/web/src/components/MemoMetadata/Relation/relationHelpers.ts b/web/src/components/MemoMetadata/Relation/relationHelpers.ts index e2913ff8a..300126771 100644 --- a/web/src/components/MemoMetadata/Relation/relationHelpers.ts +++ b/web/src/components/MemoMetadata/Relation/relationHelpers.ts @@ -40,3 +40,15 @@ export const getRelationMemo = (relation: MemoRelation, direction: RelationDirec export const getRelationMemoName = (relation: MemoRelation, direction: RelationDirection): string => { return getRelationMemo(relation, direction)?.name ?? ""; }; + +/** The links that point to this memo, shown read-only while it's edited. */ +export const getEditorBacklinkRelations = (relations: MemoRelation[], memoName?: string): MemoRelation[] => + memoName ? getRelationBuckets(relations, memoName).referenced : []; + +/** A related memo's date on its row: month and day, with the year when it isn't this year. */ +export const formatRelationDate = (date: Date, locale: string): string => + date.toLocaleDateString(locale, { + month: "short", + day: "numeric", + year: date.getFullYear() === new Date().getFullYear() ? undefined : "numeric", + }); diff --git a/web/src/components/MemoMetadata/Relation/useResolvedRelationMemos.ts b/web/src/components/MemoMetadata/Relation/useResolvedRelationMemos.ts index 30ce35b07..be84fe34c 100644 --- a/web/src/components/MemoMetadata/Relation/useResolvedRelationMemos.ts +++ b/web/src/components/MemoMetadata/Relation/useResolvedRelationMemos.ts @@ -1,9 +1,12 @@ import { create } from "@bufbuild/protobuf"; +import { timestampDate } from "@bufbuild/protobuf/wkt"; import { useQueries, useQueryClient } from "@tanstack/react-query"; +import { useTranslation } from "react-i18next"; import { findMemoInCollectionQueries, memoDetailQueryOptions } from "@/hooks/useMemoQueries"; import { type MemoRelation_MemoRef, MemoRelation_MemoRefSchema } from "@/types/proto/api/memo_service_pb"; +import { formatRelationDate } from "./relationHelpers"; -export const useResolvedRelationMemos = (memoNames: string[], options?: { enabled?: boolean }) => { +const useRelationMemoQueries = (memoNames: string[], options?: { enabled?: boolean }) => { const client = useQueryClient(); const names = Array.from(new Set(memoNames.filter(Boolean))); const queries = useQueries({ @@ -13,6 +16,11 @@ export const useResolvedRelationMemos = (memoNames: string[], options?: { enable initialData: () => findMemoInCollectionQueries(client, name, true), })), }); + return { names, queries }; +}; + +export const useResolvedRelationMemos = (memoNames: string[], options?: { enabled?: boolean }) => { + const { names, queries } = useRelationMemoQueries(memoNames, options); const resolved: Record = {}; queries.forEach((query, index) => { if (query.data === null) resolved[names[index]] = null; @@ -22,3 +30,17 @@ export const useResolvedRelationMemos = (memoNames: string[], options?: { enable }); return resolved; }; + +/** + * Each related memo's date for its row, formatted for the reader's language. It reads the same + * queries as {@link useResolvedRelationMemos}, so it adds no requests of its own. + */ +export const useRelationMemoDates = (memoNames: string[], options?: { enabled?: boolean }) => { + const { i18n } = useTranslation(); + const { names, queries } = useRelationMemoQueries(memoNames, options); + const dates: Record = {}; + queries.forEach((query, index) => { + if (query.data?.createTime) dates[names[index]] = formatRelationDate(timestampDate(query.data.createTime), i18n.language); + }); + return dates; +}; diff --git a/web/src/components/MemoView/MemoView.tsx b/web/src/components/MemoView/MemoView.tsx index 89e3a1577..066633a65 100644 --- a/web/src/components/MemoView/MemoView.tsx +++ b/web/src/components/MemoView/MemoView.tsx @@ -186,7 +186,7 @@ const MemoView = forwardRef((props, ref) => { ref={cardRef} tabIndex={readonly ? -1 : 0} > - {/* The editing session's Markdown tag takes the pinned mark's corner. */} + {/* The pinned mark steps aside while the memo is edited in place. */} {showPinned && memoData.pinned && !isEditing && } diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json index 724846c35..156206c1d 100644 --- a/web/src/locales/ar.json +++ b/web/src/locales/ar.json @@ -97,7 +97,6 @@ "profile": "الملف الشخصي", "referenced-by": "مشار إليه بواسطة", "referencing": "يشير إلى", - "relations": "العلاقات", "resources": "المصادر", "restore": "استعادة", "role": "الدور", @@ -311,9 +310,11 @@ "resize-image": "تغيير حجم الصورة" }, "attachments": { - "move-up": "نقل المرفق لأعلى", - "move-down": "نقل المرفق لأسفل", - "remove": "إزالة المرفق" + "edited": "معدَّل", + "new": "جديد", + "remove": "إزالة المرفق", + "reorder": "إعادة ترتيب {{name}}", + "reorder-hint": "اسحب، أو استخدم مفاتيح الأسهم" }, "remove-relation": "إزالة العلاقة", "remove-location": "إزالة الموقع", diff --git a/web/src/locales/az.json b/web/src/locales/az.json index a4dc977d8..31ce29ed5 100644 --- a/web/src/locales/az.json +++ b/web/src/locales/az.json @@ -206,7 +206,6 @@ "profile": "Profil", "referenced-by": "İstinad edənlər", "referencing": "İstinad edir", - "relations": "Əlaqələr", "resize-panel": "Panelin ölçüsünü dəyiş", "resize-sidebar": "Yan panelin ölçüsünü dəyiş", "resources": "Resurslar", @@ -413,9 +412,11 @@ "resize-image": "Şəklin ölçüsünü dəyiş" }, "attachments": { - "move-up": "Qoşmanı yuxarı köçür", - "move-down": "Qoşmanı aşağı köçür", - "remove": "Qoşmanı çıxar" + "edited": "Düzəldilib", + "new": "Yeni", + "remove": "Qoşmanı çıxar", + "reorder": "{{name}} sırasını dəyiş", + "reorder-hint": "Sürüşdürün və ya ox düymələrindən istifadə edin" }, "remove-relation": "Əlaqəni çıxar", "remove-location": "Məkanı çıxar", diff --git a/web/src/locales/bg.json b/web/src/locales/bg.json index dcb35ed54..e70ef1024 100644 --- a/web/src/locales/bg.json +++ b/web/src/locales/bg.json @@ -136,7 +136,6 @@ "profile": "Профил", "referenced-by": "Позовава се от", "referencing": "Рефериране", - "relations": "Връзки", "resources": "Ресурси", "restore": "Възстановяване", "role": "Роля", @@ -349,9 +348,11 @@ "resize-image": "Преоразмеряване на изображението" }, "attachments": { - "move-up": "Преместване на прикачения файл нагоре", - "move-down": "Преместване на прикачения файл надолу", - "remove": "Премахване на прикачения файл" + "edited": "Редактирано", + "new": "Ново", + "remove": "Премахване на прикачения файл", + "reorder": "Преподреждане на {{name}}", + "reorder-hint": "Плъзнете или използвайте клавишите със стрелки" }, "remove-relation": "Премахване на връзката", "remove-location": "Премахване на местоположението", diff --git a/web/src/locales/ca.json b/web/src/locales/ca.json index 84fbebd66..c9b0718c5 100644 --- a/web/src/locales/ca.json +++ b/web/src/locales/ca.json @@ -97,7 +97,6 @@ "profile": "Perfil", "referenced-by": "Referenciat per", "referencing": "Referenciant", - "relations": "Relacions", "resources": "Recursos", "restore": "Restaura", "role": "Rol", @@ -311,9 +310,11 @@ "resize-image": "Canvia la mida de la imatge" }, "attachments": { - "move-up": "Mou l'adjunt amunt", - "move-down": "Mou l'adjunt avall", - "remove": "Elimina l'adjunt" + "edited": "Editat", + "new": "Nou", + "remove": "Elimina l'adjunt", + "reorder": "Reordena {{name}}", + "reorder-hint": "Arrossega, o fes servir les tecles de fletxa" }, "remove-relation": "Elimina la relació", "remove-location": "Elimina la ubicació", diff --git a/web/src/locales/cs.json b/web/src/locales/cs.json index 6c0bf033d..24306ac56 100644 --- a/web/src/locales/cs.json +++ b/web/src/locales/cs.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Odkazováno", "referencing": "Odkazuje na", - "relations": "Souvislosti", "resources": "Zdroje", "restore": "Obnovit", "role": "Role", @@ -311,9 +310,11 @@ "resize-image": "Změnit velikost obrázku" }, "attachments": { - "move-up": "Posunout přílohu nahoru", - "move-down": "Posunout přílohu dolů", - "remove": "Odebrat přílohu" + "edited": "Upraveno", + "new": "Nové", + "remove": "Odebrat přílohu", + "reorder": "Změnit pořadí: {{name}}", + "reorder-hint": "Přetáhněte, nebo použijte šipky" }, "remove-relation": "Odebrat vazbu", "remove-location": "Odebrat místo", diff --git a/web/src/locales/da.json b/web/src/locales/da.json index b40696273..fc2e8ec68 100644 --- a/web/src/locales/da.json +++ b/web/src/locales/da.json @@ -136,7 +136,6 @@ "profile": "Profil", "referenced-by": "Refereret af", "referencing": "Referencer", - "relations": "Relationer", "resources": "Ressourcer", "restore": "Gendan", "role": "Rolle", @@ -349,9 +348,11 @@ "resize-image": "Tilpas billedets størrelse" }, "attachments": { - "move-up": "Flyt vedhæftet fil op", - "move-down": "Flyt vedhæftet fil ned", - "remove": "Fjern vedhæftet fil" + "edited": "Redigeret", + "new": "Ny", + "remove": "Fjern vedhæftet fil", + "reorder": "Flyt {{name}}", + "reorder-hint": "Træk, eller brug piletasterne" }, "remove-relation": "Fjern relation", "remove-location": "Fjern placering", diff --git a/web/src/locales/de.json b/web/src/locales/de.json index d8ee62243..60a4d5b94 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Verknüpft mit", "referencing": "Verknüpft", - "relations": "Beziehungen", "resources": "Ressourcen", "restore": "Wiederherstellen", "role": "Rolle", @@ -311,9 +310,11 @@ "resize-image": "Bildgröße ändern" }, "attachments": { - "move-up": "Anhang nach oben verschieben", - "move-down": "Anhang nach unten verschieben", - "remove": "Anhang entfernen" + "edited": "Bearbeitet", + "new": "Neu", + "remove": "Anhang entfernen", + "reorder": "{{name}} verschieben", + "reorder-hint": "Ziehen oder die Pfeiltasten verwenden" }, "remove-relation": "Verknüpfung entfernen", "remove-location": "Standort entfernen", diff --git a/web/src/locales/el.json b/web/src/locales/el.json index 64c5002f2..a740d1a4e 100644 --- a/web/src/locales/el.json +++ b/web/src/locales/el.json @@ -136,7 +136,6 @@ "profile": "Προφίλ", "referenced-by": "Αναφέρεται από", "referencing": "Αναφορά", - "relations": "Συγγένειες", "resources": "Πόροι", "restore": "Επαναφέρω", "role": "Ρόλος", @@ -349,9 +348,11 @@ "resize-image": "Αλλαγή μεγέθους εικόνας" }, "attachments": { - "move-up": "Μετακίνηση συνημμένου προς τα πάνω", - "move-down": "Μετακίνηση συνημμένου προς τα κάτω", - "remove": "Αφαίρεση συνημμένου" + "edited": "Επεξεργασμένο", + "new": "Νέο", + "remove": "Αφαίρεση συνημμένου", + "reorder": "Αναδιάταξη {{name}}", + "reorder-hint": "Σύρετε ή χρησιμοποιήστε τα πλήκτρα βέλους" }, "remove-relation": "Αφαίρεση συσχέτισης", "remove-location": "Αφαίρεση τοποθεσίας", diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.json index a8241f511..f5a1db057 100644 --- a/web/src/locales/en-GB.json +++ b/web/src/locales/en-GB.json @@ -97,7 +97,6 @@ "profile": "Profile", "referenced-by": "Referenced by", "referencing": "Referencing", - "relations": "Relations", "resources": "Resources", "restore": "Restore", "role": "Role", @@ -311,9 +310,11 @@ "resize-image": "Resize image" }, "attachments": { - "move-up": "Move attachment up", - "move-down": "Move attachment down", - "remove": "Remove attachment" + "edited": "Edited", + "new": "New", + "remove": "Remove attachment", + "reorder": "Reorder {{name}}", + "reorder-hint": "Drag, or use the arrow keys" }, "remove-relation": "Remove relation", "remove-location": "Remove location", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index b14351056..a85b110a5 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -206,7 +206,6 @@ "profile": "Profile", "referenced-by": "Referenced by", "referencing": "Referencing", - "relations": "Relations", "resize-panel": "Resize panel", "resize-sidebar": "Resize sidebar", "resources": "Resources", @@ -413,9 +412,11 @@ "resize-image": "Resize image" }, "attachments": { - "move-up": "Move attachment up", - "move-down": "Move attachment down", - "remove": "Remove attachment" + "edited": "Edited", + "new": "New", + "remove": "Remove attachment", + "reorder": "Reorder {{name}}", + "reorder-hint": "Drag, or use the arrow keys" }, "remove-relation": "Remove relation", "remove-location": "Remove location", diff --git a/web/src/locales/es.json b/web/src/locales/es.json index f2293683f..5a1ba478b 100644 --- a/web/src/locales/es.json +++ b/web/src/locales/es.json @@ -97,7 +97,6 @@ "profile": "Perfil", "referenced-by": "Referenciado por", "referencing": "Referenciando", - "relations": "Relaciones", "resources": "Recursos", "restore": "Restaurar", "role": "Rol", @@ -311,9 +310,11 @@ "resize-image": "Cambiar tamaño de la imagen" }, "attachments": { - "move-up": "Mover adjunto hacia arriba", - "move-down": "Mover adjunto hacia abajo", - "remove": "Quitar adjunto" + "edited": "Editado", + "new": "Nuevo", + "remove": "Quitar adjunto", + "reorder": "Reordenar {{name}}", + "reorder-hint": "Arrastra o usa las teclas de flecha" }, "remove-relation": "Quitar relación", "remove-location": "Quitar ubicación", diff --git a/web/src/locales/et.json b/web/src/locales/et.json index e849c82dc..201843b23 100644 --- a/web/src/locales/et.json +++ b/web/src/locales/et.json @@ -136,7 +136,6 @@ "profile": "Profiil", "referenced-by": "Viidatud", "referencing": "Viitamine", - "relations": "Suhted", "resources": "Vahendid", "restore": "Taasta", "role": "Roll", @@ -349,9 +348,11 @@ "resize-image": "Muuda pildi suurust" }, "attachments": { - "move-up": "Liiguta manus üles", - "move-down": "Liiguta manus alla", - "remove": "Eemalda manus" + "edited": "Muudetud", + "new": "Uus", + "remove": "Eemalda manus", + "reorder": "Muuda järjekorda: {{name}}", + "reorder-hint": "Lohista või kasuta nooleklahve" }, "remove-relation": "Eemalda seos", "remove-location": "Eemalda asukoht", diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index 2b515abc1..f82e5f88c 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -97,7 +97,6 @@ "profile": "مشخصات", "referenced-by": "ارجاع داده شده توسط", "referencing": "ارجاع دادن", - "relations": "روابط", "resources": "منابع", "restore": "بازیابی", "role": "نقش", @@ -311,9 +310,11 @@ "resize-image": "تغییر اندازه تصویر" }, "attachments": { - "move-up": "انتقال پیوست به بالا", - "move-down": "انتقال پیوست به پایین", - "remove": "حذف پیوست" + "edited": "ویرایش‌شده", + "new": "جدید", + "remove": "حذف پیوست", + "reorder": "جابه‌جایی {{name}}", + "reorder-hint": "بکشید یا از کلیدهای جهت‌نما استفاده کنید" }, "remove-relation": "حذف ارتباط", "remove-location": "حذف مکان", diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json index b868bff79..cc624d292 100644 --- a/web/src/locales/fi.json +++ b/web/src/locales/fi.json @@ -136,7 +136,6 @@ "profile": "Profiili", "referenced-by": "Viittannut", "referencing": "Viittaus", - "relations": "Suhteet", "resources": "Resurssit", "restore": "Palauttaa", "role": "Rooli", @@ -349,9 +348,11 @@ "resize-image": "Muuta kuvan kokoa" }, "attachments": { - "move-up": "Siirrä liitettä ylöspäin", - "move-down": "Siirrä liitettä alaspäin", - "remove": "Poista liite" + "edited": "Muokattu", + "new": "Uusi", + "remove": "Poista liite", + "reorder": "Siirrä {{name}}", + "reorder-hint": "Vedä tai käytä nuolinäppäimiä" }, "remove-relation": "Poista linkitys", "remove-location": "Poista sijainti", diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json index 390ef11f9..9354df603 100644 --- a/web/src/locales/fr.json +++ b/web/src/locales/fr.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Référencé par", "referencing": "Référence", - "relations": "Relations", "resources": "Ressources", "restore": "Restaurer", "role": "Rôle", @@ -311,9 +310,11 @@ "resize-image": "Redimensionner l'image" }, "attachments": { - "move-up": "Monter la pièce jointe", - "move-down": "Descendre la pièce jointe", - "remove": "Retirer la pièce jointe" + "edited": "Modifié", + "new": "Nouveau", + "remove": "Retirer la pièce jointe", + "reorder": "Réordonner {{name}}", + "reorder-hint": "Faites glisser, ou utilisez les touches fléchées" }, "remove-relation": "Retirer la relation", "remove-location": "Retirer l'emplacement", diff --git a/web/src/locales/gl.json b/web/src/locales/gl.json index 6e58ad101..1af5ffb2e 100644 --- a/web/src/locales/gl.json +++ b/web/src/locales/gl.json @@ -97,7 +97,6 @@ "profile": "Perfil", "referenced-by": "Referida por", "referencing": "Referindo", - "relations": "Relacións", "resources": "Recursos", "restore": "Recuperar", "role": "Rol", @@ -311,9 +310,11 @@ "resize-image": "Cambiar o tamaño da imaxe" }, "attachments": { - "move-up": "Mover o anexo cara arriba", - "move-down": "Mover o anexo cara abaixo", - "remove": "Quitar o anexo" + "edited": "Editado", + "new": "Novo", + "remove": "Quitar o anexo", + "reorder": "Reordenar {{name}}", + "reorder-hint": "Arrastra ou usa as teclas de frecha" }, "remove-relation": "Quitar a relación", "remove-location": "Quitar a localización", diff --git a/web/src/locales/he.json b/web/src/locales/he.json index 655a648e2..bedbfaed0 100644 --- a/web/src/locales/he.json +++ b/web/src/locales/he.json @@ -173,7 +173,6 @@ "profile": "פרופיל", "referenced-by": "מופנה אליו על ידי", "referencing": "מפנה אל", - "relations": "קשרים", "resize-sidebar": "שנה את גודל סרגל הצד", "resources": "משאבים", "restore": "שחזר", @@ -382,9 +381,11 @@ "resize-image": "שינוי גודל התמונה" }, "attachments": { - "move-up": "הזזת הקובץ המצורף למעלה", - "move-down": "הזזת הקובץ המצורף למטה", - "remove": "הסרת הקובץ המצורף" + "edited": "נערך", + "new": "חדש", + "remove": "הסרת הקובץ המצורף", + "reorder": "שינוי סדר: {{name}}", + "reorder-hint": "גררו, או השתמשו במקשי החיצים" }, "remove-relation": "הסרת הקישור", "remove-location": "הסרת המיקום", diff --git a/web/src/locales/hi.json b/web/src/locales/hi.json index f9097c907..aca27c4bf 100644 --- a/web/src/locales/hi.json +++ b/web/src/locales/hi.json @@ -97,7 +97,6 @@ "profile": "प्रोफ़ाइल", "referenced-by": "द्वारा संदर्भित", "referencing": "संदर्भित कर रहा है", - "relations": "संबंध", "resources": "संसाधन", "restore": "पुनर्स्थापित करें", "role": "भूमिका", @@ -311,9 +310,11 @@ "resize-image": "इमेज का आकार बदलें" }, "attachments": { - "move-up": "अटैचमेंट ऊपर ले जाएँ", - "move-down": "अटैचमेंट नीचे ले जाएँ", - "remove": "अटैचमेंट हटाएँ" + "edited": "संपादित", + "new": "नया", + "remove": "अटैचमेंट हटाएँ", + "reorder": "{{name}} का क्रम बदलें", + "reorder-hint": "खींचें, या तीर कुंजियों का उपयोग करें" }, "remove-relation": "संबंध हटाएँ", "remove-location": "स्थान हटाएँ", diff --git a/web/src/locales/hr.json b/web/src/locales/hr.json index 8d5c8a59d..83c531299 100644 --- a/web/src/locales/hr.json +++ b/web/src/locales/hr.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Referencirano od", "referencing": "Referencira", - "relations": "Odnosi", "resources": "Resursi", "restore": "Vrati", "role": "Uloga", @@ -311,9 +310,11 @@ "resize-image": "Promijeni veličinu slike" }, "attachments": { - "move-up": "Pomakni privitak gore", - "move-down": "Pomakni privitak dolje", - "remove": "Ukloni privitak" + "edited": "Uređeno", + "new": "Novo", + "remove": "Ukloni privitak", + "reorder": "Promijeni redoslijed: {{name}}", + "reorder-hint": "Povucite ili upotrijebite tipke sa strelicama" }, "remove-relation": "Ukloni poveznicu", "remove-location": "Ukloni lokaciju", diff --git a/web/src/locales/hu.json b/web/src/locales/hu.json index 0d6577bd1..0c0a75b9b 100644 --- a/web/src/locales/hu.json +++ b/web/src/locales/hu.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Hivatkozta", "referencing": "Hivatkozik", - "relations": "Kapcsolatok", "resources": "Állományok", "restore": "Helyreállítás", "role": "Jogosultság", @@ -311,9 +310,11 @@ "resize-image": "Kép átméretezése" }, "attachments": { - "move-up": "Melléklet mozgatása feljebb", - "move-down": "Melléklet mozgatása lejjebb", - "remove": "Melléklet eltávolítása" + "edited": "Szerkesztve", + "new": "Új", + "remove": "Melléklet eltávolítása", + "reorder": "{{name}} áthelyezése", + "reorder-hint": "Húzza, vagy használja a nyílbillentyűket" }, "remove-relation": "Kapcsolat eltávolítása", "remove-location": "Hely eltávolítása", diff --git a/web/src/locales/id.json b/web/src/locales/id.json index 37d0e8dc1..0e35ed3e3 100644 --- a/web/src/locales/id.json +++ b/web/src/locales/id.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Dirujuk oleh", "referencing": "Merujuk", - "relations": "Relasi", "resources": "Sumber Daya", "restore": "Pulihkan", "role": "Peran", @@ -311,9 +310,11 @@ "resize-image": "Ubah ukuran gambar" }, "attachments": { - "move-up": "Pindahkan lampiran ke atas", - "move-down": "Pindahkan lampiran ke bawah", - "remove": "Hapus lampiran" + "edited": "Diedit", + "new": "Baru", + "remove": "Hapus lampiran", + "reorder": "Ubah urutan {{name}}", + "reorder-hint": "Seret, atau gunakan tombol panah" }, "remove-relation": "Hapus relasi", "remove-location": "Hapus lokasi", diff --git a/web/src/locales/it.json b/web/src/locales/it.json index be3eb8e63..9688e6c91 100644 --- a/web/src/locales/it.json +++ b/web/src/locales/it.json @@ -97,7 +97,6 @@ "profile": "Profilo", "referenced-by": "Referenziato da", "referencing": "Referenzia", - "relations": "Relazioni", "resources": "Risorse", "restore": "Ripristina", "role": "Ruolo", @@ -311,9 +310,11 @@ "resize-image": "Ridimensiona immagine" }, "attachments": { - "move-up": "Sposta allegato in alto", - "move-down": "Sposta allegato in basso", - "remove": "Rimuovi allegato" + "edited": "Modificato", + "new": "Nuovo", + "remove": "Rimuovi allegato", + "reorder": "Riordina {{name}}", + "reorder-hint": "Trascina o usa i tasti freccia" }, "remove-relation": "Rimuovi collegamento", "remove-location": "Rimuovi posizione", diff --git a/web/src/locales/ja.json b/web/src/locales/ja.json index 89cec5fb6..b3f77b7d1 100644 --- a/web/src/locales/ja.json +++ b/web/src/locales/ja.json @@ -101,7 +101,6 @@ "profile": "プロフィール", "referenced-by": "参照元", "referencing": "参照先", - "relations": "関連", "resize-sidebar": "サイドバーの幅を変更", "resources": "リソース", "restore": "復元", @@ -311,9 +310,11 @@ "resize-image": "画像のサイズを変更" }, "attachments": { - "move-up": "添付ファイルを上へ移動", - "move-down": "添付ファイルを下へ移動", - "remove": "添付ファイルを削除" + "edited": "編集済み", + "new": "新規", + "remove": "添付ファイルを削除", + "reorder": "{{name}}を並べ替え", + "reorder-hint": "ドラッグするか、矢印キーを使います" }, "remove-relation": "関連を削除", "remove-location": "場所を削除", diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.json index ec3846531..20e464e16 100644 --- a/web/src/locales/ka-GE.json +++ b/web/src/locales/ka-GE.json @@ -97,7 +97,6 @@ "profile": "პროფილი", "referenced-by": "მიუთითებს", "referencing": "მითითება", - "relations": "კავშირები", "resources": "რესურსები", "restore": "აღდგენა", "role": "როლი", @@ -311,9 +310,11 @@ "resize-image": "სურათის ზომის შეცვლა" }, "attachments": { - "move-up": "დანართის ზემოთ გადატანა", - "move-down": "დანართის ქვემოთ გადატანა", - "remove": "დანართის წაშლა" + "edited": "შესწორებული", + "new": "ახალი", + "remove": "დანართის წაშლა", + "reorder": "{{name}}-ის გადაადგილება", + "reorder-hint": "გადაათრიეთ ან გამოიყენეთ ისრიანი ღილაკები" }, "remove-relation": "კავშირის წაშლა", "remove-location": "მდებარეობის წაშლა", diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json index fb9c0982e..553504846 100644 --- a/web/src/locales/ko.json +++ b/web/src/locales/ko.json @@ -97,7 +97,6 @@ "profile": "프로필", "referenced-by": "참조됨", "referencing": "참조중", - "relations": "관계", "resources": "리소스", "restore": "복원", "role": "역할", @@ -311,9 +310,11 @@ "resize-image": "이미지 크기 조절" }, "attachments": { - "move-up": "첨부파일 위로 이동", - "move-down": "첨부파일 아래로 이동", - "remove": "첨부파일 제거" + "edited": "편집됨", + "new": "새 항목", + "remove": "첨부파일 제거", + "reorder": "{{name}} 순서 변경", + "reorder-hint": "드래그하거나 화살표 키를 사용하세요" }, "remove-relation": "연결 제거", "remove-location": "위치 제거", diff --git a/web/src/locales/lt.json b/web/src/locales/lt.json index 5baa69ded..81b3007a0 100644 --- a/web/src/locales/lt.json +++ b/web/src/locales/lt.json @@ -136,7 +136,6 @@ "profile": "Profilis", "referenced-by": "Nurodyta", "referencing": "Nuoroda", - "relations": "Santykiai", "resources": "Ištekliai", "restore": "Atkurti", "role": "Vaidmuo", @@ -349,9 +348,11 @@ "resize-image": "Keisti paveikslėlio dydį" }, "attachments": { - "move-up": "Perkelti priedą aukštyn", - "move-down": "Perkelti priedą žemyn", - "remove": "Pašalinti priedą" + "edited": "Redaguotas", + "new": "Naujas", + "remove": "Pašalinti priedą", + "reorder": "Pertvarkyti {{name}}", + "reorder-hint": "Vilkite arba naudokite rodyklių klavišus" }, "remove-relation": "Pašalinti ryšį", "remove-location": "Pašalinti vietą", diff --git a/web/src/locales/lv.json b/web/src/locales/lv.json index 6e6e3d011..22d01d322 100644 --- a/web/src/locales/lv.json +++ b/web/src/locales/lv.json @@ -136,7 +136,6 @@ "profile": "Profils", "referenced-by": "Atsaucas", "referencing": "Atsauces", - "relations": "Attiecības", "resources": "Resursi", "restore": "Atjaunot", "role": "Loma", @@ -349,9 +348,11 @@ "resize-image": "Mainīt attēla izmēru" }, "attachments": { - "move-up": "Pārvietot pielikumu augšup", - "move-down": "Pārvietot pielikumu lejup", - "remove": "Noņemt pielikumu" + "edited": "Rediģēts", + "new": "Jauns", + "remove": "Noņemt pielikumu", + "reorder": "Pārkārtot {{name}}", + "reorder-hint": "Velciet vai izmantojiet bulttaustiņus" }, "remove-relation": "Noņemt saiti", "remove-location": "Noņemt atrašanās vietu", diff --git a/web/src/locales/mr.json b/web/src/locales/mr.json index c9f0bc2a1..65b003d9c 100644 --- a/web/src/locales/mr.json +++ b/web/src/locales/mr.json @@ -97,7 +97,6 @@ "profile": "प्रोफाइल", "referenced-by": "याने संदर्भित", "referencing": "संदर्भ देत आहे", - "relations": "संबंध", "resources": "संसाधने", "restore": "पुनर्संचयित करा", "role": "भूमिका", @@ -311,9 +310,11 @@ "resize-image": "प्रतिमेचा आकार बदला" }, "attachments": { - "move-up": "संलग्नक वर हलवा", - "move-down": "संलग्नक खाली हलवा", - "remove": "संलग्नक काढा" + "edited": "संपादित", + "new": "नवीन", + "remove": "संलग्नक काढा", + "reorder": "{{name}} चा क्रम बदला", + "reorder-hint": "ओढा, किंवा बाण कळा वापरा" }, "remove-relation": "संबंध काढा", "remove-location": "स्थान काढा", diff --git a/web/src/locales/nb.json b/web/src/locales/nb.json index 68b1463cd..977de8a17 100644 --- a/web/src/locales/nb.json +++ b/web/src/locales/nb.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Referert til av", "referencing": "Refererer til", - "relations": "Relasjon", "resources": "Ressurser", "restore": "Gjenopprett", "role": "Rolle", @@ -311,9 +310,11 @@ "resize-image": "Endre bildestørrelse" }, "attachments": { - "move-up": "Flytt vedlegg opp", - "move-down": "Flytt vedlegg ned", - "remove": "Fjern vedlegg" + "edited": "Redigert", + "new": "Ny", + "remove": "Fjern vedlegg", + "reorder": "Flytt {{name}}", + "reorder-hint": "Dra, eller bruk piltastene" }, "remove-relation": "Fjern kobling", "remove-location": "Fjern plassering", diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json index b5ef4eb3e..e0323d804 100644 --- a/web/src/locales/nl.json +++ b/web/src/locales/nl.json @@ -97,7 +97,6 @@ "profile": "Profiel", "referenced-by": "Gerefereerd door", "referencing": "Verwijst naar", - "relations": "Relaties", "resources": "Bronnen", "restore": "Terugzetten", "role": "Rol", @@ -311,9 +310,11 @@ "resize-image": "Afbeeldingsgrootte wijzigen" }, "attachments": { - "move-up": "Bijlage omhoog verplaatsen", - "move-down": "Bijlage omlaag verplaatsen", - "remove": "Bijlage verwijderen" + "edited": "Bewerkt", + "new": "Nieuw", + "remove": "Bijlage verwijderen", + "reorder": "{{name}} verplaatsen", + "reorder-hint": "Sleep, of gebruik de pijltjestoetsen" }, "remove-relation": "Koppeling verwijderen", "remove-location": "Locatie verwijderen", diff --git a/web/src/locales/nn.json b/web/src/locales/nn.json index bb4b101d8..d087f866e 100644 --- a/web/src/locales/nn.json +++ b/web/src/locales/nn.json @@ -177,7 +177,6 @@ "profile": "Profil", "referenced-by": "Vist til av", "referencing": "Viser til", - "relations": "Samband", "resize-panel": "Endre panelstorleik", "resize-sidebar": "Endre storleiken på sidestolpen", "resources": "Ressursar", @@ -387,9 +386,11 @@ "resize-image": "Endre biletstorleik" }, "attachments": { - "move-up": "Flytt vedlegget opp", - "move-down": "Flytt vedlegget ned", - "remove": "Fjern vedlegget" + "edited": "Redigert", + "new": "Ny", + "remove": "Fjern vedlegget", + "reorder": "Flytt {{name}}", + "reorder-hint": "Dra, eller bruk piltastane" }, "remove-relation": "Fjern koplinga", "remove-location": "Fjern staden", diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json index 1135acd4c..4873125cb 100644 --- a/web/src/locales/pl.json +++ b/web/src/locales/pl.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Wspomniane przez", "referencing": "Odwołuje się do", - "relations": "Relacje", "resources": "Zasoby", "restore": "Przywróć", "role": "Rola", @@ -311,9 +310,11 @@ "resize-image": "Zmień rozmiar obrazu" }, "attachments": { - "move-up": "Przenieś załącznik w górę", - "move-down": "Przenieś załącznik w dół", - "remove": "Usuń załącznik" + "edited": "Edytowany", + "new": "Nowy", + "remove": "Usuń załącznik", + "reorder": "Zmień kolejność: {{name}}", + "reorder-hint": "Przeciągnij lub użyj klawiszy strzałek" }, "remove-relation": "Usuń powiązanie", "remove-location": "Usuń lokalizację", diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.json index eafa728db..fe9a9d3bc 100644 --- a/web/src/locales/pt-BR.json +++ b/web/src/locales/pt-BR.json @@ -97,7 +97,6 @@ "profile": "Perfil", "referenced-by": "Referenciado por", "referencing": "Referenciando", - "relations": "Relações", "resources": "Recursos", "restore": "Restaurar", "role": "Cargo", @@ -311,9 +310,11 @@ "resize-image": "Redimensionar imagem" }, "attachments": { - "move-up": "Mover anexo para cima", - "move-down": "Mover anexo para baixo", - "remove": "Remover anexo" + "edited": "Editado", + "new": "Novo", + "remove": "Remover anexo", + "reorder": "Reordenar {{name}}", + "reorder-hint": "Arraste ou use as teclas de seta" }, "remove-relation": "Remover vínculo", "remove-location": "Remover local", diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.json index af9e22441..b4231a590 100644 --- a/web/src/locales/pt-PT.json +++ b/web/src/locales/pt-PT.json @@ -97,7 +97,6 @@ "profile": "Perfil", "referenced-by": "Referenciado por", "referencing": "A referenciar", - "relations": "Relações", "resources": "Recursos", "restore": "Restaurar", "role": "Função", @@ -311,9 +310,11 @@ "resize-image": "Redimensionar imagem" }, "attachments": { - "move-up": "Mover anexo para cima", - "move-down": "Mover anexo para baixo", - "remove": "Remover anexo" + "edited": "Editado", + "new": "Novo", + "remove": "Remover anexo", + "reorder": "Reordenar {{name}}", + "reorder-hint": "Arraste ou utilize as teclas de seta" }, "remove-relation": "Remover ligação", "remove-location": "Remover local", diff --git a/web/src/locales/ro.json b/web/src/locales/ro.json index 8ad0688d3..efcf18b51 100644 --- a/web/src/locales/ro.json +++ b/web/src/locales/ro.json @@ -136,7 +136,6 @@ "profile": "Profil", "referenced-by": "Referit de", "referencing": "Referire", - "relations": "Relaţii", "resources": "Resurse", "restore": "Restabili", "role": "Rol", @@ -349,9 +348,11 @@ "resize-image": "Redimensionează imaginea" }, "attachments": { - "move-up": "Mutați atașamentul în sus", - "move-down": "Mutați atașamentul în jos", - "remove": "Eliminați atașamentul" + "edited": "Editat", + "new": "Nou", + "remove": "Eliminați atașamentul", + "reorder": "Reordonează {{name}}", + "reorder-hint": "Trage sau folosește tastele săgeți" }, "remove-relation": "Eliminați legătura", "remove-location": "Eliminați locația", diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json index a6b87313b..0797a54b3 100644 --- a/web/src/locales/ru.json +++ b/web/src/locales/ru.json @@ -97,7 +97,6 @@ "profile": "Профиль", "referenced-by": "Упоминания", "referencing": "Связи", - "relations": "Карта связей", "resources": "Ресурсы", "restore": "Восстановить", "role": "Роль", @@ -311,9 +310,11 @@ "resize-image": "Изменить размер изображения" }, "attachments": { - "move-up": "Переместить вложение вверх", - "move-down": "Переместить вложение вниз", - "remove": "Удалить вложение" + "edited": "Изменено", + "new": "Новое", + "remove": "Удалить вложение", + "reorder": "Переместить {{name}}", + "reorder-hint": "Перетащите или используйте клавиши со стрелками" }, "remove-relation": "Удалить связь", "remove-location": "Удалить местоположение", diff --git a/web/src/locales/sk.json b/web/src/locales/sk.json index e9578748e..69d490f66 100644 --- a/web/src/locales/sk.json +++ b/web/src/locales/sk.json @@ -136,7 +136,6 @@ "profile": "Profil", "referenced-by": "Odkazuje", "referencing": "Odkazovanie", - "relations": "Vzťahy", "resources": "Zdroje", "restore": "Obnoviť", "role": "Role", @@ -349,9 +348,11 @@ "resize-image": "Zmeniť veľkosť obrázka" }, "attachments": { - "move-up": "Posunúť prílohu nahor", - "move-down": "Posunúť prílohu nadol", - "remove": "Odstrániť prílohu" + "edited": "Upravené", + "new": "Nové", + "remove": "Odstrániť prílohu", + "reorder": "Zmeniť poradie: {{name}}", + "reorder-hint": "Potiahnite alebo použite šípky" }, "remove-relation": "Odstrániť prepojenie", "remove-location": "Odstrániť polohu", diff --git a/web/src/locales/sl.json b/web/src/locales/sl.json index 47e5ee18b..42106d50a 100644 --- a/web/src/locales/sl.json +++ b/web/src/locales/sl.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Nanaša se na", "referencing": "Nanašanje", - "relations": "Relacije", "resources": "Viri", "restore": "Obnovi", "role": "Vloga", @@ -311,9 +310,11 @@ "resize-image": "Spremeni velikost slike" }, "attachments": { - "move-up": "Premakni prilogo gor", - "move-down": "Premakni prilogo dol", - "remove": "Odstrani prilogo" + "edited": "Urejeno", + "new": "Novo", + "remove": "Odstrani prilogo", + "reorder": "Prerazporedi {{name}}", + "reorder-hint": "Povlecite ali uporabite smerne tipke" }, "remove-relation": "Odstrani povezavo", "remove-location": "Odstrani lokacijo", diff --git a/web/src/locales/sr.json b/web/src/locales/sr.json index 9650438ed..a6ab39756 100644 --- a/web/src/locales/sr.json +++ b/web/src/locales/sr.json @@ -136,7 +136,6 @@ "profile": "Профиле", "referenced-by": "Референца од", "referencing": "Референца", - "relations": "Односи", "resources": "Ресурси", "restore": "Ресторе", "role": "Улога", @@ -349,9 +348,11 @@ "resize-image": "Промени величину слике" }, "attachments": { - "move-up": "Помери прилог нагоре", - "move-down": "Помери прилог надоле", - "remove": "Уклони прилог" + "edited": "Измењено", + "new": "Ново", + "remove": "Уклони прилог", + "reorder": "Промени редослед: {{name}}", + "reorder-hint": "Превуците или користите тастере са стрелицама" }, "remove-relation": "Уклони везу", "remove-location": "Уклони локацију", diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json index 6f13e804d..a363f73ea 100644 --- a/web/src/locales/sv.json +++ b/web/src/locales/sv.json @@ -97,7 +97,6 @@ "profile": "Profil", "referenced-by": "Refererad av", "referencing": "Refererar", - "relations": "Relationer", "resources": "Resurser", "restore": "Återställ", "role": "Roll", @@ -311,9 +310,11 @@ "resize-image": "Ändra bildstorlek" }, "attachments": { - "move-up": "Flytta bilaga uppåt", - "move-down": "Flytta bilaga nedåt", - "remove": "Ta bort bilaga" + "edited": "Redigerad", + "new": "Ny", + "remove": "Ta bort bilaga", + "reorder": "Flytta {{name}}", + "reorder-hint": "Dra, eller använd piltangenterna" }, "remove-relation": "Ta bort koppling", "remove-location": "Ta bort plats", diff --git a/web/src/locales/th.json b/web/src/locales/th.json index 37924a2b4..3da952dc1 100644 --- a/web/src/locales/th.json +++ b/web/src/locales/th.json @@ -97,7 +97,6 @@ "profile": "ข้อมูลส่วนตัว", "referenced-by": "อ้างอิงโดย", "referencing": "กำลังอ้างอิง", - "relations": "ความสัมพันธ์", "resources": "แหล่งข้อมูล", "restore": "คืนค่า", "role": "บทบาท", @@ -311,9 +310,11 @@ "resize-image": "ปรับขนาดรูปภาพ" }, "attachments": { - "move-up": "ย้ายไฟล์แนบขึ้น", - "move-down": "ย้ายไฟล์แนบลง", - "remove": "ลบไฟล์แนบ" + "edited": "แก้ไขแล้ว", + "new": "ใหม่", + "remove": "ลบไฟล์แนบ", + "reorder": "จัดลำดับ {{name}} ใหม่", + "reorder-hint": "ลาก หรือใช้ปุ่มลูกศร" }, "remove-relation": "ลบความสัมพันธ์", "remove-location": "ลบตำแหน่ง", diff --git a/web/src/locales/tr.json b/web/src/locales/tr.json index 8e82dc0e4..a39d460c5 100644 --- a/web/src/locales/tr.json +++ b/web/src/locales/tr.json @@ -134,7 +134,6 @@ "profile": "Profil", "referenced-by": "Referans Verilenler", "referencing": "Referans Verenler", - "relations": "İlişkiler", "resize-panel": "Paneli yeniden boyutlandır", "resize-sidebar": "Kenar çubuğunu yeniden boyutlandır", "resources": "Kaynaklar", @@ -342,9 +341,11 @@ "resize-image": "Görseli yeniden boyutlandır" }, "attachments": { - "move-up": "Eki yukarı taşı", - "move-down": "Eki aşağı taşı", - "remove": "Eki kaldır" + "edited": "Düzenlendi", + "new": "Yeni", + "remove": "Eki kaldır", + "reorder": "{{name}} sırasını değiştir", + "reorder-hint": "Sürükleyin veya ok tuşlarını kullanın" }, "remove-relation": "İlişkiyi kaldır", "remove-location": "Konumu kaldır", diff --git a/web/src/locales/uk.json b/web/src/locales/uk.json index 471255877..0f61bf7a0 100644 --- a/web/src/locales/uk.json +++ b/web/src/locales/uk.json @@ -97,7 +97,6 @@ "profile": "Профіль", "referenced-by": "Згадується в", "referencing": "Згадує", - "relations": "Зв'язки", "resources": "Ресурси", "restore": "Відновити", "role": "Роль", @@ -311,9 +310,11 @@ "resize-image": "Змінити розмір зображення" }, "attachments": { - "move-up": "Перемістити вкладення вгору", - "move-down": "Перемістити вкладення вниз", - "remove": "Вилучити вкладення" + "edited": "Змінено", + "new": "Нове", + "remove": "Вилучити вкладення", + "reorder": "Перемістити {{name}}", + "reorder-hint": "Перетягніть або скористайтеся клавішами зі стрілками" }, "remove-relation": "Вилучити зв’язок", "remove-location": "Вилучити місцезнаходження", diff --git a/web/src/locales/vi.json b/web/src/locales/vi.json index 8936e280a..a35f4195f 100644 --- a/web/src/locales/vi.json +++ b/web/src/locales/vi.json @@ -97,7 +97,6 @@ "profile": "Hồ sơ", "referenced-by": "Được tham chiếu bởi", "referencing": "Đang tham chiếu", - "relations": "Liên kết", "resources": "Tài nguyên", "restore": "Khôi phục", "role": "Vai trò", @@ -311,9 +310,11 @@ "resize-image": "Đổi kích thước hình ảnh" }, "attachments": { - "move-up": "Di chuyển tệp đính kèm lên", - "move-down": "Di chuyển tệp đính kèm xuống", - "remove": "Xóa tệp đính kèm" + "edited": "Đã sửa", + "new": "Mới", + "remove": "Xóa tệp đính kèm", + "reorder": "Sắp xếp lại {{name}}", + "reorder-hint": "Kéo, hoặc dùng các phím mũi tên" }, "remove-relation": "Xóa liên kết", "remove-location": "Xóa vị trí", diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json index 6a60768be..12e64c1c2 100644 --- a/web/src/locales/zh-Hans.json +++ b/web/src/locales/zh-Hans.json @@ -140,7 +140,6 @@ "profile": "个人资料", "referenced-by": "被引用", "referencing": "引用", - "relations": "关系图", "resize-panel": "调整面板宽度", "resources": "资源库", "restore": "恢复", @@ -347,9 +346,11 @@ "resize-image": "调整图片大小" }, "attachments": { - "move-up": "上移附件", - "move-down": "下移附件", - "remove": "移除附件" + "edited": "已编辑", + "new": "新", + "remove": "移除附件", + "reorder": "调整 {{name}} 的顺序", + "reorder-hint": "拖动,或使用方向键" }, "remove-relation": "移除关联", "remove-location": "移除位置", diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json index 353653691..55c342ed0 100644 --- a/web/src/locales/zh-Hant.json +++ b/web/src/locales/zh-Hant.json @@ -181,7 +181,6 @@ "profile": "個人檔案", "referenced-by": "被引用", "referencing": "引用", - "relations": "關聯", "resize-sidebar": "調整側邊欄寬度", "resources": "檔案", "restore": "還原", @@ -390,9 +389,11 @@ "resize-image": "調整圖片大小" }, "attachments": { - "move-up": "上移附件", - "move-down": "下移附件", - "remove": "移除附件" + "edited": "已編輯", + "new": "新", + "remove": "移除附件", + "reorder": "調整 {{name}} 的順序", + "reorder-hint": "拖曳,或使用方向鍵" }, "remove-relation": "移除關聯", "remove-location": "移除位置", diff --git a/web/tests/attachment-inline-placement.test.tsx b/web/tests/attachment-inline-placement.test.tsx index 59a5a8ce5..92f8ca7b0 100644 --- a/web/tests/attachment-inline-placement.test.tsx +++ b/web/tests/attachment-inline-placement.test.tsx @@ -46,31 +46,45 @@ describe("attachment inline placement actions", () => { }; const { rerender } = render(); - expect(screen.queryByText("Attachments")).not.toBeInTheDocument(); - expect(screen.queryByText("photo.png")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Preview photo.png" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Remove attachment" })).not.toBeInTheDocument(); rerender(); - expect(screen.getByText(/Attachments/)).toBeInTheDocument(); - expect(screen.getByText("photo.png")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Preview photo.png" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Remove attachment" })).toBeInTheDocument(); }); - it("preserves hidden inline attachments when visible attachments are reordered", () => { + it("keeps hidden inline attachments in the order when a visible one moves", () => { const second = create(AttachmentSchema, { ...image, name: "attachments/second", filename: "second.png" }); const third = create(AttachmentSchema, { ...image, name: "attachments/third", filename: "third.png" }); - const onAttachmentsChange = vi.fn(); + const onOrderChange = vi.fn(); render( , ); - fireEvent.click(screen.getAllByRole("button", { name: "Move attachment down" })[0]!); - expect(onAttachmentsChange).toHaveBeenCalledWith([image, third, second]); + // Alt + arrow moves a focused tile, so plain arrows still scroll. + fireEvent.keyDown(screen.getByRole("button", { name: "Preview second.png" }), { key: "ArrowRight", altKey: true }); + expect(onOrderChange).toHaveBeenCalledWith(["attachments/photo", "attachments/third", "attachments/second"]); + }); + + it("puts a new file before a saved one in one order", () => { + const second = create(AttachmentSchema, { ...image, name: "attachments/second", filename: "second.png" }); + const localImage = { + file: new File(["image"], "local.png", { type: "image/png" }), + previewUrl: "blob:local", + origin: "upload" as const, + }; + const onOrderChange = vi.fn(); + render(); + + fireEvent.keyDown(screen.getByRole("button", { name: "Preview local.png" }), { key: "ArrowLeft", altKey: true }); + expect(onOrderChange).toHaveBeenCalledWith(["attachments/photo", "blob:local", "attachments/second"]); }); it("does not offer inline placement for external images", () => { @@ -101,7 +115,7 @@ describe("attachment inline placement actions", () => { />, ); - expect(screen.getByText("Uploading to content")).toBeInTheDocument(); + expect(screen.getByRole("status", { name: "Uploading to content" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Insert image" })).toBeDisabled(); expect(screen.queryByRole("button", { name: "Remove attachment" })).not.toBeInTheDocument(); }); diff --git a/web/tests/attachment-order.test.ts b/web/tests/attachment-order.test.ts new file mode 100644 index 000000000..f543c8250 --- /dev/null +++ b/web/tests/attachment-order.test.ts @@ -0,0 +1,66 @@ +import { create } from "@bufbuild/protobuf"; +import { describe, expect, it } from "vitest"; +import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment"; +import { + effectiveOrder, + localFileOrderKey, + moveGroup, + orderAttachments, + renameUploadedKeys, + sortByOrder, +} from "@/components/MemoEditor/edit/utils/attachmentOrder"; +import { previewOrder } from "@/components/MemoMetadata/Attachment/useDragReorder"; +import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb"; + +const attachment = (name: string) => create(AttachmentSchema, { name: `attachments/${name}`, filename: `${name}.png` }); +const localFile = (previewUrl: string, replaces?: string): LocalFile => ({ + file: new File(["x"], `${previewUrl}.png`, { type: "image/png" }), + previewUrl, + replaces, +}); + +describe("attachment order", () => { + it("keeps unlisted items in their natural place after the ordered ones", () => { + expect(sortByOrder(["a", "b", "c", "d"], (key) => [key], ["c", "a"])).toEqual(["c", "a", "b", "d"]); + expect(sortByOrder(["a", "b"], (key) => [key], [])).toEqual(["a", "b"]); + }); + + it("moves an item to its target's place, down after it and up before it", () => { + expect(moveGroup([["a"], ["b"], ["c"]], 0, 2)).toEqual(["b", "c", "a"]); + expect(moveGroup([["a"], ["b"], ["c"]], 2, 0)).toEqual(["c", "a", "b"]); + // A Live Photo's two files move together. + expect(moveGroup([["a"], ["still", "video"], ["c"]], 1, 0)).toEqual(["still", "video", "a", "c"]); + }); + + it("gives an edited drawing the key of the attachment it replaces", () => { + expect(localFileOrderKey(localFile("blob:edit", "attachments/drawing"))).toBe("attachments/drawing"); + expect(localFileOrderKey(localFile("blob:new"))).toBe("blob:new"); + }); + + it("falls back to saved attachments then new files before the first reorder", () => { + expect(effectiveOrder([], [attachment("a")], [localFile("blob:n")])).toEqual(["attachments/a", "blob:n"]); + expect(effectiveOrder(["blob:n"], [attachment("a")], [localFile("blob:n")])).toEqual(["blob:n"]); + }); + + it("saves new files where the draft placed them among the saved ones", () => { + const saved = [attachment("a"), attachment("b")]; + const uploaded = attachment("new"); + const merged = [...saved, uploaded]; + const result = orderAttachments(merged, new Map([["blob:new", uploaded]]), ["attachments/a", "blob:new", "attachments/b"]); + expect(result.map((item) => item.name)).toEqual(["attachments/a", "attachments/new", "attachments/b"]); + }); + + it("renames uploaded files' keys so a retry keeps their place", () => { + expect(renameUploadedKeys(["attachments/a", "blob:new"], new Map([["blob:new", attachment("new")]]))).toEqual([ + "attachments/a", + "attachments/new", + ]); + }); + + it("shows the order a drag would drop into, and the committed order when idle", () => { + expect(previewOrder(["a", "b", "c"], 0, 2)).toEqual(["b", "c", "a"]); + expect(previewOrder(["a", "b", "c"], 2, 0)).toEqual(["c", "a", "b"]); + expect(previewOrder(["a", "b", "c"], null, null)).toEqual(["a", "b", "c"]); + expect(previewOrder(["a", "b", "c"], 1, 1)).toEqual(["a", "b", "c"]); + }); +}); diff --git a/web/tests/drawing-gallery.test.tsx b/web/tests/drawing-gallery.test.tsx index cc824027f..b9aeb3e9e 100644 --- a/web/tests/drawing-gallery.test.tsx +++ b/web/tests/drawing-gallery.test.tsx @@ -5,7 +5,6 @@ import { AttachmentGallery } from "@/components/MemoMetadata/Attachment/Attachme import { DRAWING_SHEET_MEDIA_CLASS, DRAWING_SHEET_SINGLE_CLASS, - DRAWING_SHEET_TILE_CLASS, VISUAL_TILE_BUTTON_CLASS, } from "@/components/MemoMetadata/Attachment/attachmentVisualClasses"; import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb"; @@ -15,15 +14,16 @@ const image = (name: string, filename: string) => create(AttachmentSchema, { nam const classesOf = (value: string) => value.split(" ").filter(Boolean); describe("drawings in the memo gallery", () => { - it("shows a drawing as a sheet of paper and a photo in its framed tile", () => { + it("frames a drawing in a collage like the photos beside it", () => { render( , ); + // One grid, one edge: the drawing keeps its paper but takes the photos' hairline frame. const drawing = screen.getByRole("button", { name: "drawing-20261106-101500.canvas.png" }); const photo = screen.getByRole("button", { name: "beach.png" }); - expect(drawing).toHaveClass(...classesOf(DRAWING_SHEET_TILE_CLASS)); - expect(drawing).not.toHaveClass("border"); + expect(drawing).toHaveClass(...classesOf(VISUAL_TILE_BUTTON_CLASS)); + expect(drawing).not.toHaveClass("shadow-mu-raised"); expect(photo).toHaveClass(...classesOf(VISUAL_TILE_BUTTON_CLASS)); }); diff --git a/web/tests/drawing.test.tsx b/web/tests/drawing.test.tsx index 55cce0dee..583601037 100644 --- a/web/tests/drawing.test.tsx +++ b/web/tests/drawing.test.tsx @@ -237,23 +237,27 @@ describe("drawing attachments", () => { ...toLocalFile(new File([fixturePng], "drawing-20261106-130000.canvas.png", { type: "image/png" })), replaces: drawingAttachment.name, }; - const onAttachmentsChange = vi.fn(); + const onOrderChange = vi.fn(); const photo = create(AttachmentSchema, { name: "attachments/photo", filename: "photo.png", type: "image/png" }); const map = create(AttachmentSchema, { name: "attachments/map", filename: "map.png", type: "image/png" }); render( , ); - expect(screen.queryByText(drawingAttachment.filename)).not.toBeInTheDocument(); - expect(screen.getByText("drawing-20261106-130000.canvas.png")).toBeInTheDocument(); - // Reordering the visible rows keeps the replaced drawing bound to the memo. - fireEvent.click(screen.getAllByRole("button", { name: "Move attachment down" })[0]); - expect(onAttachmentsChange).toHaveBeenLastCalledWith([drawingAttachment, map, photo]); + expect(screen.queryByRole("button", { name: `Preview ${drawingAttachment.filename}` })).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Preview drawing-20261106-130000.canvas.png" })).toBeInTheDocument(); + expect(screen.getByText("Edited")).toBeInTheDocument(); + // Moving the edit moves the saved drawing it stands in for: its key is the attachment's name. + fireEvent.keyDown(screen.getByRole("button", { name: "Preview drawing-20261106-130000.canvas.png" }), { + key: "ArrowRight", + altKey: true, + }); + expect(onOrderChange).toHaveBeenLastCalledWith([photo.name, drawingAttachment.name, map.name]); }); it("does not offer Insert image on a pending edit of a saved drawing", () => { diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx index 5b09994b6..606a37a9b 100644 --- a/web/tests/editor-controller.test.tsx +++ b/web/tests/editor-controller.test.tsx @@ -157,7 +157,7 @@ describe("upload anchors", () => { c.updateUploadAnchor(descriptor("upload-three", { status: "failed", message: "Retrying soon", onRetry: fresh })); expect(container.querySelector(".memo-upload-anchor")).toHaveTextContent("Retrying soon"); - container.querySelector(".memo-upload-anchor-action")?.click(); + container.querySelector(".memo-upload-anchor button")?.click(); expect(fresh).toHaveBeenCalledTimes(1); expect(stale).not.toHaveBeenCalled(); }); diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsx index 43751476c..7c7be2571 100644 --- a/web/tests/editor-suggestions.test.tsx +++ b/web/tests/editor-suggestions.test.tsx @@ -48,11 +48,12 @@ describe("editor suggestions", () => { expect(screen.queryByRole("group")).not.toBeInTheDocument(); }); - it("uses a payload-agnostic bar with dashed buttons", async () => { + it("uses a payload-agnostic bar of quiet pills", async () => { const onAccept = vi.fn(); render(); const chip = screen.getByRole("button", { name: "Example" }); - expect(chip).toHaveClass("border-dashed"); + expect(chip).not.toHaveClass("border-dashed"); + expect(chip).toHaveClass("bg-mu-hover/60"); fireEvent.click(chip); expect(onAccept).toHaveBeenCalledWith("future:example"); }); diff --git a/web/tests/memo-editor-paste-files.test.tsx b/web/tests/memo-editor-paste-files.test.tsx index 3509d4ed4..5c27937ef 100644 --- a/web/tests/memo-editor-paste-files.test.tsx +++ b/web/tests/memo-editor-paste-files.test.tsx @@ -67,8 +67,9 @@ describe("MemoEditor paste", () => { const event = paste(content, [pdf, image]); expect(event.defaultPrevented).toBe(true); - await waitFor(() => expect(container.textContent).toContain(image.name)); - expect(container.textContent).toContain(pdf.name); + // The image joins the gallery as a tile; the PDF is a row with its name. + await waitFor(() => expect(container.textContent).toContain(pdf.name)); + expect(container.querySelectorAll("[data-reorder-key] img")).toHaveLength(1); // A paste has no placement gesture: the image is attached rather than // inlined, so no inline upload starts and the text stays untouched. expect(content.textContent).toBe(""); diff --git a/web/tests/memo-editor-upload-retry.test.tsx b/web/tests/memo-editor-upload-retry.test.tsx index 8c4ca715c..b3ef4b89e 100644 --- a/web/tests/memo-editor-upload-retry.test.tsx +++ b/web/tests/memo-editor-upload-retry.test.tsx @@ -38,9 +38,16 @@ vi.mock("@/components/MemoEditor/edit/state", () => ({ setJustSaved: () => ({ type: "noop" }), setMetadata: (metadata: Partial) => ({ type: "set-metadata", metadata }), setLocalFiles: (localFiles: LocalFile[]) => ({ type: "set-local-files", localFiles }), + setAttachmentOrder: (attachmentOrder: string[]) => ({ type: "set-attachment-order", attachmentOrder }), setTimestamps: () => ({ type: "noop" }), }, - dispatch: (action: { type: string; metadata?: Partial; localFiles?: LocalFile[] }) => { + dispatch: (action: { + type: string; + metadata?: Partial; + localFiles?: LocalFile[]; + attachmentOrder?: string[]; + }) => { + if (action.type === "set-attachment-order") mocks.state = { ...mocks.state, attachmentOrder: action.attachmentOrder ?? [] }; if (action.type === "set-metadata") mocks.state = { ...mocks.state, metadata: { ...mocks.state.metadata, ...action.metadata } }; if (action.type === "set-local-files") mocks.state = { ...mocks.state, localFiles: action.localFiles ?? [] }; }, diff --git a/web/tests/type-roles.test.ts b/web/tests/type-roles.test.ts index bea37872b..406d10b54 100644 --- a/web/tests/type-roles.test.ts +++ b/web/tests/type-roles.test.ts @@ -59,9 +59,8 @@ describe("type roles", () => { // Sizes relative to memo text (inline code, tag pills, the welcome guide's memo specimen). "lib/markdownStyles.ts", "components/WelcomeGuide/headers.tsx", - // Drawn into images: the share card, and the type labels printed on small thumbnails. + // Drawn into images: the share card. "components/MemoActionMenu/MemoShareImagePreview.tsx", - "components/MemoMetadata/Attachment/AttachmentListEditor.tsx", "components/MemoPreview/MemoPreview.tsx", // The decorative status numeral on the error pages. "pages/NotFound.tsx",