feat(web): show attachments, links and place the same way in the composer and the memo

- The composer lays out attachments like the saved memo: pictures and
  videos in one gallery, audio and files as rows, then links and place,
  with no section headers. Editing a memo in place keeps that shape.
- Attachments can be reordered by dragging (long press on touch, the grip
  on rows) or with Alt+arrow keys. The dragged item lifts, the others
  slide aside around a placeholder, and Escape cancels.
- Saved attachments and new files share one order in the draft
  (attachmentOrder), kept through upload retries and applied on save.
  An edited drawing keeps the place of the drawing it replaces.
- Link rows show the linked memo's text and date; back-links show
  read-only while editing.
- Drawings in a collage get the photos' hairline frame.
- Composer polish: Markdown label beside the commit button, quieter
  suggestion pills, a compact recorder row, and kit buttons for upload
  anchors.
This commit is contained in:
johnnyjoygh
2026-11-10 22:02:40 +08:00
parent eb8a04111c
commit 038c1fef12
81 changed files with 1473 additions and 725 deletions
+7 -3
View File
@@ -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
@@ -347,8 +347,7 @@ export const EditSession: React.FC<EditSessionProps> = ({
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<EditSessionProps> = ({
!isFocusMode && className,
)}
>
{isSourceMode && (
<span
className={cn(
"pointer-events-none absolute end-0 top-0 rounded-es-mu-lg rounded-se-mu-lg border-s border-b border-mu-line/70 bg-mu-well/40 flex h-5 items-center px-1.5 select-none mu-label-xs font-mono text-mu-ink-muted",
isFocusMode && "border-mu-line",
)}
aria-label={t("editor.markdown-mode")}
>
Markdown
</span>
)}
{/* 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
@@ -130,6 +130,12 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
</div>
<div className="flex shrink-0 flex-row items-center justify-end gap-1">
{/* Markdown mode is said beside the commit button, where it never covers the text. */}
{sourceMode.isSourceMode && (
<span className="px-1.5 mu-label-xs font-mono text-mu-ink-muted select-none" aria-label={t("editor.markdown-mode")}>
Markdown
</span>
)}
{onCancel && (
<Button variant="ghost" onClick={onCancel} disabled={committing}>
{t("common.cancel")}
@@ -2,7 +2,6 @@ import { Button, Spinner, Tooltip } from "@usememos/ui";
import { AudioWaveformIcon, SquareIcon, XIcon } from "lucide-react";
import type { FC } from "react";
import { formatAudioTime } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { useAudioWaveform } from "../hooks/useAudioWaveform";
import type { AudioRecorderPanelProps } from "../types";
@@ -31,14 +30,14 @@ export const AudioRecorderPanel: FC<AudioRecorderPanelProps> = ({
: t("editor.audio-recorder.recording");
return (
<div
className={cn(
"flex w-full items-center justify-between gap-2 rounded-mu-lg border border-mu-line bg-mu-well/30 px-2.5 py-1.5",
"dark:bg-mu-well/20",
)}
>
// A 28px row on the text edge, like the toolbar under it: no box inside the composer's box.
<div className="mu-compact flex h-7 w-full items-center justify-between gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2">
{isRequestingPermission || isTranscribing ? <Spinner size="sm" aria-hidden className="shrink-0 text-mu-ink-muted" /> : null}
{isRequestingPermission || isTranscribing ? (
<Spinner size="sm" aria-hidden className="shrink-0 text-mu-ink-muted" />
) : (
<span aria-hidden className="size-2 shrink-0 rounded-full bg-mu-danger motion-safe:animate-pulse" />
)}
<span className="mu-visually-hidden">{srStatusText}</span>
<VoiceWaveform levels={waveformLevels} className="max-w-[200px] overflow-hidden" />
<span className="shrink-0 font-mono mu-caption tabular-nums text-mu-ink-muted">
@@ -46,7 +45,7 @@ export const AudioRecorderPanel: FC<AudioRecorderPanelProps> = ({
</span>
</div>
<div className="flex shrink-0 items-center gap-1 border-s border-mu-line/60 ps-2">
<div className="flex shrink-0 items-center gap-1">
<Tooltip.Root>
<Tooltip.Trigger
render={
@@ -1,6 +1,6 @@
import type { FC } from "react";
import { AttachmentListEditor, LocationDisplayEditor, RelationListEditor } from "@/components/MemoMetadata";
import { METADATA_ROW_LIST_CLASSES } from "@/components/MemoMetadata/MetadataSection";
import { getEditorBacklinkRelations, getEditorReferenceRelations } from "@/components/MemoMetadata/Relation/relationHelpers";
import { extractManagedAttachmentUIDs } from "@/utils/managed-attachment";
import { useEditorContext, useEditorSelector } from "../state";
import type { EditorMetadataProps } from "../types";
@@ -21,12 +21,30 @@ export const EditorMetadata: FC<EditorMetadataProps> = ({
const localFiles = useEditorSelector((s) => s.localFiles);
const relations = useEditorSelector((s) => s.metadata.relations);
const location = useEditorSelector((s) => s.metadata.location);
const attachmentOrder = useEditorSelector((s) => s.attachmentOrder);
const content = useEditorSelector((s) => s.content);
const placementActionsDisabled = useEditorSelector(
(s) => s.ui.isLoading.saving || s.ui.isLoading.uploading || s.ui.pendingInlineImageInsertions > 0,
);
const inlineAttachmentUIDs = extractManagedAttachmentUIDs(content);
const hasLinks =
getEditorReferenceRelations(relations, memoName).length > 0 || getEditorBacklinkRelations(relations, memoName).length > 0;
// Links and the place follow the attachments in the same list, so the draft reads as one quiet list under the gallery.
const trailingRows =
hasLinks || location ? (
<>
{hasLinks && (
<RelationListEditor
relations={relations}
onRelationsChange={(next) => dispatch(actions.setMetadata({ relations: next }))}
memoName={memoName}
/>
)}
{location && <LocationDisplayEditor location={location} onRemove={() => dispatch(actions.setMetadata({ location: undefined }))} />}
</>
) : undefined;
return (
<div className="w-full flex flex-col gap-2">
<AttachmentListEditor
@@ -35,6 +53,8 @@ export const EditorMetadata: FC<EditorMetadataProps> = ({
onAttachmentsChange={(next) => dispatch(actions.setMetadata({ attachments: next }))}
onLocalFilesChange={(next) => dispatch(actions.setLocalFiles(next))}
onRemoveLocalFile={(previewUrl) => dispatch(actions.removeLocalFile(previewUrl))}
order={attachmentOrder}
onOrderChange={(next) => dispatch(actions.setAttachmentOrder(next))}
inlineAttachmentUIDs={inlineAttachmentUIDs}
onInsertAttachments={onInsertAttachments}
onInsertLocalFiles={onInsertLocalFiles}
@@ -45,19 +65,9 @@ export const EditorMetadata: FC<EditorMetadataProps> = ({
transcriptionDisabled={transcriptionDisabled}
onEditDrawing={onEditDrawing}
openingDrawing={openingDrawing}
/>
<RelationListEditor
relations={relations}
onRelationsChange={(next) => dispatch(actions.setMetadata({ relations: next }))}
memoName={memoName}
/>
{location && (
<div className={METADATA_ROW_LIST_CLASSES}>
<LocationDisplayEditor location={location} onRemove={() => dispatch(actions.setMetadata({ location: undefined }))} />
</div>
)}
>
{trailingRows}
</AttachmentListEditor>
</div>
);
};
@@ -1,9 +1,7 @@
import { buttonClasses } from "@usememos/ui";
import { isEqual } from "lodash-es";
import { ListTodoIcon, ZapIcon } from "lucide-react";
import { ListTodoIcon, PlusIcon, ZapIcon } from "lucide-react";
import { type RefObject, useEffect, useId, useState } from "react";
import { MAX_MEMO_SUGGESTIONS, type MemoSuggestion, type SuggestionItem } from "@/lib/memo-suggestions";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { getAssignableVisibilityOptions, getVisibilityOption } from "@/utils/memo";
import { useEditorContext, useEditorSelector } from "../state";
@@ -24,7 +22,7 @@ export function SuggestionsBar({
if (!suggestions.length) return null;
return (
<div role="group" aria-labelledby={labelId} className="flex w-full items-start gap-2 mu-caption">
<span id={labelId} className="inline-flex h-6 shrink-0 items-center gap-1.5 text-mu-ink-muted/70">
<span id={labelId} className="inline-flex h-6 shrink-0 items-center gap-1.5 text-mu-ink-muted">
<ZapIcon className="mu-icon-sm" aria-hidden />
{t("editor.suggestions")}
</span>
@@ -35,13 +33,11 @@ export function SuggestionsBar({
type="button"
disabled={disabled}
aria-label={suggestion.accessibleLabel ?? suggestion.label}
className={cn(
buttonClasses({ variant: "ghost", size: "sm" }),
"h-6 max-w-full gap-1 border border-dashed border-mu-ink-muted/30 px-1.5 text-mu-ink-muted hover:border-mu-ink-muted/50 has-[>svg]:px-1.5",
)}
// A quiet pill until hovered, then the tag pill's own fill and ink, so it never reads as a tag already added.
className="inline-flex h-6 max-w-full items-center gap-1 rounded-mu-md bg-mu-hover/60 ps-1.5 pe-2 text-mu-ink-muted transition-colors hover:bg-mu-well hover:text-mu-ink disabled:cursor-not-allowed disabled:opacity-45 mu-focus"
onClick={() => onAccept(suggestion.id)}
>
{suggestion.icon && <suggestion.icon className="size-3" aria-hidden />}
{suggestion.icon ? <suggestion.icon className="mu-icon-xs" aria-hidden /> : <PlusIcon className="mu-icon-xs" aria-hidden />}
<span className="truncate">{suggestion.label}</span>
</button>
))}
+17 -42
View File
@@ -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
@@ -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 = {
@@ -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) {
@@ -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",
}),
@@ -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,
@@ -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: [],
};
@@ -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);
@@ -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 =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></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);
@@ -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<T>(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<string, Attachment>,
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, Attachment>): string[] {
return order.map((key) => uploaded.get(key)?.name ?? key);
}
File diff suppressed because it is too large Load Diff
@@ -104,7 +104,8 @@ const readPaperColor = (img: HTMLImageElement): string | undefined => {
/**
* 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 (
<div className={cn(DRAWING_SHEET_TILE_CLASS, className)} style={{ background: paper }} {...tileInteraction(onPreview)}>
<div
className={cn(framed ? VISUAL_TILE_BUTTON_CLASS : DRAWING_SHEET_TILE_CLASS, className)}
style={{ background: paper }}
{...tileInteraction(onPreview)}
>
<img
src={item.sourceUrl}
srcSet={`${item.sourceUrl} 2x`}
@@ -168,6 +175,7 @@ const CollageVisualItem = ({
mediaClassName={DRAWING_SHEET_CELL_MEDIA_CLASS}
onPreview={onPreview}
overlayLabel={overlayLabel}
framed
/>
);
}
@@ -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";
@@ -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<T>(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<HTMLDivElement>(null);
const ghostRef = useRef<HTMLDivElement>(null);
const pending = useRef<Pending | null>(null);
const suppressClick = useRef(false);
const settling = useRef(false);
const [dragging, setDragging] = useState<number | null>(null);
const [over, setOver] = useState<number | null>(null);
const [grab, setGrab] = useState<DragGrab | null>(null);
const draggingRef = useRef<number | null>(null);
const overRef = useRef<number | null>(null);
// Where each item stood before the shown order last changed, for the slide.
const snapshot = useRef<Map<string, DOMRect> | null>(null);
// Each place in the list, relative to the container, measured when the drag starts.
const slots = useRef<Slot[]>([]);
const itemsIn = () => Array.from(containerRef.current?.querySelectorAll<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>) => {
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<HTMLElement>) => {
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 };
}
@@ -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 };
};
@@ -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<RelationListEditorProps> = ({ 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 (
<MetadataSection title={t("common.relations")}>
<>
{referenceRelations.map((relation) => {
const relatedMemo = relation.relatedMemo!;
if (resolvedMemos[relatedMemo.name] === null) return null;
@@ -42,12 +47,35 @@ const RelationListEditor: FC<RelationListEditorProps> = ({ 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 (
<div key={memo.name} className={METADATA_ROW_BOX_CLASSES}>
<RelationRow memo={memo} parentPage={parentPage} variant="label" />
<MetadataRowRemoveControl label={t("editor.remove-relation")} onClick={() => handleDeleteRelation(memo.name)} />
<RelationRow
memo={memo}
parentPage={parentPage}
variant="label"
icon={LinkIcon}
trailing={<MetadataRowDetail parts={[dates[memo.name]]} />}
/>
{onRelationsChange && (
<MetadataRowRemoveControl label={t("editor.remove-relation")} onClick={() => handleDeleteRelation(memo.name)} />
)}
</div>
);
})}
</MetadataSection>
{backlinkRelations.map((relation) => {
const linkingMemo = relation.memo!;
if (resolvedMemos[linkingMemo.name] === null) return null;
const memo = resolvedMemos[linkingMemo.name] || linkingMemo;
return (
<RelationRow
key={memo.name}
memo={memo}
parentPage={parentPage}
icon={MilestoneIcon}
title={t("common.referenced-by")}
trailing={<MetadataRowDetail parts={[dates[memo.name]]} />}
/>
);
})}
</>
);
};
@@ -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 (
<Link
className={variant === "row" ? METADATA_ROW_CLASSES : METADATA_ROW_LABEL_CLASSES}
to={`/${memo.name}`}
title={title}
state={parentPage ? createMemoNavigationState(parentPage) : undefined}
viewTransition
>
@@ -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<RelationDirection, string> = {
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={<span className={METADATA_ROW_DETAIL_CLASSES}>{directionLabels[direction]}</span>}
title={directionLabels[direction]}
trailing={<MetadataRowDetail parts={[dates[memo.name]]} />}
/>
);
})}
@@ -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",
});
@@ -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<string, MemoRelation_MemoRef | null> = {};
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<string, string | undefined> = {};
queries.forEach((query, index) => {
if (query.data?.createTime) dates[names[index]] = formatRelationDate(timestampDate(query.data.createTime), i18n.language);
});
return dates;
};
+1 -1
View File
@@ -186,7 +186,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((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 && <MemoPinnedMark />}
<MemoHeader timeDisplay={timeDisplay} showCreator={showCreator} showVisibility={showVisibility} showSpace={showSpace} />
+5 -4
View File
@@ -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": "إزالة الموقع",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "Премахване на местоположението",
+5 -4
View File
@@ -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ó",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "Αφαίρεση τοποθεσίας",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "حذف مکان",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "הסרת המיקום",
+5 -4
View File
@@ -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": "स्थान हटाएँ",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "場所を削除",
+5 -4
View File
@@ -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": "მდებარეობის წაშლა",
+5 -4
View File
@@ -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": "위치 제거",
+5 -4
View File
@@ -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ą",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "स्थान काढा",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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ę",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "Удалить местоположение",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "Уклони локацију",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "ลบตำแหน่ง",
+5 -4
View File
@@ -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",
+5 -4
View File
@@ -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": "Вилучити місцезнаходження",
+5 -4
View File
@@ -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í",
+5 -4
View File
@@ -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": "移除位置",
+5 -4
View File
@@ -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": "移除位置",
+24 -10
View File
@@ -46,31 +46,45 @@ describe("attachment inline placement actions", () => {
};
const { rerender } = render(<AttachmentListEditor {...props} inlineAttachmentUIDs={new Set(["photo"])} />);
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(<AttachmentListEditor {...props} inlineAttachmentUIDs={new Set()} />);
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(
<AttachmentListEditor
attachments={[image, second, third]}
inlineAttachmentUIDs={new Set(["photo"])}
onAttachmentsChange={onAttachmentsChange}
onAttachmentsChange={vi.fn()}
onOrderChange={onOrderChange}
/>,
);
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(<AttachmentListEditor attachments={[image, second]} localFiles={[localImage]} onOrderChange={onOrderChange} />);
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();
});
+66
View File
@@ -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"]);
});
});
+4 -4
View File
@@ -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(
<AttachmentGallery visual={[image("d", "drawing-20261106-101500.canvas.png"), image("p", "beach.png")]} onImagePreview={vi.fn()} />,
);
// 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));
});
+11 -7
View File
@@ -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(
<AttachmentListEditor
attachments={[drawingAttachment, photo, map]}
localFiles={[edit]}
onAttachmentsChange={onAttachmentsChange}
onOrderChange={onOrderChange}
onEditDrawing={vi.fn()}
/>,
);
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", () => {
+1 -1
View File
@@ -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<HTMLButtonElement>(".memo-upload-anchor-action")?.click();
container.querySelector<HTMLButtonElement>(".memo-upload-anchor button")?.click();
expect(fresh).toHaveBeenCalledTimes(1);
expect(stale).not.toHaveBeenCalled();
});
+3 -2
View File
@@ -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(<SuggestionsBar suggestions={[{ id: "future:example", label: "Example" }]} disabled={false} onAccept={onAccept} />);
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");
});
+3 -2
View File
@@ -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("");
+8 -1
View File
@@ -38,9 +38,16 @@ vi.mock("@/components/MemoEditor/edit/state", () => ({
setJustSaved: () => ({ type: "noop" }),
setMetadata: (metadata: Partial<EditorState["metadata"]>) => ({ 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<EditorState["metadata"]>; localFiles?: LocalFile[] }) => {
dispatch: (action: {
type: string;
metadata?: Partial<EditorState["metadata"]>;
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 ?? [] };
},
+1 -2
View File
@@ -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",