mirror of
https://github.com/usememos/memos.git
synced 2026-11-19 10:29:11 +01:00
refactor(web): one memo component, MemoEditor, with view and edit modes (#6481)
This commit is contained in:
@@ -122,6 +122,7 @@ Black-box service tests live in `server/api/test/`, unit tests next to the code.
|
||||
- Use `@/` for absolute imports.
|
||||
- Follow Biome formatting: 2-space indent, double quotes, semicolons, 140-character line width.
|
||||
- Put server data in React Query hooks under `web/src/hooks/`; keep UI-only state in contexts or component state.
|
||||
- Show, edit and compose memos through `web/src/components/MemoEditor` (a name or draft seed plus a mode); see its `README.md`.
|
||||
- Use Tailwind CSS v4 utilities, `cn()` for class merging, and CVA for variants.
|
||||
- Reuse Base UI primitives and existing components before adding new UI primitives.
|
||||
- Keep generated proto TypeScript under `web/src/types/proto/` out of manual edits and Biome rewrites.
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@tanstack/react-query": "^5.100.9",
|
||||
"@tanstack/react-query-devtools": "^5.100.9",
|
||||
"@usememos/editor": "26.10.16",
|
||||
"@usememos/editor": "26.10.19",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"copy-to-clipboard": "^4.0.2",
|
||||
|
||||
Generated
+5
-5
@@ -36,8 +36,8 @@ importers:
|
||||
specifier: ^5.100.9
|
||||
version: 5.100.9(@tanstack/react-query@5.100.9(react@19.2.6))(react@19.2.6)
|
||||
'@usememos/editor':
|
||||
specifier: 26.10.16
|
||||
version: 26.10.16(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
|
||||
specifier: 26.10.19
|
||||
version: 26.10.19(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
@@ -1135,8 +1135,8 @@ packages:
|
||||
'@upsetjs/venn.js@2.0.0':
|
||||
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
|
||||
|
||||
'@usememos/editor@26.10.16':
|
||||
resolution: {integrity: sha512-o8C4gObGaKT1rV0z6zzigreQSpSjB/NQuGyicm+pUsICKyjyXPPH8OmDecW44X3l6pv157MsFxWm4IXafSblvw==}
|
||||
'@usememos/editor@26.10.19':
|
||||
resolution: {integrity: sha512-TgQkyVyC9Dpez/pZgm4hM8AFr9fKs429Xi/joMNNPSWkYlGLutJ1na57EkBdIiQpAhW2iYSgXcFc7W/g1PRC8w==}
|
||||
peerDependencies:
|
||||
react: '>=18'
|
||||
react-dom: '>=18'
|
||||
@@ -3262,7 +3262,7 @@ snapshots:
|
||||
d3-selection: 3.0.0
|
||||
d3-transition: 3.0.1(d3-selection@3.0.0)
|
||||
|
||||
'@usememos/editor@26.10.16(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
|
||||
'@usememos/editor@26.10.19(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
|
||||
optionalDependencies:
|
||||
react: 19.2.6
|
||||
react-dom: 19.2.6(react@19.2.6)
|
||||
|
||||
@@ -5,9 +5,9 @@ import {
|
||||
getActivityLevel,
|
||||
getTooltipText,
|
||||
} from "@/components/ActivityCalendar";
|
||||
import { useResolvedUser, useResolvedUsersByNames } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import UserAvatar from "@/components/UserAvatar";
|
||||
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
|
||||
import { useResolvedUser, useResolvedUsersByNames } from "@/contexts/MentionResolutionContext";
|
||||
import type { MemoTimeBasis } from "@/contexts/ViewContext";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/utils/deriveDefaultCreateTime";
|
||||
import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/edit/utils/deriveDefaultCreateTime";
|
||||
import { MEMO_PANEL_INSET, MEMO_PANEL_TITLE_CLASS, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList } from "@/components/MemoPanel";
|
||||
import MemoListError from "@/components/PagedMemoList/MemoListError";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useInstance } from "@/contexts/InstanceContext";
|
||||
import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
|
||||
import { useSpaceContext } from "@/contexts/SpaceContext";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
|
||||
@@ -125,9 +125,9 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {
|
||||
compose={
|
||||
canCompose
|
||||
? {
|
||||
cacheKey: `calendar-day-editor:${activeDate}`,
|
||||
scope: `calendar:${activeDate}`,
|
||||
label: t("calendar.new-memo-on-day"),
|
||||
defaults: { defaultCreateTime },
|
||||
defaults: { createTime: defaultCreateTime },
|
||||
onSavingChange: setSaving,
|
||||
}
|
||||
: undefined
|
||||
|
||||
@@ -305,9 +305,9 @@ export function MapView() {
|
||||
compose={
|
||||
composeLocation && user && (!creatorUsername || creatorUsername === user.username)
|
||||
? {
|
||||
cacheKey: `map-editor:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`,
|
||||
scope: `map:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`,
|
||||
label: t("map.new-here"),
|
||||
defaults: { defaultLocation: composeLocation },
|
||||
defaults: { location: composeLocation },
|
||||
onComposingChange: setComposing,
|
||||
onSavingChange: setSaving,
|
||||
onConfirm: (name) => void afterSave(name),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { forwardRef, useMemo } from "react";
|
||||
import MemoContent from "@/components/MemoContent";
|
||||
import { MemoContentView } from "@/components/MemoEditor/view/MemoContentView";
|
||||
import UserAvatar from "@/components/UserAvatar";
|
||||
import i18n from "@/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -39,7 +39,7 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
|
||||
|
||||
<div className="mt-4">
|
||||
<div className={cn("pointer-events-none", blurred && !showBlurredContent && "blur-lg")}>
|
||||
<MemoContent
|
||||
<MemoContentView
|
||||
content={memo.content}
|
||||
attachments={memo.attachments}
|
||||
compact={false}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { LoaderCircleIcon, MessageCircleIcon } from "lucide-react";
|
||||
import { type ComponentType, forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
|
||||
import { loadMemoEditor } from "@/components/MemoEditor/loader";
|
||||
import type { MemoEditorProps } from "@/components/MemoEditor/types";
|
||||
import { forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
|
||||
import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
|
||||
import MemoView from "@/components/MemoView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
@@ -31,8 +30,6 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
|
||||
const t = useTranslate();
|
||||
const currentUser = useCurrentUser();
|
||||
const [showEditor, setShowEditor] = useState(false);
|
||||
const [isEditorLoading, setIsEditorLoading] = useState(false);
|
||||
const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
|
||||
const sectionRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const canCreateComment = !!currentUser && memo.state === State.NORMAL;
|
||||
@@ -42,9 +39,8 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
|
||||
setShowEditor(false);
|
||||
};
|
||||
|
||||
const preloadEditor = useCallback(() => {
|
||||
void loadMemoEditor().catch(() => undefined);
|
||||
}, []);
|
||||
// The editing session's code loads while the pointer is still on the button.
|
||||
const preloadEditor = useCallback(() => preloadMemoEditing(), []);
|
||||
|
||||
const focusMountedEditor = useCallback(() => {
|
||||
const editorRoot = sectionRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
|
||||
@@ -53,25 +49,15 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
|
||||
}, []);
|
||||
|
||||
const openEditor = useCallback(async () => {
|
||||
if (!canCreateComment || isEditorLoading) {
|
||||
if (!canCreateComment) {
|
||||
return;
|
||||
}
|
||||
if (showEditor && EditorComponent) {
|
||||
if (showEditor) {
|
||||
focusMountedEditor();
|
||||
return;
|
||||
}
|
||||
|
||||
setIsEditorLoading(true);
|
||||
try {
|
||||
const { default: MemoEditor } = await loadMemoEditor();
|
||||
setEditorComponent(() => MemoEditor);
|
||||
setShowEditor(true);
|
||||
} catch {
|
||||
// Chunk failures are handled by loadWithReload; keep the current UI mounted.
|
||||
} finally {
|
||||
setIsEditorLoading(false);
|
||||
}
|
||||
}, [EditorComponent, canCreateComment, focusMountedEditor, isEditorLoading, showEditor]);
|
||||
setShowEditor(true);
|
||||
}, [canCreateComment, focusMountedEditor, showEditor]);
|
||||
|
||||
const scrollIntoView = useCallback(() => {
|
||||
sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
@@ -88,19 +74,9 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
|
||||
{comments.length === 0 ? (
|
||||
showCreateButton && (
|
||||
<div className="w-full flex flex-row justify-center items-center py-6">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onPointerEnter={preloadEditor}
|
||||
onFocus={preloadEditor}
|
||||
onClick={openEditor}
|
||||
disabled={isEditorLoading}
|
||||
>
|
||||
<Button variant="ghost" onPointerEnter={preloadEditor} onFocus={preloadEditor} onClick={openEditor}>
|
||||
<span className="text-muted-foreground">{t("memo.comment.write-a-comment")}</span>
|
||||
{isEditorLoading ? (
|
||||
<LoaderCircleIcon className="ml-2 h-5 w-5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />
|
||||
)}
|
||||
<MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
@@ -118,20 +94,17 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
|
||||
onPointerEnter={preloadEditor}
|
||||
onFocus={preloadEditor}
|
||||
onClick={openEditor}
|
||||
disabled={isEditorLoading}
|
||||
>
|
||||
{isEditorLoading && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}
|
||||
{t("memo.comment.write-a-comment")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{showEditor && EditorComponent && (
|
||||
{showEditor && (
|
||||
<div className="w-full mb-2">
|
||||
<EditorComponent
|
||||
cacheKey={`${memo.name}-comment`}
|
||||
<MemoEditor
|
||||
draft={{ parent: memo.name }}
|
||||
placeholder={t("editor.add-your-comment-here")}
|
||||
parentMemoName={memo.name}
|
||||
autoFocus
|
||||
onConfirm={handleCommentCreated}
|
||||
onCancel={() => setShowEditor(false)}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { type Block, type Editor, inlineText } from "@usememos/editor";
|
||||
|
||||
/** App UI mounted into the read-only editor's DOM with a portal. */
|
||||
export type Island = { key: string; target: HTMLElement; href: string };
|
||||
|
||||
let islandCounter = 0;
|
||||
/** Stable portal keys per target element, so a second pass does not remount mounted islands. */
|
||||
const islandKeys = new WeakMap<HTMLElement, string>();
|
||||
const islandKey = (target: HTMLElement): string => {
|
||||
let key = islandKeys.get(target);
|
||||
if (!key) {
|
||||
key = `island-${++islandCounter}`;
|
||||
islandKeys.set(target, key);
|
||||
}
|
||||
return key;
|
||||
};
|
||||
|
||||
/** The URL a paragraph consists of, when it is nothing but one bare web link: `https://…` written as its own text. */
|
||||
function bareLinkOf(block: Block): string | undefined {
|
||||
if (block.type !== "paragraph" || block.content.length === 0) return undefined;
|
||||
const href = block.content[0].link;
|
||||
// Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
|
||||
if (!href || !/^https?:\/\//i.test(href)) return undefined;
|
||||
// A titled link is a written `[text](url "title")`, never a bare URL; a card would drop its title.
|
||||
if (!block.content.every((span) => span.link === href && !span.linkTitle && !span.image)) return undefined;
|
||||
return inlineText(block.content) === href ? href : undefined;
|
||||
}
|
||||
|
||||
const blockElement = (root: HTMLElement, blockId: string) => root.querySelector<HTMLElement>(`[data-block-id="${CSS.escape(blockId)}"]`);
|
||||
|
||||
/**
|
||||
* The places in the read-only editor's DOM where memos' own UI takes over: a link card
|
||||
* in place of a paragraph that is one bare link, which needs the page's details from the
|
||||
* memos server. Everything else the view shows comes from the editor. Safe to run
|
||||
* repeatedly: targets keep their keys, and only new targets are prepared.
|
||||
*/
|
||||
export function findIslands(editor: Editor, root: HTMLElement, linkPreviewEnabled: boolean): Island[] {
|
||||
const islands: Island[] = [];
|
||||
for (const block of editor.state.doc.blocks) {
|
||||
const href = linkPreviewEnabled ? bareLinkOf(block) : undefined;
|
||||
const target = href ? blockElement(root, block.id) : null;
|
||||
if (!href || !target) continue;
|
||||
if (!target.hasAttribute("data-link-preview")) {
|
||||
target.setAttribute("data-link-preview", "");
|
||||
target.replaceChildren();
|
||||
}
|
||||
islands.push({ key: islandKey(target), target, href });
|
||||
}
|
||||
return islands;
|
||||
}
|
||||
|
||||
/** Whether two passes produced the same islands, so React can skip a render. */
|
||||
export const sameIslands = (a: readonly Island[], b: readonly Island[]): boolean =>
|
||||
a.length === b.length &&
|
||||
a.every((island, index) => island.key === b[index].key && island.target === b[index].target && island.href === b[index].href);
|
||||
@@ -1,198 +0,0 @@
|
||||
import type { Editor } from "@usememos/editor";
|
||||
import { MarkdownEditor } from "@usememos/editor/react";
|
||||
import "@usememos/editor/style.css";
|
||||
import { memo, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useContentSearchTerms } from "@/contexts/MemoFilterContext";
|
||||
import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
|
||||
import { useNearViewport } from "@/hooks/useNearViewport";
|
||||
import { markdownStyles } from "@/lib/markdownStyles";
|
||||
import {
|
||||
MEMO_EDITOR_THEME,
|
||||
MEMO_MARKDOWN,
|
||||
memoEditorLabels,
|
||||
memoExtensions,
|
||||
memoMentionOptions,
|
||||
memoResolveUrl,
|
||||
memoTagOptions,
|
||||
} from "@/lib/memo-markdown";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getCreatorHomePath } from "@/router/routes";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { findAnchorTarget } from "@/utils/markdown-manipulation";
|
||||
import { createMemoNavigationState } from "../MemoView/navigation";
|
||||
import { findIslands, type Island, sameIslands } from "./enhance";
|
||||
import { headingSlugs } from "./headings";
|
||||
import LinkMetadataCard from "./LinkMetadataCard";
|
||||
import { useResolvedMentionUsernames } from "./MentionResolutionContext";
|
||||
import type { MemoContentProps } from "./types";
|
||||
import { useSearchMatchHighlight } from "./useSearchMatchHighlight";
|
||||
import { useTagNavigation } from "./useTagNavigation";
|
||||
|
||||
// A memo with a Mermaid diagram draws it in the page's color scheme; the editor keeps drawn
|
||||
// diagrams, so a new scheme needs a new editor to draw them again.
|
||||
const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
|
||||
const subscribeColorScheme = (onChange: () => void) => {
|
||||
const observer = new MutationObserver(onChange);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
|
||||
return () => observer.disconnect();
|
||||
};
|
||||
const getColorScheme = () => document.documentElement.style.colorScheme;
|
||||
|
||||
const LinkPreview = ({ href }: { href: string }) => {
|
||||
const { ref, isNearViewport } = useNearViewport<HTMLAnchorElement>();
|
||||
const fallback = (
|
||||
<a ref={ref} href={href} target="_blank" rel="noopener noreferrer" className={markdownStyles.link}>
|
||||
{href}
|
||||
</a>
|
||||
);
|
||||
return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
|
||||
};
|
||||
|
||||
/**
|
||||
* A memo's content, shown by the same Markdown editor the composer uses, read-only. Owners
|
||||
* can tick task items: each tick reports the new Markdown, in which only that item's
|
||||
* `[ ]` or `[x]` changed. Truncation is not this component's concern — compact cards are
|
||||
* bounded by ClampedSection around the whole memo body; `compact` only tells in-memo
|
||||
* anchor links to open the detail page, since a collapsed card may hide their target.
|
||||
*/
|
||||
const MemoContent = (props: MemoContentProps) => {
|
||||
const { className, contentClassName, content, attachments, memoName, parentPage, compact, onTaskToggle, onClick, onDoubleClick } = props;
|
||||
const t = useTranslate();
|
||||
const navigate = useNavigate();
|
||||
const { userTagsSetting } = useAuth();
|
||||
const labels = useMemo(() => memoEditorLabels(t), [t]);
|
||||
const linkPreviewEnabled = useLinkPreviewEnabled();
|
||||
const resolvedMentionUsernames = useResolvedMentionUsernames(content);
|
||||
const navigateToTag = useTagNavigation(parentPage);
|
||||
// Whatever the page's search matched is painted here, without altering the rendered tree.
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
useSearchMatchHighlight(contentRef, useContentSearchTerms());
|
||||
const [editor, setEditor] = useState<Editor | null>(null);
|
||||
const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
|
||||
const editorKey = MERMAID_FENCE.test(content) ? colorScheme : undefined;
|
||||
const [islands, setIslands] = useState<Island[]>([]);
|
||||
|
||||
// Tag colors and resolved mentions come from outside the document: the decorations
|
||||
// read them here, and the editor decorates again when they change.
|
||||
const decorationState = useRef({ resolvedMentionUsernames, userTagsSetting });
|
||||
decorationState.current = { resolvedMentionUsernames, userTagsSetting };
|
||||
const extensions = useMemo(
|
||||
() =>
|
||||
memoExtensions({
|
||||
tags: memoTagOptions(() => decorationState.current.userTagsSetting),
|
||||
mentions: memoMentionOptions((username) => decorationState.current.resolvedMentionUsernames.has(username)),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
// Redecorate only when what the decorations read actually changed: a new editor already
|
||||
// decorates with the current values, and a resolution that comes back equal is a no-op.
|
||||
const mentionKey = [...resolvedMentionUsernames].sort().join(" ");
|
||||
const decorated = useRef({ mentionKey, userTagsSetting });
|
||||
useEffect(() => {
|
||||
const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
|
||||
decorated.current = { mentionKey, userTagsSetting };
|
||||
if (changed) editor?.redecorate();
|
||||
}, [editor, mentionKey, userTagsSetting]);
|
||||
|
||||
const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
|
||||
|
||||
// Mount memos' own UI after every render of the editor's blocks: on load, on a new
|
||||
// value, and when a ticked task item or new image URLs re-render blocks.
|
||||
useEffect(() => {
|
||||
if (!editor || editor.isDestroyed) return;
|
||||
const root = editor.root;
|
||||
let frame: number | null = null;
|
||||
const update = () => {
|
||||
frame = null;
|
||||
if (editor.isDestroyed) return;
|
||||
const next = findIslands(editor, root, linkPreviewEnabled);
|
||||
setIslands((previous) => (sameIslands(previous, next) ? previous : next));
|
||||
};
|
||||
update();
|
||||
const observer = new MutationObserver(() => {
|
||||
frame ??= requestAnimationFrame(update);
|
||||
});
|
||||
observer.observe(root, { childList: true });
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [editor, content, linkPreviewEnabled, resolveUrl]);
|
||||
|
||||
// In-memo anchors scroll within this memo; a collapsed card may hide the target, so it opens the detail page.
|
||||
const handleLinkClick = ({ href }: { href: string }) => {
|
||||
if (!href.startsWith("#")) return false;
|
||||
const id = decodeURIComponent(href.slice(1));
|
||||
const target = !compact && id && contentRef.current ? findAnchorTarget(contentRef.current, id) : null;
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
} else if (memoName) {
|
||||
navigate(`/${memoName}${href}`, { state: parentPage ? createMemoNavigationState(parentPage) : undefined });
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleClick = (event: React.MouseEvent) => {
|
||||
const target = event.target as HTMLElement;
|
||||
const tag = target.closest<HTMLElement>(".mbe-tag")?.dataset.tag;
|
||||
if (tag) {
|
||||
event.stopPropagation();
|
||||
navigateToTag(tag);
|
||||
return;
|
||||
}
|
||||
const mention = target.closest<HTMLElement>(".mbe-mention[data-resolved]")?.dataset.mention;
|
||||
if (mention) {
|
||||
event.stopPropagation();
|
||||
navigate(getCreatorHomePath(mention));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
|
||||
<div
|
||||
ref={contentRef}
|
||||
data-memo-content
|
||||
data-memo-name={memoName}
|
||||
className={cn(
|
||||
"relative w-full max-w-full wrap-break-word text-base leading-6",
|
||||
// Tags filter the list when clicked here; the composer shows them the same, without the click.
|
||||
"[&_.mbe-tag]:cursor-pointer [&_.mbe-tag]:transition-opacity [&_.mbe-tag:hover]:opacity-75",
|
||||
"[&_.mbe-mention[data-resolved]]:cursor-pointer [&_.mbe-mention[data-resolved]:hover]:underline",
|
||||
"[&_.katex-display]:max-w-full",
|
||||
"[&_.katex-display]:overflow-x-auto",
|
||||
"[&_.katex-display]:overflow-y-hidden",
|
||||
contentClassName,
|
||||
)}
|
||||
onClick={handleClick}
|
||||
onMouseUp={onClick}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
<MarkdownEditor
|
||||
key={editorKey}
|
||||
ref={setEditor}
|
||||
value={content}
|
||||
onChange={onTaskToggle}
|
||||
editable={false}
|
||||
taskToggle={Boolean(onTaskToggle)}
|
||||
toolbar={false}
|
||||
slashMenu={false}
|
||||
markdown={MEMO_MARKDOWN}
|
||||
extensions={extensions}
|
||||
theme={MEMO_EDITOR_THEME}
|
||||
labels={labels}
|
||||
resolveUrl={resolveUrl}
|
||||
referrerPolicy="no-referrer"
|
||||
headingIds={headingSlugs}
|
||||
onLinkClick={handleLinkClick}
|
||||
className="memo-content-root"
|
||||
/>
|
||||
{islands.map((island) => createPortal(<LinkPreview href={island.href} />, island.target, island.key))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(MemoContent);
|
||||
@@ -1,23 +0,0 @@
|
||||
import type React from "react";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
|
||||
export interface MemoContentProps {
|
||||
content: string;
|
||||
/** Attachments bound to this memo, used to resolve managed image URLs in share/S3 modes. */
|
||||
attachments?: Attachment[];
|
||||
/** Resource name of the memo (e.g. `memos/abc123`). Lets in-memo anchor links open the memo detail page. */
|
||||
memoName?: string;
|
||||
/** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
|
||||
parentPage?: string;
|
||||
/** The card renders collapsed (ClampedSection), so in-memo anchor links navigate instead of scrolling. */
|
||||
compact?: boolean;
|
||||
/**
|
||||
* Lets the viewer tick task items, for a memo they can manage. Called with the new
|
||||
* Markdown, in which only the ticked item's `[ ]` or `[x]` changed.
|
||||
*/
|
||||
onTaskToggle?: (content: string) => void;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
onDoubleClick?: (e: React.MouseEvent) => void;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import toast from "react-hot-toast";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_COUNT_RAIL_CLASSES, SidebarRowIconSlot } from "@/components/AppSidebar/SidebarRow";
|
||||
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "@/components/AppSidebar/SidebarSection";
|
||||
import { extractHeadings } from "@/components/MemoContent/headings";
|
||||
import { extractHeadings } from "@/components/MemoEditor/view/headings";
|
||||
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
|
||||
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
|
||||
import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { HeadingItem } from "@/components/MemoContent/headings";
|
||||
import type { HeadingItem } from "@/components/MemoEditor/view/headings";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { Suspense, useState } from "react";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import { useMemoByName, useUpdateMemo } from "@/hooks/useMemoQueries";
|
||||
import type { MemoSuggestion } from "@/lib/memo-suggestions";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Location } from "@/types/proto/api/memo_service_pb";
|
||||
import { lazyWithReload } from "@/utils/lazy";
|
||||
import { convertVisibilityFromString } from "@/utils/memo";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
import { draftKeyFor, type MemoEditIdentity, migrateLegacyDraft } from "./edit/draftKey";
|
||||
import { canChooseSpaceFor, initialEditorState } from "./edit/initialState";
|
||||
import { cacheService } from "./edit/services/cacheService";
|
||||
import { EditorProvider } from "./edit/state";
|
||||
import { MemoContentView } from "./view/MemoContentView";
|
||||
|
||||
// The editing session is the composer's chrome, uploads, audio and menus: loaded when a
|
||||
// memo is first edited or composed, so a page of memos does not carry it. Once loaded it
|
||||
// renders at once, with no suspense, so a host that preloaded it opens without a gap.
|
||||
type EditSessionComponent = typeof import("./edit/EditSession").EditSession;
|
||||
let loadedEditSession: EditSessionComponent | undefined;
|
||||
const loadEditSession = () =>
|
||||
import("./edit/EditSession").then((module) => {
|
||||
loadedEditSession = module.EditSession;
|
||||
return { default: module.EditSession };
|
||||
});
|
||||
const LazyEditSession = lazyWithReload(loadEditSession);
|
||||
|
||||
/** Loads the editing session's code ahead of time, for a host that is about to open an editor. */
|
||||
export const preloadMemoEditing = (): Promise<void> =>
|
||||
loadEditSession().then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
export interface MemoEditorViewProps {
|
||||
mode?: "view";
|
||||
/** The memo's resource name, such as `memos/abc`. */
|
||||
name: string;
|
||||
/** The card renders collapsed, so in-memo anchor links open the detail page instead of scrolling. */
|
||||
compact?: boolean;
|
||||
/** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
|
||||
parentPage?: string;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
onClick?: (event: React.MouseEvent) => void;
|
||||
onDoubleClick?: (event: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
/** What a new memo or comment starts from. */
|
||||
export interface MemoDraftSeed {
|
||||
/** The memo this draft comments on. A comment has no scope, Space or timestamps of its own. */
|
||||
parent?: string;
|
||||
/**
|
||||
* Where a new memo is composed, such as `home`, `global`, `calendar:<date>` or
|
||||
* `map:<key>`. Each scope keeps its own draft, per Space.
|
||||
*/
|
||||
scope?: string;
|
||||
/** Fixes the new memo's Space; the Space chooser is then off. */
|
||||
space?: string;
|
||||
/** Seeds the location once; a restored draft wins. */
|
||||
location?: Location;
|
||||
/**
|
||||
* Seeds `createTime` and `updateTime` and shows the timestamp popover. Followed live
|
||||
* while the draft is open, for a calendar whose selected day changes.
|
||||
*/
|
||||
createTime?: Date;
|
||||
}
|
||||
|
||||
export interface MemoEditingProps {
|
||||
/** A callback can decide whether focus is still appropriate after the draft is restored. */
|
||||
autoFocus?: boolean | (() => boolean);
|
||||
placeholder?: string;
|
||||
/** Context-derived suggestions for a new top-level memo. */
|
||||
suggestions?: readonly MemoSuggestion[];
|
||||
className?: string;
|
||||
/** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
|
||||
frameless?: boolean;
|
||||
/**
|
||||
* Marks the instance as hosted: a host (the global composer dialog) presents the
|
||||
* editor in the focus-mode layout and owns that frame. The editor mounts straight
|
||||
* into focus mode and exits by calling this to dismiss the host.
|
||||
*/
|
||||
onFocusModeExit?: () => void;
|
||||
/** Reports inline focus-mode changes, for a host whose layout must let the editor take the viewport. */
|
||||
onFocusModeChange?: (isFocusMode: boolean) => void;
|
||||
onConfirm?: (memoName: string) => void;
|
||||
/** Offers Cancel; without it the session has no way out but saving, as the Home composer. */
|
||||
onCancel?: () => void;
|
||||
/** Reports save activity so a host can keep itself open mid-transaction. */
|
||||
onSavingChange?: (isSaving: boolean) => void;
|
||||
}
|
||||
|
||||
/** Editing an existing memo by name. */
|
||||
export interface MemoEditorEditProps extends MemoEditingProps {
|
||||
mode: "edit";
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Composing a new memo or comment. */
|
||||
export interface MemoEditorDraftProps extends MemoEditingProps {
|
||||
mode?: "edit";
|
||||
draft: MemoDraftSeed;
|
||||
}
|
||||
|
||||
export type MemoEditorProps = MemoEditorViewProps | MemoEditorEditProps | MemoEditorDraftProps;
|
||||
|
||||
/**
|
||||
* A memo, shown or edited. In view mode it reads the memo by name from whatever query
|
||||
* already holds it (a list, a comment page, a detail) and shows it read-only; a viewer
|
||||
* who can manage the memo ticks its task items, and each tick is saved through the memo
|
||||
* mutation, so every copy of the memo on the page follows at once. In edit mode, for an
|
||||
* existing memo by name or a new memo from a draft seed, it owns the draft store,
|
||||
* initialized once from the memo or the persisted draft, and renders the editing
|
||||
* session over it. The parent owns the mode and hears back through `onConfirm` and
|
||||
* `onCancel`.
|
||||
*/
|
||||
export const MemoEditor = (props: MemoEditorProps) => {
|
||||
if ("draft" in props) return <MemoEditorDraft {...props} />;
|
||||
if (props.mode === "edit") return <MemoEditorEdit {...props} />;
|
||||
return <MemoEditorView {...props} />;
|
||||
};
|
||||
|
||||
const MemoEditorView = ({ name, compact, parentPage, className, contentClassName, onClick, onDoubleClick }: MemoEditorViewProps) => {
|
||||
const { data: memo } = useMemoByName(name);
|
||||
const currentUser = useCurrentUser();
|
||||
const { mutate: updateMemo } = useUpdateMemo();
|
||||
if (!memo) return null;
|
||||
|
||||
const handleTaskToggle = (content: string) => updateMemo({ update: { name, content }, updateMask: ["content", "update_time"] });
|
||||
|
||||
return (
|
||||
<MemoContentView
|
||||
memoName={name}
|
||||
content={memo.content}
|
||||
attachments={memo.attachments}
|
||||
parentPage={parentPage}
|
||||
compact={compact}
|
||||
onTaskToggle={canManageMemo(memo, currentUser) ? handleTaskToggle : undefined}
|
||||
className={className}
|
||||
contentClassName={contentClassName}
|
||||
onClick={onClick}
|
||||
onDoubleClick={onDoubleClick}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const MemoEditorEdit = ({ name, ...editing }: MemoEditorEditProps) => {
|
||||
const { data: memo } = useMemoByName(name);
|
||||
// The memo stays readable while the session's code loads, and until the memo itself has.
|
||||
const fallback = <MemoEditorView name={name} className={editing.className} />;
|
||||
if (!memo) return fallback;
|
||||
const identity: MemoEditIdentity = { kind: "edit", name };
|
||||
return (
|
||||
<Suspense fallback={fallback}>
|
||||
<EditingSession key={draftKeyFor(identity)} identity={identity} memo={memo} {...editing} />
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
const MemoEditorDraft = ({ draft, ...editing }: MemoEditorDraftProps) => {
|
||||
const identity: MemoEditIdentity = draft.parent
|
||||
? { kind: "comment", parent: draft.parent }
|
||||
: { kind: "new", scope: draft.scope ?? "default", space: draft.space };
|
||||
const fallback = editing.frameless ? null : (
|
||||
<div aria-hidden className={cn("w-full min-h-28 rounded-lg border border-border/70 bg-card", editing.className)} />
|
||||
);
|
||||
return (
|
||||
<Suspense fallback={fallback}>
|
||||
<EditingSession
|
||||
key={draftKeyFor(identity)}
|
||||
identity={identity}
|
||||
parentMemoName={draft.parent}
|
||||
defaultSpace={draft.space}
|
||||
defaultLocation={draft.location}
|
||||
defaultCreateTime={draft.createTime}
|
||||
{...editing}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
interface EditingSessionProps extends MemoEditingProps {
|
||||
identity: MemoEditIdentity;
|
||||
memo?: Parameters<typeof initialEditorState>[0]["memo"];
|
||||
parentMemoName?: string;
|
||||
defaultSpace?: string;
|
||||
defaultLocation?: Location;
|
||||
defaultCreateTime?: Date;
|
||||
}
|
||||
|
||||
/** One session over one identity: the draft store is created once, so a new identity is a new key. */
|
||||
const EditingSession = ({
|
||||
identity,
|
||||
memo,
|
||||
parentMemoName,
|
||||
defaultSpace,
|
||||
defaultLocation,
|
||||
defaultCreateTime,
|
||||
...editing
|
||||
}: EditingSessionProps) => {
|
||||
const currentUser = useCurrentUser();
|
||||
const { userGeneralSetting } = useAuth();
|
||||
const username = currentUser?.name ?? "";
|
||||
const draftKey = cacheService.key(username, draftKeyFor(identity));
|
||||
const [initialState] = useState(() => {
|
||||
migrateLegacyDraft(username, identity);
|
||||
return initialEditorState({
|
||||
memo,
|
||||
draftKey,
|
||||
// A hosted editor starts in focus mode and stays there.
|
||||
initialFocusMode: Boolean(editing.onFocusModeExit),
|
||||
defaultVisibility: userGeneralSetting?.memoVisibility ? convertVisibilityFromString(userGeneralSetting.memoVisibility) : undefined,
|
||||
defaultCreateTime,
|
||||
defaultLocation,
|
||||
canChooseSpace: canChooseSpaceFor({ memo, currentUser, parentMemoName, defaultSpace }),
|
||||
});
|
||||
});
|
||||
const EditSession = loadedEditSession ?? LazyEditSession;
|
||||
return (
|
||||
<EditorProvider initialEditorState={initialState}>
|
||||
<EditSession
|
||||
memo={memo}
|
||||
parentMemoName={parentMemoName}
|
||||
defaultSpace={defaultSpace}
|
||||
defaultCreateTime={defaultCreateTime}
|
||||
draftKey={draftKey}
|
||||
{...editing}
|
||||
/>
|
||||
</EditorProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { Editor, EditorMode, Extension } from "@usememos/editor";
|
||||
import { MarkdownEditor, type MarkdownEditorProps } from "@usememos/editor/react";
|
||||
import "@usememos/editor/style.css";
|
||||
import { type Ref, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoExtensions, memoResolveUrl } from "@/lib/memo-markdown";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { useMemoDecorations } from "./useMemoDecorations";
|
||||
|
||||
export interface MemoMarkdownProps {
|
||||
/** The Markdown. Applied only when it is not a value the editor emitted itself. */
|
||||
value: string;
|
||||
/** Editing, or the read-only memo view. Default read-only. Updates live. */
|
||||
editable?: boolean;
|
||||
/** While read-only, lets the viewer tick task items; each tick reports the new Markdown through `onChange`. */
|
||||
taskToggle?: boolean;
|
||||
onChange?: (markdown: string) => void;
|
||||
/** Mod+Enter or Ctrl+Enter while editing. */
|
||||
onSubmit?: () => void;
|
||||
/** Rich text, or the whole memo as Markdown text. Switching changes no text. */
|
||||
mode?: EditorMode;
|
||||
placeholder?: string;
|
||||
/** The memo's attachments, so images of managed attachments resolve to their served URL. */
|
||||
attachments?: readonly Attachment[];
|
||||
/** Extensions beyond the memo syntax, for editing. Keep the array's identity stable: a new set of names recreates the editor. */
|
||||
extensions?: readonly Extension[];
|
||||
/** The core editor instance. */
|
||||
editorRef?: Ref<Editor | null>;
|
||||
headingIds?: MarkdownEditorProps["headingIds"];
|
||||
onLinkClick?: MarkdownEditorProps["onLinkClick"];
|
||||
/** A tag was clicked to be followed (a plain click while read-only, Mod+click while editing), without its `#`. */
|
||||
onTagClick?: (tag: string) => void;
|
||||
/** A mention of someone who exists was clicked to be followed, without its `@`. */
|
||||
onMentionClick?: (username: string) => void;
|
||||
/** Attributes for the editable root, such as `spellcheck`. */
|
||||
attributes?: Record<string, string>;
|
||||
/** The formatting toolbar and the image toolbar. Read once; the editor hides them while read-only. */
|
||||
toolbar?: boolean;
|
||||
/** The slash menu's items, or `false` for none. Read once. */
|
||||
slashMenu?: MarkdownEditorProps["slashMenu"];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// A memo with a Mermaid diagram draws it in the page's color scheme; a new scheme draws
|
||||
// the diagrams again.
|
||||
const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
|
||||
const subscribeColorScheme = (onChange: () => void) => {
|
||||
const observer = new MutationObserver(onChange);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
|
||||
return () => observer.disconnect();
|
||||
};
|
||||
const getColorScheme = () => document.documentElement.style.colorScheme;
|
||||
|
||||
const assignRef = <T,>(ref: Ref<T> | undefined, value: T) => {
|
||||
if (typeof ref === "function") ref(value);
|
||||
else if (ref) ref.current = value;
|
||||
};
|
||||
|
||||
/**
|
||||
* A memo's Markdown in memos' dialect, look and policy, shown by the same editor whether
|
||||
* read-only or editing: the memo syntax extensions (math, footnotes, tags, mentions,
|
||||
* highlighted code, Mermaid, sanitized HTML), the theme in the app's CSS variables, the
|
||||
* translated labels, the image and link URL policy, and tags and mentions decorated from
|
||||
* the viewer's data. Everything a memo surface adds sits around this component.
|
||||
*/
|
||||
export const MemoMarkdown = (props: MemoMarkdownProps) => {
|
||||
const {
|
||||
value,
|
||||
editable = false,
|
||||
taskToggle,
|
||||
onChange,
|
||||
onSubmit,
|
||||
mode,
|
||||
placeholder,
|
||||
attachments,
|
||||
extensions,
|
||||
editorRef,
|
||||
headingIds,
|
||||
onLinkClick,
|
||||
onTagClick,
|
||||
onMentionClick,
|
||||
attributes,
|
||||
toolbar,
|
||||
slashMenu,
|
||||
className,
|
||||
} = props;
|
||||
const t = useTranslate();
|
||||
const [editor, setEditor] = useState<Editor | null>(null);
|
||||
const attach = useCallback(
|
||||
(instance: Editor | null) => {
|
||||
setEditor(instance);
|
||||
assignRef(editorRef, instance);
|
||||
},
|
||||
[editorRef],
|
||||
);
|
||||
|
||||
const decorations = useMemoDecorations(editor, value, editable, { onTagClick, onMentionClick });
|
||||
const baseExtensions = useMemo(() => memoExtensions({ tags: decorations.tags, mentions: decorations.mentions }), [decorations]);
|
||||
const allExtensions = useMemo(
|
||||
() => (extensions?.length ? [...baseExtensions, ...extensions] : baseExtensions),
|
||||
[baseExtensions, extensions],
|
||||
);
|
||||
const labels = useMemo(() => memoEditorLabels(t), [t]);
|
||||
const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
|
||||
const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
|
||||
const drawnScheme = useRef(colorScheme);
|
||||
useEffect(() => {
|
||||
if (drawnScheme.current === colorScheme) return;
|
||||
drawnScheme.current = colorScheme;
|
||||
if (MERMAID_FENCE.test(value)) editor?.refreshViews("code:mermaid");
|
||||
}, [colorScheme, editor, value]);
|
||||
|
||||
return (
|
||||
<MarkdownEditor
|
||||
ref={attach}
|
||||
value={value}
|
||||
// The React wrapper calls the latest callbacks, so inline functions are fine.
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit ? () => onSubmit() : undefined}
|
||||
editable={editable}
|
||||
taskToggle={taskToggle}
|
||||
mode={mode}
|
||||
placeholder={placeholder}
|
||||
markdown={MEMO_MARKDOWN}
|
||||
extensions={allExtensions}
|
||||
theme={MEMO_EDITOR_THEME}
|
||||
labels={labels}
|
||||
attributes={attributes}
|
||||
resolveUrl={resolveUrl}
|
||||
referrerPolicy="no-referrer"
|
||||
headingIds={headingIds}
|
||||
onLinkClick={onLinkClick}
|
||||
toolbar={toolbar}
|
||||
slashMenu={slashMenu}
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,170 +1,95 @@
|
||||
# MemoEditor Architecture
|
||||
# MemoEditor
|
||||
|
||||
## Overview
|
||||
|
||||
MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, built on [`@usememos/editor`](https://github.com/usememos/editor), a block editor whose storage format is standard Markdown. Markdown goes in and comes out: blocks the user did not edit are saved byte for byte, and edited blocks are written in a normalized style. The memo view (`components/MemoContent`) is the same editor, read-only, so a memo looks the same while editing and after saving. Everything above the editor boundary talks markdown through the `EditorController` contract.
|
||||
`MemoEditor` is the one way a memo is shown, edited or composed. It is memo-aware: it takes a memo's resource name, or a seed for a new memo or comment, and a mode. In view mode it reads the memo from whatever query already holds it and shows it read-only. In edit mode it owns a draft store and renders the editing session over it. The parent owns the mode and hears back through `onConfirm` and `onCancel`.
|
||||
|
||||
## Architecture
|
||||
Both modes show the memo through the same binding of [`@usememos/editor`](https://github.com/usememos/editor), a block editor whose storage format is standard Markdown, so a memo looks the same while editing and after saving. Blocks the user did not edit are saved byte for byte; edited blocks are written in a normalized style.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Presentation Layer (Components) │
|
||||
│ - EditorToolbar, EditorContent, etc. │
|
||||
└─────────────────┬───────────────────────┘
|
||||
│ EditorController
|
||||
┌─────────────────▼───────────────────────┐
|
||||
│ State Layer (reducer over an external │
|
||||
│ store; per-slice subscriptions) │
|
||||
│ - state/, useEditorContext(), │
|
||||
│ useEditorSelector() │
|
||||
│ - state.content ← markdown (the │
|
||||
│ single source of truth) │
|
||||
└─────────────────┬───────────────────────┘
|
||||
│
|
||||
┌─────────────────▼───────────────────────┐
|
||||
│ Service Layer (Business Logic) │
|
||||
│ - services/ (pure functions) │
|
||||
└─────────────────────────────────────────┘
|
||||
```tsx
|
||||
<MemoEditor name="memos/abc" /> // view; the owner can tick tasks
|
||||
<MemoEditor mode="edit" name="memos/abc" onConfirm onCancel /> // edit in place
|
||||
<MemoEditor draft={{ parent: "memos/abc" }} onConfirm onCancel /> // new comment
|
||||
<MemoEditor draft={{ scope: "home", space, createTime }} /> // new memo
|
||||
```
|
||||
|
||||
## Directory Structure
|
||||
## Layers
|
||||
|
||||
```
|
||||
MemoEditor/
|
||||
├── index.tsx # The shell: EditorProvider + MemoEditorImpl
|
||||
├── loader.ts # loadMemoEditor(): the shared lazy-load entry point
|
||||
├── state/ # State management (reducer, actions, context)
|
||||
├── services/ # Business logic (pure functions)
|
||||
├── components/ # UI components
|
||||
│ ├── EditorContent.tsx # Hosts Editor; forwards its EditorController ref
|
||||
│ ├── EditorMetadata.tsx # Attachment strip below the document
|
||||
│ └── ...
|
||||
├── hooks/ # React hooks (utilities)
|
||||
│ ├── useMemoSave.ts # Save transaction, cache invalidation, and reset
|
||||
│ ├── useSourceMode.ts # Rich or source mode, remembered per device
|
||||
│ └── useFocusMode.ts # Scroll lock and layout-stable focus presentation
|
||||
├── Editor/ # The composer, on @usememos/editor
|
||||
│ ├── index.tsx # React wrapper around <MarkdownEditor>; hands out the controller
|
||||
│ ├── extensions.ts # buildEditorExtensions(): memo syntax, #tag and :emoji autocomplete, file paste/drop
|
||||
│ ├── uploadAnchors.ts # Widget rendering for in-flight upload placeholders
|
||||
│ ├── controller.ts # EditorController over the editor
|
||||
│ └── editor.css # Composer sizing and upload-anchor styles
|
||||
├── Toolbar/ # EditorToolbar, InsertMenu, AudienceMenu
|
||||
├── constants.ts
|
||||
└── types/ # EditorController, component props,
|
||||
# attachment and insert-menu types
|
||||
MemoEditor memo level: name | draft seed, mode, data, draft store, mutations
|
||||
├── MemoContentView the read-only surface: navigation, anchors, link cards, search highlight
|
||||
│ └── MemoMarkdown the editor binding: dialect, theme, labels, URL policy, memo syntax, decorations
|
||||
└── EditSession the editing surface: chrome, uploads, audio, suggestions, save
|
||||
└── Editor MemoMarkdown editable, with the composer's extensions, behind EditorController
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid, sanitized HTML) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes.
|
||||
- **`view/`** is the read-only surface over `MemoMarkdown`: tags and mentions navigate, in-memo anchors scroll, a paragraph that is one bare link becomes a preview card through the editor's block view (`linkCards.ts`), the page's search matches are painted, and heading ids match the outline. Tag and mention clicks arrive through the editor's `onClick` callbacks, so nothing in memos matches the editor's class names or mutates its DOM. Previews that have Markdown but no memo query (the link-memo search, the share image) use `MemoContentView` directly.
|
||||
- **`edit/`** is the editing surface: `EditSession` renders the chrome (timestamp, attachments, suggestions, toolbar, focus mode, audio recording) over the draft store `MemoEditor` provides, persists the draft while open, and saves through the memo mutations. `Editor.tsx` is the composer's editor: `MemoMarkdown` editable with the composer's own extensions (`#tag` and `:emoji` autocomplete, file paste and drop), behind the `EditorController` contract in `controller.ts`.
|
||||
|
||||
### State Management
|
||||
## Data
|
||||
|
||||
A reducer (`state/reducer.ts`) drives an **external store**, not a `useReducer` in the provider, and consumers subscribe to just the slice they read via `useEditorSelector` (`useSyncExternalStore` under the hood). Content changes on every keystroke, so routing it through a single context value would re-render every consumer — toolbar, insert menu, metadata — per keystroke; with per-slice subscriptions only the components whose slice actually changed re-render. All state changes still go through action creators.
|
||||
- **Reads are by name.** `useMemoByName` (`hooks/useMemoQueries.ts`) returns the freshest copy of the memo any query holds (a list, a comment page, the calendar month, a detail, a shared memo) and fetches the detail only when nothing holds it. A card in a list therefore costs no request beyond the list's, follows the list's refetches, and never refetches on its own.
|
||||
- **Writes are mutations.** A ticked task, a save and a new memo go through `useUpdateMemo` and `useCreateMemo`, which patch and refresh every query holding the memo, so the saved text shows wherever the memo is on the page as soon as the server answers.
|
||||
- **The draft is UI state keyed by identity.** `edit/draftKey.ts` derives the key from what is edited: `edit:<name>`, `comment:<parent>`, `new:<scope>[:<space>]`. `initialEditorState` computes the store's first state once, from the memo or the persisted draft over the host's defaults; `useAutoSave` persists it while the session is open; an edit of an existing memo persists no draft. A new identity is a new session (`key`).
|
||||
|
||||
`state.content` holds the document as a **markdown string** and is the single source of truth. Because the editor stores markdown verbatim, `state.content` is exactly the editor's document — there is no encoding or normalization step.
|
||||
## The editing session
|
||||
|
||||
### 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.
|
||||
|
||||
### The editor contract
|
||||
|
||||
`types/editorController.ts` defines `EditorController` — document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), selection and focus (`focus`, `hasFocus`, `isEmpty`, `getSelection`, `setSelection`, `selectAll`), the upload-anchor group below, and `toggleTaskList`. Callers outside the editor implementation use this interface exclusively and never reach into the editor's own API.
|
||||
`edit/types/editorController.ts` defines `EditorController`: document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), selection and focus, the upload-anchor group, `getTags`, `hasChecklist`, `insertTag` and `toggleTaskList`. The chrome uses this interface and never reaches into the editor's own API. `edit/controller.ts` implements it over the live editor; calls before mount or after destroy do nothing.
|
||||
|
||||
`Editor/controller.ts` implements `EditorController` over the editor instance. Every method reads the live editor when called, so calls before mount or after destroy do nothing. `insertMarkdown` inserts after the caret's block (or in place of an empty paragraph) without consuming selected text. Selections are the editor's `SelectionJSON` (block index and offset), which survives remounting the same Markdown, so `cacheService` can restore the caret.
|
||||
### Formatting and source mode
|
||||
|
||||
`createUploadAnchor`/`updateUploadAnchor`/`resolveUploadAnchor`/`cancelUploadAnchor` drive editor widgets (`editor.addWidget`) that hold a place after a block while an attachment uploads and carry its progress, failure message, and retry/keep affordances. Widgets are never saved and are not part of undo history. `resolveUploadAnchor` inserts the finished markdown after the widget's block; resolving with empty markdown cancels instead, as does `cancelUploadAnchor`.
|
||||
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 and edits it as plain text; `useSourceMode` remembers the choice per device. In source mode the toolbar, slash menu, autocomplete and formatting keys are off, the checklist chip is hidden, and the controller reads tags and checklists from the text parsed as a memo.
|
||||
|
||||
### Formatting
|
||||
### Saving
|
||||
|
||||
Formatting is the editor's own: its toolbar appears over selected text (bold, italic, strikethrough, code, link), the slash menu and Markdown shortcuts change block types, and its keys cover the rest. Memos adds no formatting toolbar. The one formatting call memos makes itself is `toggleTaskList()`, for the checklist suggestion chip.
|
||||
|
||||
### Source mode
|
||||
|
||||
The editor's `mode` option shows the whole memo as Markdown text and edits it as plain text (see the editor README's "Source mode"). Every composer offers it, hosted ones included, because it changes how the text is edited, not the frame: the + menu has a "Source Mode" checkbox item, and while it is on, `EditorContent` puts a small "Source" tag in the editor's top-right corner, styled like a code block's language label, that says why autocomplete and formatting are gone and switches back. The editor's first line leaves room for the tag (a float sized by `--memo-source-tag-width` in `Editor/editor.css`), so the rest of the text keeps its full width. `useSourceMode` keeps the choice in localStorage (`memos-editor-mode`), so it is per device and every composer mounted afterwards opens in it. Switching changes no text, so saving, drafts and `state.content` are unaffected. In source mode:
|
||||
|
||||
- The editor's toolbar, slash menu, autocomplete and formatting keys are off, and the checklist suggestion chip is hidden because `toggleTaskList()` cannot apply.
|
||||
- The editor's document is one block of Markdown text, so the controller reads `getTags()` and `hasChecklist()` from the text parsed as a memo, not from its blocks. Insertions (`insertMarkdown`, `insertTag`, upload anchors) work as in rich mode.
|
||||
- A selection's shape depends on the mode, so `cacheService` stores the mode with a saved caret and does not restore a caret taken in the other mode.
|
||||
|
||||
### Editor extensions
|
||||
|
||||
`lib/memo-markdown.ts` holds what the composer and the memo view share: the memo Markdown dialect (`breaks: true`, `setext: false`, and the editor's defaults for GitHub alerts as callouts and `<details>` as collapsible sections); `memoExtensions()` (math rendered with KaTeX loaded on demand, footnotes, `#tags` and `@mentions`, code highlighted with highlight.js, ```` ```mermaid ```` diagrams, and raw HTML through the sanitizer in `lib/sanitized-html.ts`); the URL policy for links and images (`memoResolveUrl`); the theme in the app's CSS variables; the translated UI labels; and the tag and mention collectors. Whatever the editor renders shows its source at the caret while editing.
|
||||
|
||||
`Editor/extensions.ts` adds what only the composer needs: the `#tag` autocomplete (`suggestion()` with `matchToken(scanTags)`, so the popup opens exactly where tags are highlighted; not inside code or links, and not for a bare `#` at the start of a line, which may be a heading) with items from `useTagCounts`, `:emoji` autocomplete from `@usememos/editor/emoji` (its list loads the first time the popup opens), and a `fileHandler()`: pasted files join the attachment list, dropped images are inserted inline where they land and other dropped files are attached.
|
||||
|
||||
Keys are the editor's own (see its README): Mod+B/I/E, Mod+Shift+S, Mod+Alt+0–4, Mod+Alt+C, Mod+Shift+6 (collapsible section), Mod+Shift+7–9, Tab/Shift+Tab, and Mod+Enter / Ctrl+Enter to save. The first Escape selects the caret's block; a second Escape leaves the editor.
|
||||
|
||||
### Tags and mentions
|
||||
|
||||
Highlighting, autocomplete, `EditorController.getTags()` and the memo view all use the editor's scanners (`scanTags`, `scanMentions`), which skip code, links, images and extension tokens, so what is highlighted is what counts. `extractMentionUsernames` in `lib/memo-markdown.ts` reads mentions the same way to decide which users to resolve.
|
||||
|
||||
### Services
|
||||
|
||||
Pure TypeScript functions containing business logic. No React hooks, easy to test.
|
||||
`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.
|
||||
|
||||
### Suggestions
|
||||
|
||||
Hosts of a new top-level memo (Home, the global composer) pass `useMemoSuggestions()`
|
||||
into the `suggestions` prop; edits and comments omit the bar. `lib/memo-suggestions.ts`
|
||||
merges typed candidates from providers and keeps the strongest source per id
|
||||
(selection, then search, then the selected View). `lib/suggestion-expression.ts` is a
|
||||
small Boolean CEL reader shared by the providers; unsupported syntax never falls back
|
||||
to scanning free text.
|
||||
Hosts of a new top-level memo pass `useMemoSuggestions()` into `suggestions`; edits and comments show none. `EditorSuggestions` hides until the draft has text, drops suggestions already satisfied or accepted, and shows at most three. Acceptance history lives in the store so Undo does not immediately resuggest, and clears with the draft.
|
||||
|
||||
- Tags: explicit tag conditions and selected tags. `insertTag()` is one isolated undo
|
||||
step at the caret that keeps selected text and honors the current Markdown context.
|
||||
- Checklist: task-list conditions in saved Views or filters; a negative
|
||||
task-list or incomplete-task condition suppresses it.
|
||||
- Visibility: exactly one explicit audience across filters and View, otherwise nothing.
|
||||
Space visibility also requires actual Space placement.
|
||||
### Presentation: in a card, inline, hosted
|
||||
|
||||
`EditorSuggestions` hides until the draft has text, drops suggestions already satisfied
|
||||
(via the Markdown-aware `getTags()` / `hasChecklist()`, so code examples do not count)
|
||||
or already accepted, and shows at most three across kinds. Acceptance history lives in
|
||||
the editor store so Undo or reverting a choice does not immediately resuggest it, and it
|
||||
clears with the draft on reset; nothing is persisted with the memo. `SuggestionsBar` is
|
||||
payload-agnostic; a new kind extends the `MemoSuggestion` union and its
|
||||
eligibility/application in `EditorSuggestions`.
|
||||
- **In a card** (`frameless`): the card is the frame, so the session has no background, border or padding of its own outside focus mode. `MemoView` flips its body into the session by name and keeps its header, frame and reactions mounted.
|
||||
- **Inline** (Home, panels): the session brings its own frame. The + menu offers focus mode, which expands it over the page; the exit button minimizes it back.
|
||||
- **Hosted** (`onFocusModeExit`): a host presents the session full-screen and owns that frame (`contexts/GlobalMemoEditorContext.tsx`). It mounts straight into focus mode and exits by calling back to dismiss the host.
|
||||
|
||||
### Presentation: inline vs hosted
|
||||
|
||||
Every instance is one of two things, and `onFocusModeExit` is the switch:
|
||||
|
||||
- **Inline** (prop omitted) — the editor sits in page flow (Home composer, memo edit, comments) and owns its presentation. The + menu offers focus mode, which expands the editor over the page; the exit button in its top row minimizes it back in place.
|
||||
- **Hosted** (prop supplied) — a host presents the editor full-screen and owns that frame; `contexts/GlobalMemoEditorContext.tsx` is the one today. The editor mounts straight into focus mode and exits by calling back to dismiss the host, so the exit button reads as Close rather than minimize. The + menu's view toggle is absent: focus mode is not the editor's to leave.
|
||||
|
||||
The toggle travels as an optional `viewToggles` object (`types/components.ts`) down `EditorToolbar` → `InsertMenu`. The source-mode switch is not a view toggle and travels separately as `sourceMode` to `InsertMenu` and `EditorContent`, which every instance has.
|
||||
The session's code is a chunk of its own, loaded when a memo is first edited or composed, and renders without suspending once loaded; a host that knows an editor is coming calls `preloadMemoEditing()`.
|
||||
|
||||
### Destination and visibility
|
||||
|
||||
`AudienceMenu` is one dropdown for a memo's visibility and, where allowed, its Space. Visibility options come first; the Space is an optional row below them that never names the empty state: it reads "Add to space" until one is chosen, then shows the Space, and the selected Space in its submenu toggles back off (a check at rest, an ✕ under the pointer or keyboard, always an ✕ on touch). New top-level memos and edits of top-level memos the user can manage offer the row; a host-provided `defaultSpace` fixes a new memo's placement, and comments never offer it because their Space is the parent's. The destination lives in editor metadata: it is sent on creation, and an edit that changes it sends `space` and `visibility` together so the server can validate the move as one transition. Clearing a Space-only audience resets it to Private; adding a Space never changes the audience. Drafts retain destination and visibility alongside content, attachments, and location. Long names are truncated, with their full text retained for accessible labels and hover titles. Moving a memo between Spaces happens here; there is no separate move dialog.
|
||||
`AudienceMenu` is one dropdown for a memo's visibility and, where allowed, its Space. New top-level memos and edits of top-level memos the user can manage offer the Space row; a draft seed's `space` fixes a new memo's placement; comments never offer it because their Space is their parent's. An edit that changes the Space sends `space` and `visibility` together so the server validates the move as one transition.
|
||||
|
||||
### Lifecycle hooks
|
||||
## Directory structure
|
||||
|
||||
Cross-cutting React workflows stay outside the editor shell. `useMemoSave`
|
||||
coordinates validation, persistence, query invalidation, and post-save reducer
|
||||
state. `useFocusMode` owns focus mode's DOM lifecycle, including restoring the
|
||||
previous body scroll style and preserving the editor's place in grid layouts.
|
||||
|
||||
### Components
|
||||
|
||||
Thin presentation components that dispatch actions and render UI.
|
||||
|
||||
## Usage
|
||||
|
||||
```typescript
|
||||
import MemoEditor from "@/components/MemoEditor";
|
||||
|
||||
// Create mode: omit `memo`. Pass an existing Memo to edit it instead.
|
||||
<MemoEditor
|
||||
cacheKey="home-composer"
|
||||
onConfirm={(name) => console.log('Saved:', name)}
|
||||
onCancel={() => console.log('Cancelled')}
|
||||
/>
|
||||
```
|
||||
MemoEditor/
|
||||
├── index.ts # MemoEditor, preloadMemoEditing, prop types
|
||||
├── MemoEditor.tsx # The memo-level component: modes, data, draft store, lazy session
|
||||
├── MemoMarkdown.tsx # The editor binding
|
||||
├── useMemoDecorations.ts # Tag colors and resolved mentions, one redecorate
|
||||
├── view/ # Read-only surface: MemoContentView, linkCards, headings, navigation, search highlight
|
||||
└── edit/ # Editing surface
|
||||
├── EditSession.tsx # The chrome over the draft store
|
||||
├── Editor.tsx # MemoMarkdown editable + composer extensions + controller
|
||||
├── controller.ts, extensions.ts, uploadAnchors.ts, editor.css
|
||||
├── draftKey.ts # Identity → draft key, legacy migration
|
||||
├── initialState.ts # The store's first state, from the memo or the draft
|
||||
├── state/, services/, hooks/, components/, Toolbar/, types/, utils/
|
||||
└── constants.ts
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Services are pure functions — easy to unit test without React.
|
||||
|
||||
```typescript
|
||||
const state = createInitialState(); // from state/types.ts
|
||||
const result = await memoService.save(state, { memoName: 'memos/123' });
|
||||
```
|
||||
- `tests/memo-record.test.tsx`: reads by name, freshness, optimistic patches, the comment mutations.
|
||||
- `tests/memo-editor-view.test.tsx`: view mode by name, task ticking through the mutation.
|
||||
- `tests/memo-content-view.test.tsx`, `tests/editor.test.tsx`: the surfaces over the binding.
|
||||
- `tests/use-memo-init.test.tsx`, `tests/draft-key.test.ts`, `tests/use-auto-save.test.tsx`: drafts and keys.
|
||||
- `tests/use-memo-save.test.tsx`, `tests/memo-editor-*.test.ts*`: the session and its save path. Tests that mount the session call `await preloadMemoEditing()` first so it renders without suspending.
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { forwardRef, useLayoutEffect, useRef } from "react";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import Editor from "../Editor";
|
||||
import { useEditorContext, useEditorSelector } from "../state";
|
||||
import type { EditorContentProps } from "../types";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
// Imported eagerly (not React.lazy): the editor is the always-present compose
|
||||
// box on the home route, which is already code-split — so deferring the
|
||||
// editor bundle separately bought nothing and made the editor paint empty
|
||||
// for a beat before its placeholder appeared (a visible flicker on load).
|
||||
|
||||
/**
|
||||
* Hosts the Markdown Editor behind the EditorController contract. The
|
||||
* editor writes into state.content on every change.
|
||||
*/
|
||||
export const EditorContent = forwardRef<EditorController, EditorContentProps>(
|
||||
({ placeholder, sourceMode, onSubmit, onFiles, tagsSetting }, ref) => {
|
||||
const t = useTranslate();
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const sourceTagRef = useRef<HTMLButtonElement>(null);
|
||||
const isSourceMode = sourceMode.isSourceMode;
|
||||
const sourceLabel = t("editor.source");
|
||||
// The first line of the text leaves room for the tag; its width varies by language.
|
||||
useLayoutEffect(() => {
|
||||
const width = isSourceMode ? sourceTagRef.current?.offsetWidth : undefined;
|
||||
wrapperRef.current?.style.setProperty("--memo-source-tag-width", width ? `${width}px` : "0px");
|
||||
}, [isSourceMode, sourceLabel]);
|
||||
const { actions, dispatch } = useEditorContext();
|
||||
const content = useEditorSelector((s) => s.content);
|
||||
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
|
||||
const attachments = useEditorSelector((s) => s.metadata.attachments);
|
||||
|
||||
const handleContentChange = (content: string) => {
|
||||
dispatch(actions.updateContent(content));
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className="relative w-full flex flex-col flex-1">
|
||||
<Editor
|
||||
ref={ref}
|
||||
className="memo-editor-content"
|
||||
value={content}
|
||||
placeholder={placeholder || ""}
|
||||
isFocusMode={isFocusMode}
|
||||
mode={isSourceMode ? "source" : "rich"}
|
||||
attachments={attachments}
|
||||
tagsSetting={tagsSetting}
|
||||
onContentChange={handleContentChange}
|
||||
onFiles={onFiles}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
{/* Source mode names itself in the corner, as a code block names its language, and switches back from there.
|
||||
It fills on hover like the toolbar's quiet buttons, so it reads as a button once pointed at. */}
|
||||
{isSourceMode && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
ref={sourceTagRef}
|
||||
type="button"
|
||||
onClick={sourceMode.onToggle}
|
||||
className="absolute end-0 top-0.5 flex h-5 cursor-pointer items-center rounded px-1 text-2xs text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:bg-muted/60 focus-visible:text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{sourceLabel}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{t("editor.switch-to-rich-text")}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
EditorContent.displayName = "EditorContent";
|
||||
+27
-37
@@ -7,11 +7,11 @@ import { cn } from "@/lib/utils";
|
||||
import { InstanceSetting_Key } from "@/types/proto/api/instance_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { convertVisibilityFromString } from "@/utils/memo";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
|
||||
import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeExitButton, FocusModeOverlay, TimestampPopover } from "./components";
|
||||
import { EditorSuggestions } from "./components/EditorSuggestions";
|
||||
import { FOCUS_MODE_STYLES } from "./constants";
|
||||
import type { EditorFileOrigin } from "./Editor/extensions";
|
||||
import type { EditorFileOrigin } from "./extensions";
|
||||
import {
|
||||
splitInlineLocalFiles,
|
||||
toLocalFiles,
|
||||
@@ -25,29 +25,30 @@ import {
|
||||
useMemoSave,
|
||||
useSourceMode,
|
||||
} from "./hooks";
|
||||
import { canChooseSpaceFor } from "./initialState";
|
||||
import { cacheService, errorService, transcriptionService } from "./services";
|
||||
import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
|
||||
import { useEditorContext, useEditorSelector } from "./state";
|
||||
import { EditorToolbar } from "./Toolbar";
|
||||
import type { EditorViewToggles, MemoEditorProps } from "./types";
|
||||
import type { EditorViewToggles, EditSessionProps } from "./types";
|
||||
import type { LocalFile } from "./types/attachment";
|
||||
import type { EditorController, EditorPosition } from "./types/editorController";
|
||||
|
||||
// A host that presents the editor full-screen supplies `onFocusModeExit`; its
|
||||
// presence is what makes an instance hosted, so focus mode starts on and stays on.
|
||||
const MemoEditor = (props: MemoEditorProps) => (
|
||||
<EditorProvider initialFocusMode={Boolean(props.onFocusModeExit)}>
|
||||
<MemoEditorImpl {...props} />
|
||||
</EditorProvider>
|
||||
);
|
||||
|
||||
const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
/**
|
||||
* An editing session over the draft store MemoEditor provides: the editor with the
|
||||
* composer's chrome around it (timestamp, attachments, suggestions, toolbar, focus
|
||||
* mode, audio recording), the draft persisted while it is open, and the save that
|
||||
* writes the memo through the memo mutations. A host that presents the editor
|
||||
* full-screen supplies `onFocusModeExit`; its presence is what makes an instance
|
||||
* hosted, so focus mode starts on and stays on.
|
||||
*/
|
||||
export const EditSession: React.FC<EditSessionProps> = ({
|
||||
className,
|
||||
cacheKey,
|
||||
draftKey,
|
||||
frameless,
|
||||
memo,
|
||||
parentMemoName,
|
||||
suggestions = [],
|
||||
defaultSpace,
|
||||
defaultLocation,
|
||||
autoFocus,
|
||||
onFocusModeExit,
|
||||
onFocusModeChange,
|
||||
@@ -71,7 +72,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
}, [isFocusMode, onFocusModeChange]);
|
||||
const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
|
||||
const hasTimestamp = useEditorSelector((s) => Boolean(s.timestamps.createTime));
|
||||
const { userGeneralSetting, userTagsSetting } = useAuth();
|
||||
const { userGeneralSetting } = useAuth();
|
||||
const { aiSetting, fetchSetting } = useInstance();
|
||||
const [isAudioRecorderOpen, setIsAudioRecorderOpen] = useState(false);
|
||||
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false);
|
||||
@@ -85,7 +86,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
// An edited top-level memo can change its Space; a new one can unless its
|
||||
// host fixes the target (e.g. composing inside a Space).
|
||||
const draftSpace = useEditorSelector((s) => s.metadata.space);
|
||||
const canChooseSpace = memo ? !memo.parent && canManageMemo(memo, currentUser) : !parentMemoName && !defaultSpace;
|
||||
const canChooseSpace = canChooseSpaceFor({ memo, currentUser, parentMemoName, defaultSpace });
|
||||
const editorSpace = memo ? draftSpace : parentMemoName ? undefined : (defaultSpace ?? draftSpace);
|
||||
const canTranscribe = useMemo(() => {
|
||||
const providerId = aiSetting.transcription?.providerId ?? "";
|
||||
@@ -96,25 +97,14 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
|
||||
// Get default visibility from user settings
|
||||
const defaultVisibility = userGeneralSetting?.memoVisibility ? convertVisibilityFromString(userGeneralSetting.memoVisibility) : undefined;
|
||||
const editorCacheKey = cacheService.key(currentUser?.name ?? "", cacheKey);
|
||||
|
||||
// Source mode only changes how the text is edited, so every composer offers it.
|
||||
const [editorMode, setEditorMode] = useSourceMode();
|
||||
const isSourceMode = editorMode === "source";
|
||||
const sourceMode = { isSourceMode, onToggle: () => setEditorMode(isSourceMode ? "rich" : "source") };
|
||||
|
||||
const { isInitialized } = useMemoInit({
|
||||
editorRef,
|
||||
memo,
|
||||
cacheKey,
|
||||
username: currentUser?.name ?? "",
|
||||
autoFocus,
|
||||
defaultVisibility,
|
||||
defaultCreateTime,
|
||||
defaultLocation,
|
||||
canChooseSpace,
|
||||
mode: editorMode,
|
||||
});
|
||||
const { isInitialized } = useMemoInit({ editorRef, draftKey, autoFocus, mode: editorMode });
|
||||
// An edit starts from the memo and never persists a draft; only new memos and comments do.
|
||||
const isDraftCacheEnabled = !memo;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -122,7 +112,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
}, [isSaving, onSavingChange]);
|
||||
|
||||
// Auto-save content to localStorage (subscribes to the store internally).
|
||||
const { discardDraft } = useAutoSave(currentUser?.name ?? "", cacheKey, isInitialized && isDraftCacheEnabled);
|
||||
const { discardDraft } = useAutoSave(draftKey, isInitialized && isDraftCacheEnabled);
|
||||
|
||||
const { containerRef: editorContainerRef, placeholderHeight } = useFocusMode(isFocusMode);
|
||||
|
||||
@@ -231,9 +221,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
const rememberCursor = useCallback(() => {
|
||||
const cursor = editorRef.current?.getSelection();
|
||||
if (cursor !== undefined) {
|
||||
cacheService.saveCursor(editorCacheKey, cursor, editorMode);
|
||||
cacheService.saveCursor(draftKey, cursor, editorMode);
|
||||
}
|
||||
}, [editorCacheKey, editorMode]);
|
||||
}, [draftKey, editorMode]);
|
||||
|
||||
// Hosted: focus mode is the host's frame, so leaving it dismisses the host.
|
||||
// Inline: focus mode is a view this editor owns and toggles in place.
|
||||
@@ -351,7 +341,10 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
<div
|
||||
ref={editorContainerRef}
|
||||
className={cn(
|
||||
"group relative w-full flex flex-col justify-between items-start bg-card px-4 py-3 rounded-lg border border-border/70 gap-2",
|
||||
"group relative w-full flex flex-col justify-between items-start gap-2",
|
||||
// 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.
|
||||
(!frameless || isFocusMode) && "bg-card px-4 py-3 rounded-lg border border-border/70",
|
||||
FOCUS_MODE_STYLES.transition,
|
||||
isFocusMode && cn(FOCUS_MODE_STYLES.container.base, FOCUS_MODE_STYLES.container.spacing),
|
||||
!isFocusMode && className,
|
||||
@@ -379,7 +372,6 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
sourceMode={sourceMode}
|
||||
onSubmit={handleSave}
|
||||
onFiles={handleEditorFiles}
|
||||
tagsSetting={userTagsSetting}
|
||||
/>
|
||||
|
||||
{isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (
|
||||
@@ -425,5 +417,3 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MemoEditor;
|
||||
+11
-58
@@ -1,16 +1,12 @@
|
||||
import type { EditorMode, Editor as MarkdownEditorInstance } from "@usememos/editor";
|
||||
import { MarkdownEditor } from "@usememos/editor/react";
|
||||
import "@usememos/editor/style.css";
|
||||
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
import { useDebouncedEffect } from "@/hooks";
|
||||
import { useTagCounts, useUsersByUsernames } from "@/hooks/useUserQueries";
|
||||
import { extractMentionUsernames, MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoResolveUrl } from "@/lib/memo-markdown";
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import { useTagCounts } from "@/hooks/useUserQueries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
import { MemoMarkdown } from "../MemoMarkdown";
|
||||
import { createController } from "./controller";
|
||||
import type { EditorController } from "./types/editorController";
|
||||
import "./editor.css";
|
||||
import { buildEditorExtensions, type EditorFileOrigin } from "./extensions";
|
||||
|
||||
@@ -28,8 +24,6 @@ interface EditorProps {
|
||||
mode?: EditorMode;
|
||||
/** The draft's attachments, so images of managed attachments show. */
|
||||
attachments?: readonly Attachment[];
|
||||
/** The user's tag settings, for tags in their custom colors. */
|
||||
tagsSetting?: UserSetting_TagsSetting;
|
||||
}
|
||||
|
||||
const EDITOR_ATTRIBUTES = {
|
||||
@@ -41,55 +35,21 @@ const EDITOR_ATTRIBUTES = {
|
||||
spellcheck: "true",
|
||||
};
|
||||
|
||||
/** The composer's editor: MemoMarkdown, editable, with the composer's extensions, behind the EditorController contract. */
|
||||
const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef<EditorController>) {
|
||||
const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, mode, attachments, tagsSetting } = props;
|
||||
const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, mode, attachments } = props;
|
||||
const t = useTranslate();
|
||||
const editorRef = useRef<MarkdownEditorInstance | null>(null);
|
||||
const onContentChangeRef = useRef(onContentChange);
|
||||
onContentChangeRef.current = onContentChange;
|
||||
const onFilesRef = useRef(onFiles);
|
||||
onFilesRef.current = onFiles;
|
||||
const onSubmitRef = useRef(onSubmit);
|
||||
onSubmitRef.current = onSubmit;
|
||||
// A user can only author their own memos. Reuse the current-user stats query
|
||||
// instead of fetching and aggregating every user's tags for autocomplete.
|
||||
const { data: tagData } = useTagCounts(true);
|
||||
const tagsRef = useRef<string[]>([]);
|
||||
tagsRef.current = useMemo(() => Object.keys(tagData ?? {}), [tagData]);
|
||||
|
||||
const tagsSettingRef = useRef(tagsSetting);
|
||||
tagsSettingRef.current = tagsSetting;
|
||||
// Tag colors are drawn from the settings; draw them again when the settings change.
|
||||
const decoratedTagsSetting = useRef(tagsSetting);
|
||||
useEffect(() => {
|
||||
if (decoratedTagsSetting.current === tagsSetting) return;
|
||||
decoratedTagsSetting.current = tagsSetting;
|
||||
editorRef.current?.redecorate();
|
||||
}, [tagsSetting]);
|
||||
|
||||
// Mentions of people who exist are drawn as in the memo view. The names are looked up
|
||||
// once typing pauses, so a half-typed name is not; until a lookup answers, the people
|
||||
// already found stay found.
|
||||
const [mentionNames, setMentionNames] = useState<string[]>([]);
|
||||
useDebouncedEffect(
|
||||
() => {
|
||||
const next = extractMentionUsernames(value);
|
||||
setMentionNames((previous) => (previous.join("\n") === next.join("\n") ? previous : next));
|
||||
},
|
||||
400,
|
||||
[value],
|
||||
);
|
||||
const { data: mentionUsers } = useUsersByUsernames(mentionNames);
|
||||
const resolvedMentionsRef = useRef<ReadonlySet<string>>(new Set());
|
||||
useEffect(() => {
|
||||
if (!mentionUsers) return;
|
||||
const next = new Set([...mentionUsers].flatMap(([username, user]) => (user ? [username] : [])));
|
||||
const current = resolvedMentionsRef.current;
|
||||
if (next.size === current.size && [...next].every((username) => current.has(username))) return;
|
||||
resolvedMentionsRef.current = next;
|
||||
editorRef.current?.redecorate();
|
||||
}, [mentionUsers]);
|
||||
|
||||
const controller = useMemo(
|
||||
() =>
|
||||
createController(
|
||||
@@ -107,15 +67,11 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
|
||||
buildEditorExtensions({
|
||||
getTags: () => tagsRef.current,
|
||||
onFiles: (files, origin) => onFilesRef.current(files, origin),
|
||||
getTagsSetting: () => tagsSettingRef.current,
|
||||
isMentionResolved: (username) => resolvedMentionsRef.current.has(username),
|
||||
// Read once, like the rest: the popup keeps the language the composer opened in.
|
||||
emojiLabel: t("editor.blocks.emoji"),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
const labels = useMemo(() => memoEditorLabels(t), [t]);
|
||||
const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -124,20 +80,17 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
|
||||
data-source-mode={mode === "source" || undefined}
|
||||
>
|
||||
<div className={cn("memo-editor-scroller w-full text-base", isFocusMode && "min-h-0 flex-1")}>
|
||||
<MarkdownEditor
|
||||
ref={editorRef}
|
||||
<MemoMarkdown
|
||||
editorRef={editorRef}
|
||||
value={value}
|
||||
editable
|
||||
onChange={onContentChange}
|
||||
onSubmit={() => onSubmitRef.current()}
|
||||
onSubmit={onSubmit}
|
||||
placeholder={placeholder}
|
||||
mode={mode}
|
||||
markdown={MEMO_MARKDOWN}
|
||||
attachments={attachments}
|
||||
extensions={extensions}
|
||||
theme={MEMO_EDITOR_THEME}
|
||||
labels={labels}
|
||||
attributes={EDITOR_ATTRIBUTES}
|
||||
resolveUrl={resolveUrl}
|
||||
referrerPolicy="no-referrer"
|
||||
className="memo-editor-root"
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,74 @@
|
||||
import { forwardRef, useLayoutEffect, useRef } from "react";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import Editor from "../Editor";
|
||||
import { useEditorContext, useEditorSelector } from "../state";
|
||||
import type { EditorContentProps } from "../types";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
// The editor itself is imported eagerly: the memo view needs it on every page, so
|
||||
// splitting it would only make the composer paint empty for a beat. The session
|
||||
// around it is what loads lazily (see MemoEditor.tsx).
|
||||
|
||||
/**
|
||||
* Hosts the Markdown Editor behind the EditorController contract. The
|
||||
* editor writes into state.content on every change.
|
||||
*/
|
||||
export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, sourceMode, onSubmit, onFiles }, ref) => {
|
||||
const t = useTranslate();
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const sourceTagRef = useRef<HTMLButtonElement>(null);
|
||||
const isSourceMode = sourceMode.isSourceMode;
|
||||
const sourceLabel = t("editor.source");
|
||||
// The first line of the text leaves room for the tag; its width varies by language.
|
||||
useLayoutEffect(() => {
|
||||
const width = isSourceMode ? sourceTagRef.current?.offsetWidth : undefined;
|
||||
wrapperRef.current?.style.setProperty("--memo-source-tag-width", width ? `${width}px` : "0px");
|
||||
}, [isSourceMode, sourceLabel]);
|
||||
const { actions, dispatch } = useEditorContext();
|
||||
const content = useEditorSelector((s) => s.content);
|
||||
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
|
||||
const attachments = useEditorSelector((s) => s.metadata.attachments);
|
||||
|
||||
const handleContentChange = (content: string) => {
|
||||
dispatch(actions.updateContent(content));
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className="relative w-full flex flex-col flex-1">
|
||||
<Editor
|
||||
ref={ref}
|
||||
className="memo-editor-content"
|
||||
value={content}
|
||||
placeholder={placeholder || ""}
|
||||
isFocusMode={isFocusMode}
|
||||
mode={isSourceMode ? "source" : "rich"}
|
||||
attachments={attachments}
|
||||
onContentChange={handleContentChange}
|
||||
onFiles={onFiles}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
{/* Source mode names itself in the corner, as a code block names its language, and switches back from there.
|
||||
It fills on hover like the toolbar's quiet buttons, so it reads as a button once pointed at. */}
|
||||
{isSourceMode && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
ref={sourceTagRef}
|
||||
type="button"
|
||||
onClick={sourceMode.onToggle}
|
||||
className="absolute end-0 top-0.5 flex h-5 cursor-pointer items-center rounded px-1 text-2xs text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:bg-muted/60 focus-visible:text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{sourceLabel}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{t("editor.switch-to-rich-text")}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
EditorContent.displayName = "EditorContent";
|
||||
+13
-45
@@ -1,7 +1,7 @@
|
||||
import { type Block, containerContent, type Editor, getBlock, inlineText, type Position, type Widget } from "@usememos/editor";
|
||||
import { type Block, type Editor, inlineText, type Widget } from "@usememos/editor";
|
||||
import { collectTags, parseMemoMarkdown } from "@/lib/memo-markdown";
|
||||
import { isCompleteTagValue } from "@/utils/tag-grammar";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
import type { EditorController } from "./types/editorController";
|
||||
import { renderUploadAnchor } from "./uploadAnchors";
|
||||
|
||||
/** The live editor, or null before it mounts and after it is destroyed. */
|
||||
@@ -12,12 +12,6 @@ const live = (getEditor: EditorGetter): Editor | null => {
|
||||
return editor && !editor.isDestroyed ? editor : null;
|
||||
};
|
||||
|
||||
/** The text of the block (or table cell) holding `position`. */
|
||||
const textAt = (editor: Editor, position: Position): string => {
|
||||
const content = containerContent(getBlock(editor.state.doc, position.blockId), position.cell);
|
||||
return content ? inlineText(content) : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* The memo's blocks. Source mode holds the whole memo as one block of Markdown
|
||||
* text, so the blocks are read from that text instead.
|
||||
@@ -25,23 +19,9 @@ const textAt = (editor: Editor, position: Position): string => {
|
||||
const memoBlocks = (editor: Editor): readonly Block[] =>
|
||||
editor.mode === "source" ? parseMemoMarkdown(editor.getMarkdown()).blocks : editor.state.doc.blocks;
|
||||
|
||||
/** An empty paragraph, which an inserted block should replace rather than follow. */
|
||||
/** An empty paragraph, which inserted blocks take the place of rather than follow. */
|
||||
const isEmptyParagraph = (block: Block): boolean => block.type === "paragraph" && inlineText(block.content) === "";
|
||||
|
||||
/**
|
||||
* Inserts Markdown as its own blocks at `position`. In an empty paragraph it
|
||||
* takes the paragraph's place, as a paste would, so no empty line is left
|
||||
* above the inserted content.
|
||||
*/
|
||||
const insertBlocks = (editor: Editor, markdown: string, position: Position): void => {
|
||||
if (isEmptyParagraph(getBlock(editor.state.doc, position.blockId))) {
|
||||
editor.setSelection({ anchor: position, focus: position });
|
||||
editor.commands.insertMarkdown(markdown, { block: true });
|
||||
} else {
|
||||
editor.commands.insertMarkdown(markdown, { at: position, block: true });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* EditorController over a @usememos/editor instance. Every method reads the
|
||||
* live editor when called, so the controller can be handed out before the
|
||||
@@ -74,8 +54,9 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
|
||||
if (!editor || !markdown) return;
|
||||
// Insert at the caret without consuming the selection: callers live outside
|
||||
// the editor (attachment list, audio recorder), and replacing the range
|
||||
// would delete text the user merely had highlighted.
|
||||
insertBlocks(editor, markdown, editor.getSelection().focus);
|
||||
// would delete text the user merely had highlighted. An empty paragraph at
|
||||
// the caret is replaced, as a paste would.
|
||||
editor.commands.insertMarkdown(markdown, { at: editor.getSelection().focus, block: true });
|
||||
editor.commands.focus();
|
||||
editor.commands.scrollIntoView();
|
||||
},
|
||||
@@ -89,21 +70,10 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
|
||||
},
|
||||
insertTag: (tag) => {
|
||||
const editor = live(getEditor);
|
||||
if (!editor || !isCompleteTagValue(tag) || editor.isComposing || currentTags(editor).includes(tag)) return false;
|
||||
// Like insertMarkdown, keep highlighted text and insert at the active end.
|
||||
// Honor the chosen Markdown context, including code, instead of relocating it.
|
||||
const head = editor.getSelection().focus;
|
||||
const text = textAt(editor, head);
|
||||
const prefix = head.offset > 0 && !/\s/.test(text[head.offset - 1] ?? "") ? " " : "";
|
||||
const hasFollowingSpace = /^[ \t]$/.test(text[head.offset] ?? "");
|
||||
editor.setSelection({ anchor: head, focus: head });
|
||||
editor.commands.insertText(`${prefix}#${tag}${hasFollowingSpace ? "" : " "}`);
|
||||
if (hasFollowingSpace) {
|
||||
// Exactly one space follows the tag, inserted or reused; the caret lands after it.
|
||||
const after = editor.getSelection().focus;
|
||||
const next = { ...after, offset: after.offset + 1 };
|
||||
editor.setSelection({ anchor: next, focus: next });
|
||||
}
|
||||
if (!editor || !isCompleteTagValue(tag) || currentTags(editor).includes(tag)) return false;
|
||||
// As a word of its own at the caret, keeping highlighted text and the Markdown
|
||||
// context, including code; refused while an input method is composing.
|
||||
if (!editor.commands.insertToken(`#${tag}`)) return false;
|
||||
editor.commands.focus();
|
||||
editor.commands.scrollIntoView();
|
||||
return true;
|
||||
@@ -124,12 +94,10 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
|
||||
const widget = takeAnchor(id);
|
||||
if (!editor || !widget) return;
|
||||
if (markdown) {
|
||||
// The anchor sits after its block; an empty block gives its place to the content.
|
||||
const block = editor.state.doc.blocks.find((candidate) => candidate.id === widget.blockId);
|
||||
if (block && isEmptyParagraph(block)) {
|
||||
insertBlocks(editor, markdown, { blockId: block.id, offset: 0 });
|
||||
} else {
|
||||
editor.commands.insertMarkdown(markdown, { at: widget, block: true });
|
||||
}
|
||||
const at = block && isEmptyParagraph(block) ? { blockId: block.id, offset: 0 } : widget;
|
||||
editor.commands.insertMarkdown(markdown, { at, block: true });
|
||||
editor.commands.focus();
|
||||
editor.commands.scrollIntoView();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { cacheService } from "./services/cacheService";
|
||||
|
||||
/** What an editing session is for, which decides where its draft and caret are kept. */
|
||||
export type MemoEditIdentity =
|
||||
| { kind: "edit"; name: string }
|
||||
| { kind: "comment"; parent: string }
|
||||
| { kind: "new"; scope: string; space?: string };
|
||||
|
||||
/** The suffix of the draft's storage key; `cacheService.key` prefixes the user. */
|
||||
export function draftKeyFor(identity: MemoEditIdentity): string {
|
||||
switch (identity.kind) {
|
||||
case "edit":
|
||||
return `edit:${identity.name}`;
|
||||
case "comment":
|
||||
return `comment:${identity.parent}`;
|
||||
case "new":
|
||||
return identity.space ? `new:${identity.scope}:${identity.space}` : `new:${identity.scope}`;
|
||||
}
|
||||
}
|
||||
|
||||
// The keys hosts chose for themselves before the key followed the identity.
|
||||
const LEGACY_SCOPE_PREFIXES: Record<string, string> = {
|
||||
home: "home-memo-editor",
|
||||
global: "global-memo-editor",
|
||||
calendar: "calendar-day-editor",
|
||||
map: "map-editor",
|
||||
};
|
||||
|
||||
/** The key a draft for `identity` was stored under before this scheme, if it had one. */
|
||||
export function legacyDraftKeyFor(identity: MemoEditIdentity): string | undefined {
|
||||
if (identity.kind === "comment") return `${identity.parent}-comment`;
|
||||
if (identity.kind !== "new") return undefined;
|
||||
const [head, ...rest] = identity.scope.split(":");
|
||||
const prefix = LEGACY_SCOPE_PREFIXES[head];
|
||||
if (!prefix) return undefined;
|
||||
const scoped = rest.length > 0 ? `${prefix}:${rest.join(":")}` : prefix;
|
||||
return identity.space ? `${scoped}:${identity.space}` : scoped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a draft stored under the previous key scheme to its key under this one, once.
|
||||
* A draft already under the new key wins.
|
||||
*/
|
||||
export function migrateLegacyDraft(username: string, identity: MemoEditIdentity): void {
|
||||
const legacySuffix = legacyDraftKeyFor(identity);
|
||||
if (!legacySuffix) return;
|
||||
const from = cacheService.key(username, legacySuffix);
|
||||
const to = cacheService.key(username, draftKeyFor(identity));
|
||||
try {
|
||||
if (localStorage.getItem(to) !== null || localStorage.getItem(from) === null) return;
|
||||
cacheService.saveNow(to, cacheService.loadDraft(from));
|
||||
cacheService.clear(from);
|
||||
} catch {
|
||||
// Storage is unavailable; there is nothing to move.
|
||||
}
|
||||
}
|
||||
+3
-16
@@ -1,8 +1,6 @@
|
||||
import { type Extension, fileHandler, matchToken, type SuggestionAllowContext, scanTags, suggestion } from "@usememos/editor";
|
||||
import { emoji } from "@usememos/editor/emoji";
|
||||
import { memoExtensions, memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
|
||||
import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
|
||||
import type { EditorPosition } from "../types/editorController";
|
||||
import type { EditorPosition } from "./types/editorController";
|
||||
|
||||
/** The gesture that handed files to the editor: a drop lands at a document position, a paste has none. */
|
||||
export type EditorFileOrigin = { source: "paste" } | { source: "drop"; position: EditorPosition | null };
|
||||
@@ -11,10 +9,6 @@ export interface EditorExtensionsOptions {
|
||||
/** Known tags, read when the popup asks for items. */
|
||||
getTags: () => string[];
|
||||
onFiles: (files: File[], origin: EditorFileOrigin) => void;
|
||||
/** The user's tag settings, read when tags are drawn, for their custom colors. */
|
||||
getTagsSetting: () => UserSetting_TagsSetting | undefined;
|
||||
/** Whether a mentioned username belongs to a user, read when mentions are drawn. */
|
||||
isMentionResolved: (username: string) => boolean;
|
||||
/** Accessible name of the emoji popup. */
|
||||
emojiLabel: string;
|
||||
}
|
||||
@@ -57,16 +51,9 @@ export const allowTagSuggestion = ({ excluded, explicit, query, textBefore }: Su
|
||||
return !(query === "" && /(^|\n)[ \t]*$/.test(textBefore));
|
||||
};
|
||||
|
||||
export function buildEditorExtensions({
|
||||
getTags,
|
||||
onFiles,
|
||||
getTagsSetting,
|
||||
isMentionResolved,
|
||||
emojiLabel,
|
||||
}: EditorExtensionsOptions): Extension[] {
|
||||
/** What only the composer adds to the memo syntax MemoMarkdown already reads: autocomplete and file handling. */
|
||||
export function buildEditorExtensions({ getTags, onFiles, emojiLabel }: EditorExtensionsOptions): Extension[] {
|
||||
return [
|
||||
// Tags and mentions look the same as in the memo view.
|
||||
...memoExtensions({ tags: memoTagOptions(getTagsSetting), mentions: memoMentionOptions(isMentionResolved) }),
|
||||
// The popup opens exactly where tags are highlighted: the matcher is built
|
||||
// from the same scanner as tags(). A pick writes "#work/planning ".
|
||||
suggestion({
|
||||
+4
-7
@@ -30,7 +30,7 @@ const sameDraft = (left: EditorDraft, right: EditorDraft): boolean =>
|
||||
* state as props, so the component that mounts this hook does not re-render on
|
||||
* every keystroke.
|
||||
*/
|
||||
export const useAutoSave = (username: string, cacheKey: string | undefined, enabled = true) => {
|
||||
export const useAutoSave = (key: string, enabled = true) => {
|
||||
const store = useEditorStore();
|
||||
const latestDraftRef = useRef<EditorDraft>(draftFromState(store.getState()));
|
||||
const discardedDraftRef = useRef<EditorDraft | undefined>(undefined);
|
||||
@@ -38,7 +38,6 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
const persist = (draft: EditorDraft) => {
|
||||
latestDraftRef.current = draft;
|
||||
if (discardedDraftRef.current !== undefined && !sameDraft(discardedDraftRef.current, draft)) {
|
||||
@@ -55,12 +54,11 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
|
||||
persist(draft);
|
||||
}
|
||||
});
|
||||
}, [store, username, cacheKey, enabled]);
|
||||
}, [store, key, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
const flushDraft = () => {
|
||||
if (discardedDraftRef.current && sameDraft(discardedDraftRef.current, latestDraftRef.current)) {
|
||||
return;
|
||||
@@ -84,13 +82,12 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
|
||||
window.removeEventListener("pagehide", flushDraft);
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
};
|
||||
}, [store, username, cacheKey, enabled]);
|
||||
}, [store, key, enabled]);
|
||||
|
||||
const discardDraft = useCallback(() => {
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
discardedDraftRef.current = latestDraftRef.current;
|
||||
cacheService.clear(key);
|
||||
}, [username, cacheKey]);
|
||||
}, [key]);
|
||||
|
||||
return { discardDraft };
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { EditorMode } from "@usememos/editor";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { cacheService } from "../services";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
interface UseMemoInitOptions {
|
||||
editorRef: React.RefObject<EditorController | null>;
|
||||
/** The persisted draft's key, under which the caret was remembered. */
|
||||
draftKey: string;
|
||||
autoFocus?: boolean | (() => boolean);
|
||||
/** The mode the editor opens in; a caret saved in the other mode is not restored. */
|
||||
mode: EditorMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Once the editor has mounted over its initial draft (see `initialEditorState`), puts
|
||||
* the caret back where it was remembered and focuses when asked. `autoFocus` is read
|
||||
* after the caret is restored, so a host can decide then whether focus is still wanted.
|
||||
*/
|
||||
export const useMemoInit = ({ editorRef, draftKey, autoFocus, mode }: UseMemoInitOptions) => {
|
||||
const initializedRef = useRef(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
const cachedCursor = cacheService.loadCursor(draftKey, mode);
|
||||
let restoreCursorTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
if (autoFocus || cachedCursor !== undefined) {
|
||||
restoreCursorTimer = setTimeout(() => {
|
||||
if (cachedCursor !== undefined) {
|
||||
editorRef.current?.setSelection(cachedCursor);
|
||||
}
|
||||
if (typeof autoFocus === "function" ? autoFocus() : autoFocus) {
|
||||
editorRef.current?.focus();
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
setIsInitialized(true);
|
||||
return () => {
|
||||
if (restoreCursorTimer) {
|
||||
clearTimeout(restoreCursorTimer);
|
||||
}
|
||||
};
|
||||
}, [draftKey, autoFocus, mode, editorRef]);
|
||||
|
||||
return { isInitialized };
|
||||
};
|
||||
+24
-18
@@ -1,15 +1,17 @@
|
||||
import { Code, ConnectError } from "@connectrpc/connect";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useNewMemo } from "@/contexts/NewMemoContext";
|
||||
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
|
||||
import { memoKeys } from "@/hooks/useMemoQueries";
|
||||
import { memoDetailQueryOptions, useCreateMemo, useUpdateMemo } from "@/hooks/useMemoQueries";
|
||||
import { userKeys } from "@/hooks/useUserQueries";
|
||||
import { handleError } from "@/lib/error";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import type { Visibility } from "@/types/proto/api/memo_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { errorService, memoService, validationService } from "../services";
|
||||
import type { MemoSaveOperations } from "../services/memoService";
|
||||
import { useEditorContext } from "../state";
|
||||
import { restampDefaultCreateTime } from "../utils/deriveDefaultCreateTime";
|
||||
|
||||
@@ -28,9 +30,10 @@ interface UseMemoSaveOptions {
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the editor's save transaction and its post-save cache/state updates.
|
||||
* Keeping this workflow outside the shell makes saving identical whether it is
|
||||
* triggered by the toolbar or the editor keyboard shortcut.
|
||||
* Owns the editor's save transaction and its post-save state. The memo itself is
|
||||
* written through the memo mutation hooks, which patch and refresh every query that
|
||||
* holds it, so the saved text shows wherever the memo is on the page as soon as the
|
||||
* server answers. Saving is identical whether the toolbar or the keyboard triggers it.
|
||||
*/
|
||||
export function useMemoSave({
|
||||
memoName,
|
||||
@@ -44,6 +47,8 @@ export function useMemoSave({
|
||||
}: UseMemoSaveOptions): () => Promise<void> {
|
||||
const t = useTranslate();
|
||||
const queryClient = useQueryClient();
|
||||
const { mutateAsync: createMemo } = useCreateMemo();
|
||||
const { mutateAsync: updateMemo } = useUpdateMemo();
|
||||
const { markNewMemo } = useNewMemo();
|
||||
const { actions, dispatch, getState } = useEditorContext();
|
||||
|
||||
@@ -78,6 +83,17 @@ export function useMemoSave({
|
||||
dispatch(actions.setLocalFiles(current.localFiles.filter((file) => !uploaded.has(file.previewUrl))));
|
||||
};
|
||||
|
||||
const operations: MemoSaveOperations = {
|
||||
// The server's current copy, fetched afresh into the detail cache.
|
||||
getMemo: async (name) => {
|
||||
const memo = await queryClient.fetchQuery({ ...memoDetailQueryOptions(name), staleTime: 0 });
|
||||
if (!memo) throw new ConnectError("memo not found", Code.NotFound);
|
||||
return memo;
|
||||
},
|
||||
updateMemo: (update, updateMask) => updateMemo({ update, updateMask }),
|
||||
createMemo: (memo, parent) => createMemo({ memo, parent }),
|
||||
};
|
||||
|
||||
try {
|
||||
// A new memo composed on a selected day keeps the day but is stamped with
|
||||
// the time of saving, so consecutive memos do not share one createTime.
|
||||
@@ -96,6 +112,7 @@ export function useMemoSave({
|
||||
space: defaultSpace,
|
||||
onFileUploaded: (file, attachment) => uploaded.set(file.previewUrl, attachment),
|
||||
},
|
||||
operations,
|
||||
);
|
||||
|
||||
if (!result.hasChanges) {
|
||||
@@ -111,27 +128,14 @@ export function useMemoSave({
|
||||
toast.success(t("memo.moved"));
|
||||
}
|
||||
|
||||
const invalidationPromises: Promise<unknown>[] = [
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.lists() }),
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.stats() }),
|
||||
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() }),
|
||||
];
|
||||
if (memoName) {
|
||||
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(memoName) }));
|
||||
}
|
||||
if (parentMemoName) {
|
||||
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.comments(parentMemoName) }));
|
||||
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(parentMemoName) }));
|
||||
}
|
||||
// Hosts that close after saving (edit, comment) hold a brief "Saved"
|
||||
// confirmation on the toolbar while the caches refresh underneath. The
|
||||
// in-place composer clears immediately, so it shows nothing.
|
||||
if (memoName || parentMemoName) {
|
||||
dispatch(actions.setLoading("saving", false));
|
||||
dispatch(actions.setJustSaved(true));
|
||||
invalidationPromises.push(new Promise((resolve) => setTimeout(resolve, SAVED_CONFIRMATION_MS)));
|
||||
await new Promise((resolve) => setTimeout(resolve, SAVED_CONFIRMATION_MS));
|
||||
}
|
||||
await Promise.all(invalidationPromises);
|
||||
|
||||
dispatch(actions.reset());
|
||||
if (!memoName && defaultVisibility) {
|
||||
@@ -166,6 +170,7 @@ export function useMemoSave({
|
||||
}
|
||||
}, [
|
||||
actions,
|
||||
createMemo,
|
||||
defaultCreateTime,
|
||||
defaultSpace,
|
||||
defaultVisibility,
|
||||
@@ -179,5 +184,6 @@ export function useMemoSave({
|
||||
parentMemoName,
|
||||
queryClient,
|
||||
t,
|
||||
updateMemo,
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
|
||||
import type { User } from "@/types/proto/api/user_service_pb";
|
||||
import { canManageMemo } from "@/utils/user";
|
||||
import { cacheService } from "./services/cacheService";
|
||||
import { memoService } from "./services/memoService";
|
||||
import { createInitialState, type EditorState } from "./state/types";
|
||||
|
||||
/**
|
||||
* Whether a session may place the memo in a Space of its own. Replies are never placed
|
||||
* independently: a comment's Space is its parent's. An edited top-level memo can change
|
||||
* its Space; a new one can unless its host fixes the target, such as composing inside a
|
||||
* Space.
|
||||
*/
|
||||
export const canChooseSpaceFor = ({
|
||||
memo,
|
||||
currentUser,
|
||||
parentMemoName,
|
||||
defaultSpace,
|
||||
}: {
|
||||
memo?: Memo;
|
||||
currentUser: User | undefined;
|
||||
parentMemoName?: string;
|
||||
defaultSpace?: string;
|
||||
}): boolean => (memo ? !memo.parent && canManageMemo(memo, currentUser) : !parentMemoName && !defaultSpace);
|
||||
|
||||
export interface InitialEditorStateOptions {
|
||||
/** The memo being edited; its draft is never restored from the cache. */
|
||||
memo?: Memo;
|
||||
/** The persisted draft's key, for a new memo or comment. */
|
||||
draftKey: string;
|
||||
initialFocusMode?: boolean;
|
||||
defaultVisibility?: Visibility;
|
||||
defaultCreateTime?: Date;
|
||||
defaultLocation?: Location;
|
||||
/** Whether the draft may carry a Space of its own; a comment's Space is its parent's. */
|
||||
canChooseSpace?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft store's first state, computed once when editing starts: the memo's own
|
||||
* fields for an edit, otherwise the persisted draft under `draftKey` over the host's
|
||||
* defaults. A cached `null` location is one the user removed, so the default does not
|
||||
* come back.
|
||||
*/
|
||||
export function initialEditorState({
|
||||
memo,
|
||||
draftKey,
|
||||
initialFocusMode = false,
|
||||
defaultVisibility,
|
||||
defaultCreateTime,
|
||||
defaultLocation,
|
||||
canChooseSpace = false,
|
||||
}: InitialEditorStateOptions): EditorState {
|
||||
const base = createInitialState(initialFocusMode);
|
||||
if (memo) {
|
||||
cacheService.clear(draftKey);
|
||||
return { ...base, ...memoService.fromMemo(memo) };
|
||||
}
|
||||
const draft = cacheService.loadDraft(draftKey);
|
||||
const visibility = draft.visibility ?? defaultVisibility ?? base.metadata.visibility;
|
||||
return {
|
||||
...base,
|
||||
content: draft.content,
|
||||
metadata: {
|
||||
...base.metadata,
|
||||
attachments: draft.attachments.length > 0 ? draft.attachments : base.metadata.attachments,
|
||||
location: draft.location === null ? undefined : (draft.location ?? defaultLocation),
|
||||
visibility,
|
||||
space: canChooseSpace ? draft.space : undefined,
|
||||
},
|
||||
timestamps: defaultCreateTime ? { createTime: defaultCreateTime, updateTime: defaultCreateTime } : base.timestamps,
|
||||
};
|
||||
}
|
||||
+3
-2
@@ -98,8 +98,9 @@ function writeEntry(key: string, draft: EditorDraft): void {
|
||||
}
|
||||
|
||||
export const cacheService = {
|
||||
key: (username: string, cacheKey?: string): string => {
|
||||
return `${username}-${cacheKey || ""}`;
|
||||
/** The storage key for a draft: the user, then the identity-derived suffix (see `draftKeyFor`). */
|
||||
key: (username: string, draftKey?: string): string => {
|
||||
return `${username}-${draftKey || ""}`;
|
||||
},
|
||||
|
||||
save: (key: string, draft: EditorDraft) => {
|
||||
+14
-14
@@ -1,8 +1,7 @@
|
||||
import { create } from "@bufbuild/protobuf";
|
||||
import { FieldMaskSchema, timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
|
||||
import { timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
|
||||
import { isEqual } from "lodash-es";
|
||||
import { getEditorReferenceRelations } from "@/components/MemoMetadata/Relation/relationHelpers";
|
||||
import { memoServiceClient } from "@/connect";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
|
||||
import type { Memo } from "@/types/proto/api/memo_service_pb";
|
||||
@@ -85,6 +84,15 @@ function buildUpdateMask(
|
||||
return { mask, patch };
|
||||
}
|
||||
|
||||
/** The memo operations a save runs: the memo mutation hooks, so caches follow every save. */
|
||||
export interface MemoSaveOperations {
|
||||
/** The memo as the server has it now, to diff the draft against. */
|
||||
getMemo: (name: string) => Promise<Memo>;
|
||||
updateMemo: (update: Partial<Memo>, updateMask: string[]) => Promise<Memo>;
|
||||
/** Creates a memo, or a comment on `parent`. */
|
||||
createMemo: (memo: Memo, parent?: string) => Promise<Memo>;
|
||||
}
|
||||
|
||||
export const memoService = {
|
||||
async save(
|
||||
state: EditorState,
|
||||
@@ -95,6 +103,7 @@ export const memoService = {
|
||||
/** Runs as each local file finishes uploading, before the memo is saved. */
|
||||
onFileUploaded?: (localFile: LocalFile, attachment: Attachment) => void;
|
||||
},
|
||||
operations: MemoSaveOperations,
|
||||
): Promise<{ memoName: string; hasChanges: boolean; moved?: boolean }> {
|
||||
// 1. Upload local files first
|
||||
const newAttachments = await uploadService.uploadFiles(state.localFiles, options.onFileUploaded);
|
||||
@@ -102,17 +111,14 @@ export const memoService = {
|
||||
|
||||
// 2. Update existing memo
|
||||
if (options.memoName) {
|
||||
const prevMemo = await memoServiceClient.getMemo({ name: options.memoName });
|
||||
const prevMemo = await operations.getMemo(options.memoName);
|
||||
const { mask, patch } = buildUpdateMask(prevMemo, state, allAttachments);
|
||||
|
||||
if (mask.size === 0) {
|
||||
return { memoName: prevMemo.name, hasChanges: false };
|
||||
}
|
||||
|
||||
const memo = await memoServiceClient.updateMemo({
|
||||
memo: create(MemoSchema, patch as Record<string, unknown>),
|
||||
updateMask: create(FieldMaskSchema, { paths: Array.from(mask) }),
|
||||
});
|
||||
const memo = await operations.updateMemo(patch, Array.from(mask));
|
||||
return { memoName: memo.name, hasChanges: true, moved: mask.has("space") };
|
||||
}
|
||||
|
||||
@@ -128,13 +134,7 @@ export const memoService = {
|
||||
space: options.parentMemoName ? undefined : (options.space ?? state.metadata.space),
|
||||
});
|
||||
|
||||
const memo = options.parentMemoName
|
||||
? await memoServiceClient.createMemoComment({
|
||||
parent: options.parentMemoName,
|
||||
comment: memoData,
|
||||
})
|
||||
: await memoServiceClient.createMemo({ memo: memoData });
|
||||
|
||||
const memo = await operations.createMemo(memoData, options.parentMemoName);
|
||||
return { memoName: memo.name, hasChanges: true };
|
||||
},
|
||||
|
||||
+8
-9
@@ -1,24 +1,25 @@
|
||||
import type { MemoSuggestion } from "@/lib/memo-suggestions";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
|
||||
import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
|
||||
import type { EditorFileOrigin } from "../Editor/extensions";
|
||||
import type { EditorFileOrigin } from "../extensions";
|
||||
import type { AudioRecorderStatus } from "../hooks/useAudioRecorder";
|
||||
import type { LocalFile } from "./attachment";
|
||||
|
||||
export interface MemoEditorProps {
|
||||
/** What MemoEditor hands an editing session: its subject, the host's defaults, and where the draft lives. */
|
||||
export interface EditSessionProps {
|
||||
className?: string;
|
||||
cacheKey?: string;
|
||||
/** The draft and caret storage key, derived from what is edited; see `draftKeyFor`. */
|
||||
draftKey: string;
|
||||
/** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
|
||||
frameless?: boolean;
|
||||
placeholder?: string;
|
||||
/** Existing memo to edit. When provided, the editor initializes from it without fetching. */
|
||||
/** Existing memo to edit; the session starts from it and persists no draft. */
|
||||
memo?: Memo;
|
||||
parentMemoName?: string;
|
||||
/** Context-derived suggestions for a new top-level memo. */
|
||||
suggestions?: readonly MemoSuggestion[];
|
||||
/** Assigns a newly created top-level memo to this Space. Ignored for edits and comments. */
|
||||
defaultSpace?: string;
|
||||
/** Seeds a new memo once; restored draft metadata takes precedence. */
|
||||
defaultLocation?: Location;
|
||||
/** A callback can decide whether focus is still appropriate after draft restoration. */
|
||||
autoFocus?: boolean | (() => boolean);
|
||||
/**
|
||||
@@ -54,8 +55,6 @@ export interface EditorContentProps {
|
||||
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
|
||||
onSubmit: () => void;
|
||||
onFiles: (files: File[], origin: EditorFileOrigin) => void;
|
||||
/** The user's tag settings, for tags in their custom colors. */
|
||||
tagsSetting?: UserSetting_TagsSetting;
|
||||
}
|
||||
|
||||
/**
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type { Position, SelectionJSON } from "@usememos/editor";
|
||||
import type { UploadAnchorDescriptor } from "../Editor/uploadAnchors";
|
||||
import type { UploadAnchorDescriptor } from "../uploadAnchors";
|
||||
|
||||
/** A place in the document, such as where files were dropped. Valid until the document changes. */
|
||||
export type EditorPosition = Position;
|
||||
+1
-1
@@ -8,10 +8,10 @@ export type {
|
||||
EditorSourceModeToggle,
|
||||
EditorToolbarProps,
|
||||
EditorViewToggles,
|
||||
EditSessionProps,
|
||||
FocusModeExitButtonProps,
|
||||
FocusModeOverlayProps,
|
||||
InsertMenuProps,
|
||||
MemoEditorProps,
|
||||
} from "./components";
|
||||
export type { EditorController } from "./editorController";
|
||||
export type { LocationState } from "./insertMenu";
|
||||
@@ -1,103 +0,0 @@
|
||||
import type { EditorMode } from "@usememos/editor";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
|
||||
import { cacheService, memoService } from "../services";
|
||||
import { useEditorContext } from "../state";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
interface UseMemoInitOptions {
|
||||
editorRef: React.RefObject<EditorController | null>;
|
||||
memo?: Memo;
|
||||
cacheKey?: string;
|
||||
username: string;
|
||||
autoFocus?: boolean | (() => boolean);
|
||||
defaultVisibility?: Visibility;
|
||||
defaultCreateTime?: Date;
|
||||
defaultLocation?: Location;
|
||||
canChooseSpace?: boolean;
|
||||
/** The mode the editor opens in; a caret saved in the other mode is not restored. */
|
||||
mode: EditorMode;
|
||||
}
|
||||
|
||||
export const useMemoInit = ({
|
||||
editorRef,
|
||||
memo,
|
||||
cacheKey,
|
||||
username,
|
||||
autoFocus,
|
||||
defaultVisibility,
|
||||
defaultCreateTime,
|
||||
defaultLocation,
|
||||
canChooseSpace = false,
|
||||
mode,
|
||||
}: UseMemoInitOptions) => {
|
||||
const { actions, dispatch } = useEditorContext();
|
||||
const initializedRef = useRef(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
|
||||
if (memo) {
|
||||
const initialState = memoService.fromMemo(memo);
|
||||
cacheService.clear(key);
|
||||
dispatch(actions.initMemo(initialState));
|
||||
} else {
|
||||
const cachedDraft = cacheService.loadDraft(key);
|
||||
if (cachedDraft.content) {
|
||||
dispatch(actions.updateContent(cachedDraft.content));
|
||||
}
|
||||
if (cachedDraft.attachments.length > 0) {
|
||||
dispatch(actions.setMetadata({ attachments: cachedDraft.attachments }));
|
||||
}
|
||||
dispatch(actions.setMetadata({ location: cachedDraft.location === null ? undefined : (cachedDraft.location ?? defaultLocation) }));
|
||||
const visibility = cachedDraft.visibility ?? defaultVisibility;
|
||||
if (visibility !== undefined) {
|
||||
dispatch(actions.setMetadata({ visibility }));
|
||||
}
|
||||
if (canChooseSpace) {
|
||||
dispatch(actions.setMetadata({ space: cachedDraft.space }));
|
||||
}
|
||||
if (defaultCreateTime) {
|
||||
dispatch(actions.setTimestamps({ createTime: defaultCreateTime, updateTime: defaultCreateTime }));
|
||||
}
|
||||
}
|
||||
|
||||
const cachedCursor = cacheService.loadCursor(key, mode);
|
||||
let restoreCursorTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
if (autoFocus || cachedCursor !== undefined) {
|
||||
restoreCursorTimer = setTimeout(() => {
|
||||
if (cachedCursor !== undefined) {
|
||||
editorRef.current?.setSelection(cachedCursor);
|
||||
}
|
||||
if (typeof autoFocus === "function" ? autoFocus() : autoFocus) {
|
||||
editorRef.current?.focus();
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
setIsInitialized(true);
|
||||
return () => {
|
||||
if (restoreCursorTimer) {
|
||||
clearTimeout(restoreCursorTimer);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
memo,
|
||||
cacheKey,
|
||||
username,
|
||||
autoFocus,
|
||||
defaultVisibility,
|
||||
defaultCreateTime,
|
||||
defaultLocation,
|
||||
canChooseSpace,
|
||||
mode,
|
||||
actions,
|
||||
dispatch,
|
||||
editorRef,
|
||||
]);
|
||||
|
||||
return { isInitialized };
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export {
|
||||
type MemoDraftSeed,
|
||||
type MemoEditingProps,
|
||||
MemoEditor,
|
||||
type MemoEditorDraftProps,
|
||||
type MemoEditorEditProps,
|
||||
type MemoEditorProps,
|
||||
type MemoEditorViewProps,
|
||||
preloadMemoEditing,
|
||||
} from "./MemoEditor";
|
||||
@@ -1,15 +0,0 @@
|
||||
import { loadWithReload } from "@/utils/lazy";
|
||||
|
||||
type MemoEditorModule = typeof import(".");
|
||||
|
||||
let memoEditorModulePromise: Promise<MemoEditorModule> | undefined;
|
||||
|
||||
// Share one in-flight request across edit and comment entry points. Callers
|
||||
// keep their current UI mounted until this promise resolves.
|
||||
export const loadMemoEditor = (): Promise<MemoEditorModule> => {
|
||||
memoEditorModulePromise ??= loadWithReload(() => import(".")).catch((error) => {
|
||||
memoEditorModulePromise = undefined;
|
||||
throw error;
|
||||
});
|
||||
return memoEditorModulePromise;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Editor, TagsOptions } from "@usememos/editor";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useResolvedMentionUsernames } from "@/contexts/MentionResolutionContext";
|
||||
import { useDebouncedEffect } from "@/hooks";
|
||||
import { memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
|
||||
|
||||
/** How long typing pauses before the mentions in a draft are looked up. */
|
||||
const MENTION_LOOKUP_DELAY_MS = 400;
|
||||
|
||||
export interface MemoDecorations {
|
||||
/** `tags()` class, attributes and click: pills in the viewer's custom tag colors. */
|
||||
readonly tags: Pick<TagsOptions, "class" | "attributes" | "onClick">;
|
||||
/** `mentions()` class, attributes and click: the primary color for people who exist. */
|
||||
readonly mentions: Pick<TagsOptions, "class" | "attributes" | "onClick">;
|
||||
}
|
||||
|
||||
export interface MemoDecorationHandlers {
|
||||
/** A tag was clicked to be followed, without its `#`. */
|
||||
onTagClick?: (tag: string) => void;
|
||||
/** A mention of someone who exists was clicked to be followed, without its `@`. Unknown names are plain text. */
|
||||
onMentionClick?: (username: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a memo's tags and mentions look like wherever a memo is shown, and what a click on
|
||||
* them does. The options are stable for the editor's lifetime and read the latest data
|
||||
* and handlers through refs; `editor` decorates again when that data changes.
|
||||
*
|
||||
* Tag colors come from the viewer's tag settings. Mentions resolve through the shared
|
||||
* provider of the surrounding list when it knows this content, otherwise with a lookup
|
||||
* of their own. While editing, a half-typed name is not looked up: mentions are read
|
||||
* once typing pauses, and until a lookup answers, the people already found stay found.
|
||||
*/
|
||||
export function useMemoDecorations(
|
||||
editor: Editor | null,
|
||||
value: string,
|
||||
editable: boolean,
|
||||
handlers: MemoDecorationHandlers = {},
|
||||
): MemoDecorations {
|
||||
const { userTagsSetting } = useAuth();
|
||||
const [settled, setSettled] = useState(value);
|
||||
useDebouncedEffect(() => setSettled(value), MENTION_LOOKUP_DELAY_MS, [value]);
|
||||
const resolved = useResolvedMentionUsernames(editable ? settled : value);
|
||||
|
||||
const tagsSettingRef = useRef(userTagsSetting);
|
||||
tagsSettingRef.current = userTagsSetting;
|
||||
const resolvedRef = useRef(resolved);
|
||||
resolvedRef.current = resolved;
|
||||
const handlersRef = useRef(handlers);
|
||||
handlersRef.current = handlers;
|
||||
|
||||
// Decorate again only when what the decorations read changed: a new editor already
|
||||
// decorates with the current values, and a lookup that answers the same is a no-op.
|
||||
const mentionKey = useMemo(() => [...resolved].sort().join(" "), [resolved]);
|
||||
const decorated = useRef({ mentionKey, userTagsSetting });
|
||||
useEffect(() => {
|
||||
const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
|
||||
decorated.current = { mentionKey, userTagsSetting };
|
||||
if (changed) editor?.redecorate();
|
||||
}, [editor, mentionKey, userTagsSetting]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
tags: {
|
||||
...memoTagOptions(() => tagsSettingRef.current),
|
||||
onClick: ({ match }) => {
|
||||
const onTagClick = handlersRef.current.onTagClick;
|
||||
if (!onTagClick) return false;
|
||||
onTagClick(match.slice(1));
|
||||
return true;
|
||||
},
|
||||
},
|
||||
mentions: {
|
||||
...memoMentionOptions((username) => resolvedRef.current.has(username)),
|
||||
onClick: ({ match }) => {
|
||||
const username = match.slice(1);
|
||||
const onMentionClick = handlersRef.current.onMentionClick;
|
||||
if (!onMentionClick || !resolvedRef.current.has(username)) return false;
|
||||
onMentionClick(username);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { Editor } from "@usememos/editor";
|
||||
import { memo, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { MemoMarkdown } from "@/components/MemoEditor/MemoMarkdown";
|
||||
import { createMemoNavigationState } from "@/components/MemoView/navigation";
|
||||
import { useContentSearchTerms } from "@/contexts/MemoFilterContext";
|
||||
import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
|
||||
import { useNearViewport } from "@/hooks/useNearViewport";
|
||||
import { markdownStyles } from "@/lib/markdownStyles";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getCreatorHomePath } from "@/router/routes";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
import { findAnchorTarget } from "@/utils/markdown-manipulation";
|
||||
import { headingSlugs } from "./headings";
|
||||
import LinkMetadataCard from "./LinkMetadataCard";
|
||||
import { type LinkCardMount, linkCardsExtension } from "./linkCards";
|
||||
import { useSearchMatchHighlight } from "./useSearchMatchHighlight";
|
||||
import { useTagNavigation } from "./useTagNavigation";
|
||||
|
||||
export interface MemoContentViewProps {
|
||||
content: string;
|
||||
/** Attachments bound to this memo, used to resolve managed image URLs in share/S3 modes. */
|
||||
attachments?: readonly Attachment[];
|
||||
/** Resource name of the memo (e.g. `memos/abc123`). Lets in-memo anchor links open the memo detail page. */
|
||||
memoName?: string;
|
||||
/** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
|
||||
parentPage?: string;
|
||||
/** The card renders collapsed (ClampedSection), so in-memo anchor links navigate instead of scrolling. */
|
||||
compact?: boolean;
|
||||
/**
|
||||
* Lets the viewer tick task items, for a memo they can manage. Called with the new
|
||||
* Markdown, in which only the ticked item's `[ ]` or `[x]` changed.
|
||||
*/
|
||||
onTaskToggle?: (content: string) => void;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
onDoubleClick?: (e: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
const LinkPreview = ({ href }: { href: string }) => {
|
||||
const { ref, isNearViewport } = useNearViewport<HTMLAnchorElement>();
|
||||
const fallback = (
|
||||
<a ref={ref} href={href} target="_blank" rel="noopener noreferrer" className={markdownStyles.link}>
|
||||
{href}
|
||||
</a>
|
||||
);
|
||||
return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
|
||||
};
|
||||
|
||||
/** A mounted card, keyed for React: the element is the editor's, so the key cannot be derived from the block. */
|
||||
interface LinkCard extends LinkCardMount {
|
||||
readonly key: number;
|
||||
}
|
||||
let nextLinkCardKey = 0;
|
||||
|
||||
/**
|
||||
* A memo's content, read-only, with the memo view's own surface over MemoMarkdown: tags and
|
||||
* mentions navigate, in-memo anchors scroll, bare links become preview cards, and the page's
|
||||
* search matches are painted. Owners can tick task items: each tick reports the new Markdown,
|
||||
* in which only that item's `[ ]` or `[x]` changed. Truncation is not this component's
|
||||
* concern — compact cards are bounded by ClampedSection around the whole memo body;
|
||||
* `compact` only tells in-memo anchor links to open the detail page, since a collapsed card
|
||||
* may hide their target. MemoEditor shows a memo by name through it; previews pass content.
|
||||
*/
|
||||
const MemoContentViewImpl = (props: MemoContentViewProps) => {
|
||||
const { className, contentClassName, content, attachments, memoName, parentPage, compact, onTaskToggle, onClick, onDoubleClick } = props;
|
||||
const navigate = useNavigate();
|
||||
const linkPreviewEnabled = useLinkPreviewEnabled();
|
||||
const navigateToTag = useTagNavigation(parentPage);
|
||||
// Whatever the page's search matched is painted here, without altering the rendered tree.
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
useSearchMatchHighlight(contentRef, useContentSearchTerms());
|
||||
const [editor, setEditor] = useState<Editor | null>(null);
|
||||
|
||||
// Bare links become preview cards through the editor's block view: it hands over an
|
||||
// element per such paragraph and keeps it while the block is unchanged, so the card
|
||||
// portaled into it survives renders. Built once; the setting is read through a ref and
|
||||
// applied with a refresh of this view.
|
||||
const [cards, setCards] = useState<readonly LinkCard[]>([]);
|
||||
const linkPreviewEnabledRef = useRef(linkPreviewEnabled);
|
||||
linkPreviewEnabledRef.current = linkPreviewEnabled;
|
||||
const linkCards = useMemo(
|
||||
() => [
|
||||
linkCardsExtension({
|
||||
isEnabled: () => linkPreviewEnabledRef.current,
|
||||
onMount: (mount) =>
|
||||
setCards((previous) => [...previous.filter((card) => card.element !== mount.element), { ...mount, key: nextLinkCardKey++ }]),
|
||||
onUnmount: (element) => setCards((previous) => previous.filter((card) => card.element !== element)),
|
||||
}),
|
||||
],
|
||||
[],
|
||||
);
|
||||
const appliedLinkPreview = useRef(linkPreviewEnabled);
|
||||
useEffect(() => {
|
||||
if (appliedLinkPreview.current === linkPreviewEnabled) return;
|
||||
appliedLinkPreview.current = linkPreviewEnabled;
|
||||
editor?.refreshViews("linkCards");
|
||||
}, [editor, linkPreviewEnabled]);
|
||||
|
||||
// In-memo anchors scroll within this memo; a collapsed card may hide the target, so it opens the detail page.
|
||||
const handleLinkClick = ({ href }: { href: string }) => {
|
||||
if (!href.startsWith("#")) return false;
|
||||
const id = decodeURIComponent(href.slice(1));
|
||||
const target = !compact && id && contentRef.current ? findAnchorTarget(contentRef.current, id) : null;
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
} else if (memoName) {
|
||||
navigate(`/${memoName}${href}`, { state: parentPage ? createMemoNavigationState(parentPage) : undefined });
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
|
||||
<div
|
||||
ref={contentRef}
|
||||
data-memo-content
|
||||
data-memo-name={memoName}
|
||||
className={cn(
|
||||
"relative w-full max-w-full wrap-break-word text-base leading-6",
|
||||
"[&_.katex-display]:max-w-full",
|
||||
"[&_.katex-display]:overflow-x-auto",
|
||||
"[&_.katex-display]:overflow-y-hidden",
|
||||
contentClassName,
|
||||
)}
|
||||
onMouseUp={onClick}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
<MemoMarkdown
|
||||
editorRef={setEditor}
|
||||
value={content}
|
||||
onChange={onTaskToggle}
|
||||
taskToggle={Boolean(onTaskToggle)}
|
||||
toolbar={false}
|
||||
slashMenu={false}
|
||||
attachments={attachments}
|
||||
extensions={linkCards}
|
||||
headingIds={headingSlugs}
|
||||
onLinkClick={handleLinkClick}
|
||||
// Tags filter the list when clicked here; mentions of people who exist open their page.
|
||||
onTagClick={navigateToTag}
|
||||
onMentionClick={(username) => navigate(getCreatorHomePath(username))}
|
||||
className="memo-content-root"
|
||||
/>
|
||||
{cards.map((card) => createPortal(<LinkPreview href={card.href} />, card.element, String(card.key)))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const MemoContentView = memo(MemoContentViewImpl);
|
||||
@@ -0,0 +1,46 @@
|
||||
import { type Block, type Extension, inlineText } from "@usememos/editor";
|
||||
|
||||
/** The URL a paragraph consists of, when it is nothing but one bare web link: `https://…` written as its own text. */
|
||||
export function bareLinkOf(block: Block): string | undefined {
|
||||
if (block.type !== "paragraph" || block.content.length === 0) return undefined;
|
||||
const href = block.content[0].link;
|
||||
// Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
|
||||
if (!href || !/^https?:\/\//i.test(href)) return undefined;
|
||||
// A titled link is a written `[text](url "title")`, never a bare URL; a card would drop its title.
|
||||
if (!block.content.every((span) => span.link === href && !span.linkTitle && !span.image)) return undefined;
|
||||
return inlineText(block.content) === href ? href : undefined;
|
||||
}
|
||||
|
||||
/** A card's place in the editor: the element the editor owns for the block, and the link it shows. */
|
||||
export interface LinkCardMount {
|
||||
readonly element: HTMLElement;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface LinkCardsHooks {
|
||||
/** Read when the editor draws a block; `editor.refreshViews("linkCards")` applies a change. */
|
||||
isEnabled: () => boolean;
|
||||
/** The editor has an element for a bare-link paragraph; the host mounts its card into it. */
|
||||
onMount: (mount: LinkCardMount) => void;
|
||||
/** The editor let the element go: the block was removed or changed, or the view was refreshed. */
|
||||
onUnmount: (element: HTMLElement) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The link preview cards, as the editor's own block view: a paragraph that is one bare
|
||||
* web link is drawn by the host, which needs the page's details from the memos server.
|
||||
* The editor keeps the element while the block is unchanged, so the card the host mounts
|
||||
* into it (a React portal) survives renders, and calls `onUnmount` when it lets it go.
|
||||
*/
|
||||
export const linkCardsExtension = (hooks: LinkCardsHooks): Extension => ({
|
||||
name: "linkCards",
|
||||
blockView: {
|
||||
match: (block) => hooks.isEnabled() && bareLinkOf(block) !== undefined,
|
||||
render: (block, element) => {
|
||||
const href = bareLinkOf(block);
|
||||
if (!href) return false;
|
||||
hooks.onMount({ element, href });
|
||||
return () => hooks.onUnmount(element);
|
||||
},
|
||||
},
|
||||
});
|
||||
+1
-1
@@ -1,8 +1,8 @@
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { isMemoResourcePath, withMemoFilter } from "@/components/MemoView/navigation";
|
||||
import { type MemoFilter, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import { Routes } from "@/router";
|
||||
import { isMemoResourcePath, withMemoFilter } from "../MemoView/navigation";
|
||||
|
||||
/**
|
||||
* What clicking a tag in a memo does. On a memo detail page it opens the collection the
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { type FC, type MouseEvent, useMemo, useRef, useState } from "react";
|
||||
import type { AttachmentItem, LocalFile } from "@/components/MemoEditor/types/attachment";
|
||||
import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/types/attachment";
|
||||
import type { AttachmentItem, LocalFile } from "@/components/MemoEditor/edit/types/attachment";
|
||||
import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/edit/types/attachment";
|
||||
import MetadataSection, {
|
||||
METADATA_ROW_BOX_CLASSES,
|
||||
METADATA_ROW_CONTROLS_CLASSES,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LocationState } from "@/components/MemoEditor/types/insertMenu";
|
||||
import type { LocationState } from "@/components/MemoEditor/edit/types/insertMenu";
|
||||
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
|
||||
import type { MapPoint } from "@/components/map/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import MemoEditor from "@/components/MemoEditor";
|
||||
import type { MemoEditorProps } from "@/components/MemoEditor/types/components";
|
||||
import { type MemoDraftSeed, MemoEditor } from "@/components/MemoEditor";
|
||||
import MemoView from "@/components/MemoView";
|
||||
import type { MemoTimeDisplay } from "@/components/MemoView/types";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
|
||||
import { NewMemoProvider } from "@/contexts/NewMemoContext";
|
||||
import { useSpaceContext } from "@/contexts/SpaceContext";
|
||||
import { useView } from "@/contexts/ViewContext";
|
||||
@@ -18,11 +17,12 @@ import { useTranslate } from "@/utils/i18n";
|
||||
const COMPOSE_ROW_CLASS = cn(buttonVariants({ variant: "quiet", size: "sm" }), "self-start");
|
||||
|
||||
export interface MemoPanelCompose {
|
||||
cacheKey: string;
|
||||
/** Where the new memo is composed, such as `calendar:<date>`; each scope keeps its own draft. */
|
||||
scope: string;
|
||||
/** The quiet row's label, e.g. "New memo on this day". */
|
||||
label: string;
|
||||
/** What the new memo inherits from the selection: its day, its place. */
|
||||
defaults?: Pick<MemoEditorProps, "defaultCreateTime" | "defaultLocation">;
|
||||
defaults?: Pick<MemoDraftSeed, "createTime" | "location">;
|
||||
/** Whether the editor is open in place of the row, for hosts whose own gestures could dismiss it. */
|
||||
onComposingChange?: (composing: boolean) => void;
|
||||
onSavingChange?: (saving: boolean) => void;
|
||||
@@ -94,11 +94,9 @@ export function MemoPanelList({ memos, selectionKey, timeDisplay, emptyText, com
|
||||
isUserSettingsInitialized &&
|
||||
(composing ? (
|
||||
<MemoEditor
|
||||
cacheKey={compose.cacheKey}
|
||||
draft={{ scope: compose.scope, space: selectedSpaceName, ...compose.defaults }}
|
||||
autoFocus
|
||||
placeholder={t("editor.any-thoughts")}
|
||||
defaultSpace={selectedSpaceName}
|
||||
{...compose.defaults}
|
||||
onSavingChange={compose.onSavingChange}
|
||||
onConfirm={(name) => {
|
||||
setComposingFor(undefined);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { create } from "@bufbuild/protobuf";
|
||||
import { FileIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { MemoContentView } from "@/components/MemoEditor/view/MemoContentView";
|
||||
import { extractMemoIdFromName } from "@/lib/resource-names";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
|
||||
@@ -9,7 +10,6 @@ import type { User } from "@/types/proto/api/user_service_pb";
|
||||
import { getAttachmentType, isMotionAttachment } from "@/utils/attachment";
|
||||
import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
|
||||
import { buildAttachmentVisualItems, countLogicalAttachmentItems } from "@/utils/media-item";
|
||||
import MemoContent from "../MemoContent";
|
||||
import { MemoViewContext, type MemoViewContextValue } from "../MemoView/MemoViewContext";
|
||||
|
||||
interface MemoPreviewProps {
|
||||
@@ -34,7 +34,10 @@ const STUB_CONTEXT: MemoViewContextValue = {
|
||||
readonly: true,
|
||||
showBlurredContent: false,
|
||||
blurred: false,
|
||||
isEditing: false,
|
||||
openEditor: () => {},
|
||||
closeEditor: () => {},
|
||||
onEditorFocusModeChange: () => {},
|
||||
toggleBlurVisibility: () => {},
|
||||
openPreview: () => {},
|
||||
};
|
||||
@@ -134,7 +137,7 @@ const MemoPreview = ({
|
||||
// interactive clamp a full memo card gets.
|
||||
hasContent && (
|
||||
<div className="max-h-36 w-full overflow-hidden">
|
||||
<MemoContent content={content} attachments={attachments} compact={compact} />
|
||||
<MemoContentView content={content} attachments={attachments} compact={compact} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useMemo } from "react";
|
||||
import { useResolvedUsersByNames } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import { memoServiceClient } from "@/connect";
|
||||
import { useResolvedUsersByNames } from "@/contexts/MentionResolutionContext";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import { memoKeys } from "@/hooks/useMemoQueries";
|
||||
import type { Memo, Reaction } from "@/types/proto/api/memo_service_pb";
|
||||
|
||||
@@ -1,22 +1,8 @@
|
||||
import {
|
||||
type ComponentType,
|
||||
forwardRef,
|
||||
memo,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { forwardRef, memo, Suspense, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useColumnGridUntrapped } from "@/components/ColumnGrid/ColumnGridContext";
|
||||
import { useResolvedUser } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import { loadMemoEditor } from "@/components/MemoEditor/loader";
|
||||
import type { MemoEditorProps } from "@/components/MemoEditor/types";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useResolvedUser } from "@/contexts/MentionResolutionContext";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import { isMemoBlurred } from "@/lib/tag";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -47,8 +33,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
showSpace,
|
||||
} = props;
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
const [showEditor, setShowEditor] = useState(false);
|
||||
const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [cardWidth, setCardWidth] = useState(0);
|
||||
|
||||
const currentUser = useCurrentUser();
|
||||
@@ -70,27 +55,23 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
const toggleBlurVisibility = useCallback(() => setShowBlurredContent((prev) => !prev), []);
|
||||
|
||||
const { previewState, openPreview, setPreviewOpen } = useImagePreview();
|
||||
const editorHostRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const focusMountedEditor = useCallback(() => {
|
||||
const editorRoot = editorHostRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
|
||||
const fallbackInput = editorHostRef.current?.querySelector<HTMLElement>("textarea, input");
|
||||
const editorRoot = cardRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
|
||||
const fallbackInput = cardRef.current?.querySelector<HTMLElement>("textarea, input");
|
||||
(editorRoot ?? fallbackInput)?.focus();
|
||||
}, []);
|
||||
|
||||
// The body edits in place: the card, its header and its frame stay, and the memo's
|
||||
// own editing session takes the body's place until it saves or cancels.
|
||||
const openEditor = useCallback(() => {
|
||||
if (showEditor && EditorComponent) {
|
||||
if (isEditing) {
|
||||
focusMountedEditor();
|
||||
return;
|
||||
}
|
||||
void loadMemoEditor()
|
||||
.then(({ default: MemoEditor }) => {
|
||||
setEditorComponent(() => MemoEditor);
|
||||
setShowEditor(true);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [EditorComponent, focusMountedEditor, showEditor]);
|
||||
const closeEditor = useCallback(() => setShowEditor(false), []);
|
||||
setIsEditing(true);
|
||||
}, [focusMountedEditor, isEditing]);
|
||||
const closeEditor = useCallback(() => setIsEditing(false), []);
|
||||
|
||||
// The grid keys tiles by memo name (see getMemoKey), so the focused editor
|
||||
// identifies its own tile by name and untraps it for the duration.
|
||||
@@ -108,10 +89,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
// Release the slot when the editor closes or this card unmounts. Both calls
|
||||
// are ownership-scoped, so mounting cards never clobber another card's slot.
|
||||
useEffect(() => {
|
||||
if (!showEditor) {
|
||||
if (!isEditing) {
|
||||
clearUntrappedKey(memoData.name);
|
||||
}
|
||||
}, [showEditor, memoData.name, clearUntrappedKey]);
|
||||
}, [isEditing, memoData.name, clearUntrappedKey]);
|
||||
useEffect(() => () => clearUntrappedKey(memoData.name), [memoData.name, clearUntrappedKey]);
|
||||
|
||||
useImperativeHandle(ref, () => ({ openEditor }), [openEditor]);
|
||||
@@ -163,7 +144,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
readonly,
|
||||
showBlurredContent,
|
||||
blurred,
|
||||
isEditing,
|
||||
openEditor,
|
||||
closeEditor,
|
||||
onEditorFocusModeChange: handleFocusModeChange,
|
||||
toggleBlurVisibility,
|
||||
openPreview,
|
||||
}),
|
||||
@@ -177,7 +161,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
readonly,
|
||||
showBlurredContent,
|
||||
blurred,
|
||||
isEditing,
|
||||
openEditor,
|
||||
closeEditor,
|
||||
handleFocusModeChange,
|
||||
toggleBlurVisibility,
|
||||
openPreview,
|
||||
],
|
||||
@@ -222,26 +209,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
|
||||
article
|
||||
);
|
||||
|
||||
return (
|
||||
<MemoViewContext.Provider value={contextValue}>
|
||||
{showEditor && EditorComponent ? (
|
||||
<div ref={editorHostRef} className="w-full">
|
||||
<EditorComponent
|
||||
autoFocus
|
||||
className="mb-2"
|
||||
cacheKey={`inline-memo-editor-${memoData.name}`}
|
||||
memo={memoData}
|
||||
parentMemoName={memoData.parent || undefined}
|
||||
onConfirm={closeEditor}
|
||||
onCancel={closeEditor}
|
||||
onFocusModeChange={handleFocusModeChange}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
memoDisplay
|
||||
)}
|
||||
</MemoViewContext.Provider>
|
||||
);
|
||||
return <MemoViewContext.Provider value={contextValue}>{memoDisplay}</MemoViewContext.Provider>;
|
||||
});
|
||||
|
||||
MemoView.displayName = "MemoView";
|
||||
|
||||
@@ -19,7 +19,12 @@ export interface MemoViewContextValue {
|
||||
readonly: boolean;
|
||||
showBlurredContent: boolean;
|
||||
blurred: boolean;
|
||||
/** Whether the card shows the memo's editing session in place of its body. */
|
||||
isEditing: boolean;
|
||||
openEditor: () => void;
|
||||
closeEditor: () => void;
|
||||
/** The session reports focus mode so the card's layout can let it take the viewport. */
|
||||
onEditorFocusModeChange: (isFocusMode: boolean) => void;
|
||||
toggleBlurVisibility: () => void;
|
||||
openPreview: (items: string | string[] | PreviewMediaItem[], index?: number) => void;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { EyeIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import ClampedSection from "@/components/ClampedSection";
|
||||
import { MemoEditor } from "@/components/MemoEditor/MemoEditor";
|
||||
import { AttachmentGallery, MemoMetadataRows } from "@/components/MemoMetadata";
|
||||
import { separateAttachments } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
|
||||
import { isReferenceRelation } from "@/components/MemoMetadata/Relation/relationHelpers";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useUpdateMemo } from "@/hooks/useMemoQueries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
|
||||
import MemoContent from "../../MemoContent";
|
||||
import { MemoReactionListView } from "../../MemoReactionListView";
|
||||
import { useMemoHandlers } from "../hooks";
|
||||
import { useMemoViewContext } from "../MemoViewContext";
|
||||
@@ -28,12 +27,21 @@ const BlurOverlay: React.FC<{ onClick?: () => void }> = ({ onClick }) => {
|
||||
};
|
||||
|
||||
const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
|
||||
const { memo, parentPage, showBlurredContent, blurred, readonly, openEditor, openPreview, toggleBlurVisibility } = useMemoViewContext();
|
||||
const {
|
||||
memo,
|
||||
parentPage,
|
||||
showBlurredContent,
|
||||
blurred,
|
||||
readonly,
|
||||
isEditing,
|
||||
openEditor,
|
||||
closeEditor,
|
||||
onEditorFocusModeChange,
|
||||
openPreview,
|
||||
toggleBlurVisibility,
|
||||
} = useMemoViewContext();
|
||||
|
||||
const { handleMemoContentClick, handleMemoContentDoubleClick } = useMemoHandlers({ readonly, openEditor, openPreview });
|
||||
const { mutate: updateMemo } = useUpdateMemo();
|
||||
const handleTaskToggle = (content: string) =>
|
||||
updateMemo({ update: { name: memo.name, content }, updateMask: ["content", "update_time"] });
|
||||
|
||||
const referencedMemos = memo.relations.filter(isReferenceRelation);
|
||||
// Memoized so AttachmentListView's own useMemo chain keeps its cache across body renders.
|
||||
@@ -43,6 +51,24 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
|
||||
);
|
||||
const { visual, audio, docs } = useMemo(() => separateAttachments(attachmentOnlyItems), [attachmentOnlyItems]);
|
||||
|
||||
// Editing takes the body's place inside the card's own frame: the session brings its
|
||||
// attachments, metadata and toolbar, so the read-only rows and reactions step aside.
|
||||
if (isEditing) {
|
||||
return (
|
||||
<div data-slot="memo-body" className="w-full">
|
||||
<MemoEditor
|
||||
mode="edit"
|
||||
name={memo.name}
|
||||
frameless
|
||||
autoFocus
|
||||
onConfirm={closeEditor}
|
||||
onCancel={closeEditor}
|
||||
onFocusModeChange={onEditorFocusModeChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-start items-start gap-2">
|
||||
<div data-slot="memo-body" className="relative w-full">
|
||||
@@ -55,15 +81,12 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
|
||||
{/* Compact bounds the whole body — attachments included — behind one Show more.
|
||||
Reactions stay outside so they never hide under the fade. */}
|
||||
<ClampedSection enabled={Boolean(compact)}>
|
||||
<MemoContent
|
||||
memoName={memo.name}
|
||||
<MemoEditor
|
||||
name={memo.name}
|
||||
parentPage={parentPage}
|
||||
content={memo.content}
|
||||
attachments={memo.attachments}
|
||||
compact={Boolean(compact)}
|
||||
onClick={handleMemoContentClick}
|
||||
onDoubleClick={handleMemoContentDoubleClick}
|
||||
onTaskToggle={readonly ? undefined : handleTaskToggle}
|
||||
compact={Boolean(compact)}
|
||||
/>
|
||||
<AttachmentGallery visual={visual} onImagePreview={openPreview} />
|
||||
<MemoMetadataRows
|
||||
|
||||
@@ -27,7 +27,7 @@ const MEMO_HEADER_ACTION_CLASSES = cn(buttonVariants({ variant: "quiet", size: "
|
||||
const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showCreator, showVisibility, showSpace }) => {
|
||||
const t = useTranslate();
|
||||
|
||||
const { memo, creator, currentUser, parentPage, isArchived, readonly, openEditor } = useMemoViewContext();
|
||||
const { memo, creator, currentUser, parentPage, isArchived, readonly, isEditing, openEditor } = useMemoViewContext();
|
||||
const location = useLocation();
|
||||
const { createTime, updateTime, displayTime: memoDisplayTime, isDisplayingUpdatedTime, relativeTimeFormat } = useMemoViewDerived();
|
||||
const { newMemoName } = useNewMemo();
|
||||
@@ -55,6 +55,24 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
|
||||
: undefined,
|
||||
};
|
||||
const spaceMetadata = showSpace && memo.space ? <MemoSpaceBadge spaceName={memo.space} /> : null;
|
||||
const showsCreator = Boolean(showCreator && creator);
|
||||
const isNew = memo.name === newMemoName;
|
||||
|
||||
// While the card edits in place, the header keeps only identity. The time, visibility
|
||||
// and Space show once, in their editable form, in the session below (its timestamp row
|
||||
// and audience menu); reacting or opening the action menu makes no sense mid-edit, and
|
||||
// the "new" mark is for finding the memo in the list, not for the person editing it.
|
||||
// With no identity to show, the row goes and the session's timestamp row takes its place.
|
||||
if (isEditing) {
|
||||
if (!showsCreator || !creator) return null;
|
||||
return (
|
||||
<div className="flex h-6 w-full items-center gap-2">
|
||||
<div data-slot="memo-header-meta" className="flex min-w-0 items-center gap-1.5 overflow-hidden">
|
||||
<CreatorDisplay creator={creator} withSeparator={false} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
// A fixed 24px row, the height of its action squares, so the card's top edge never
|
||||
@@ -63,7 +81,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
{/* The time stays visible while the creator and Space badge can shrink and truncate. */}
|
||||
<div data-slot="memo-header-meta" className="flex min-w-0 items-center gap-1.5 overflow-hidden">
|
||||
{showCreator && creator && <CreatorDisplay creator={creator} />}
|
||||
{showsCreator && creator && <CreatorDisplay creator={creator} />}
|
||||
<TimeDisplay
|
||||
displayTime={displayTime}
|
||||
timeTooltip={timeTooltip}
|
||||
@@ -73,11 +91,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
|
||||
/>
|
||||
{spaceMetadata}
|
||||
</div>
|
||||
{memo.name === newMemoName && (
|
||||
<span className="shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium leading-none text-primary">
|
||||
{t("memo.new-badge")}
|
||||
</span>
|
||||
)}
|
||||
{isNew && <NewBadge />}
|
||||
</div>
|
||||
|
||||
<div data-slot="memo-header-actions" className="flex shrink-0 select-none flex-row items-center justify-end gap-1">
|
||||
@@ -103,12 +117,21 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
|
||||
);
|
||||
};
|
||||
|
||||
const NewBadge = () => {
|
||||
const t = useTranslate();
|
||||
return (
|
||||
<span className="shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium leading-none text-primary">
|
||||
{t("memo.new-badge")}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* The author on one line with the time: a 20px avatar in a 20px slot, then the name in
|
||||
* medium 13px foreground ink. It is the identity, so it carries the weight; the time after
|
||||
* it is muted.
|
||||
* it is muted, and the separator before it goes when nothing follows.
|
||||
*/
|
||||
const CreatorDisplay: React.FC<{ creator: User }> = ({ creator }) => (
|
||||
const CreatorDisplay: React.FC<{ creator: User; withSeparator?: boolean }> = ({ creator, withSeparator = true }) => (
|
||||
<>
|
||||
<Link
|
||||
className={cn(
|
||||
@@ -123,9 +146,11 @@ const CreatorDisplay: React.FC<{ creator: User }> = ({ creator }) => (
|
||||
</span>
|
||||
<span className="min-w-0 truncate">{creator.displayName || creator.username}</span>
|
||||
</Link>
|
||||
<span aria-hidden="true" className="shrink-0 text-muted-foreground/40">
|
||||
·
|
||||
</span>
|
||||
{withSeparator && (
|
||||
<span aria-hidden="true" className="shrink-0 text-muted-foreground/40">
|
||||
·
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ArrowUpIcon, LoaderCircleIcon } from "lucide-react";
|
||||
import { type ReactElement, type ReactNode, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAppSidebar } from "@/contexts/AppSidebarContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { isSearchFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
|
||||
import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
|
||||
import { useNewMemo } from "@/contexts/NewMemoContext";
|
||||
import { useView } from "@/contexts/ViewContext";
|
||||
import { useDelayedFlag } from "@/hooks/useDelayedFlag";
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
|
||||
import { type ComponentType, createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { getSidebarRouteKind } from "@/components/AppSidebar/routes";
|
||||
import { loadMemoEditor } from "@/components/MemoEditor/loader";
|
||||
import type { MemoEditorProps } from "@/components/MemoEditor/types";
|
||||
import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
|
||||
import { VisuallyHidden } from "@/components/ui/visually-hidden";
|
||||
import { useAppSidebar } from "@/contexts/AppSidebarContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
@@ -11,7 +10,6 @@ import { useSpaceContext } from "@/contexts/SpaceContext";
|
||||
import useCurrentUser from "@/hooks/useCurrentUser";
|
||||
import useMediaQuery from "@/hooks/useMediaQuery";
|
||||
import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
|
||||
import { spaceScopedCacheKey } from "@/lib/resource-names";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
|
||||
interface GlobalMemoEditorContextValue {
|
||||
@@ -55,12 +53,10 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
|
||||
// signing out closes the composer in the same render and a different user signing
|
||||
// in cannot resurrect it, and pinned to the Space that was selected at that moment.
|
||||
const [opened, setOpened] = useState<{ user: string; space?: string }>();
|
||||
const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
|
||||
// Only ever read from event handlers, so a ref keeps each save from
|
||||
// re-rendering the provider and the whole editor tree it hosts.
|
||||
const isSavingRef = useRef(false);
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null);
|
||||
const openRequestVersionRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -83,7 +79,6 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
|
||||
}, []);
|
||||
|
||||
const closeEditor = useCallback(() => {
|
||||
openRequestVersionRef.current += 1;
|
||||
isSavingRef.current = false;
|
||||
setOpened(undefined);
|
||||
}, []);
|
||||
@@ -106,18 +101,13 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
|
||||
setMobileOpen(false);
|
||||
setQuickFindOpen(false);
|
||||
|
||||
const requestVersion = ++openRequestVersionRef.current;
|
||||
isSavingRef.current = false;
|
||||
const activeElement = document.activeElement;
|
||||
returnFocusRef.current = activeElement instanceof HTMLElement && activeElement !== document.body ? activeElement : null;
|
||||
|
||||
void loadMemoEditor()
|
||||
.then(({ default: MemoEditor }) => {
|
||||
if (openRequestVersionRef.current !== requestVersion) return;
|
||||
setEditorComponent(() => MemoEditor);
|
||||
setOpened({ user: currentUserName, space: selectedSpaceName });
|
||||
})
|
||||
.catch(() => undefined);
|
||||
// The dialog opens at once; the editor fills it as soon as its code is here.
|
||||
preloadMemoEditing();
|
||||
setOpened({ user: currentUserName, space: selectedSpaceName });
|
||||
}, [canOpen, selectedSpaceName, currentUserName, setMobileOpen, setQuickFindOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -158,7 +148,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
|
||||
}
|
||||
}}
|
||||
>
|
||||
{EditorComponent && (
|
||||
{editorIsOpen && (
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Backdrop className="fixed inset-0 z-overlay bg-transparent" />
|
||||
<DialogPrimitive.Popup
|
||||
@@ -170,10 +160,9 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
|
||||
<VisuallyHidden>
|
||||
<DialogPrimitive.Title>{t("editor.new-memo")}</DialogPrimitive.Title>
|
||||
</VisuallyHidden>
|
||||
<EditorComponent
|
||||
<MemoEditor
|
||||
autoFocus
|
||||
cacheKey={spaceScopedCacheKey("global-memo-editor", opened?.space)}
|
||||
defaultSpace={opened?.space}
|
||||
draft={{ scope: "global", space: opened?.space }}
|
||||
suggestions={suggestions}
|
||||
placeholder={t("editor.any-thoughts")}
|
||||
onConfirm={closeEditor}
|
||||
|
||||
+15
-14
@@ -1,5 +1,5 @@
|
||||
import { useQueries } from "@tanstack/react-query";
|
||||
import { createContext, type ReactNode, useContext, useMemo } from "react";
|
||||
import { createContext, type ReactNode, useContext, useMemo, useRef } from "react";
|
||||
import { userDetailQueryOptions, useUsersByUsernames } from "@/hooks/useUserQueries";
|
||||
import { extractMentionUsernames } from "@/lib/memo-markdown";
|
||||
import { extractUsernameFromName } from "@/lib/resource-names";
|
||||
@@ -57,23 +57,24 @@ export const MentionResolutionProvider = ({ contents, userNames = EMPTY_USER_NAM
|
||||
|
||||
export function useResolvedMentionUsernames(content: string) {
|
||||
const sharedResolution = useContext(UserResolutionContext);
|
||||
const shouldUseSharedResolution = sharedResolution !== null;
|
||||
const usernames = useMemo(
|
||||
() => sharedResolution?.mentionUsernamesByContent.get(content) ?? extractMentionUsernames(content),
|
||||
[content, sharedResolution],
|
||||
);
|
||||
const { data: mentionUsers } = useUsersByUsernames(usernames, { enabled: !shouldUseSharedResolution });
|
||||
// The provider resolves only the contents it was given; a draft in the composer, or a
|
||||
// memo outside its list, looks its own mentions up.
|
||||
const shared = sharedResolution?.mentionUsernamesByContent.has(content) ? sharedResolution : null;
|
||||
const usernames = useMemo(() => shared?.mentionUsernamesByContent.get(content) ?? extractMentionUsernames(content), [content, shared]);
|
||||
const { data: mentionUsers } = useUsersByUsernames(usernames, { enabled: shared === null });
|
||||
// Until a lookup answers, the people already found stay found: a name typed next to a
|
||||
// resolved mention must not unresolve it for the length of a request.
|
||||
const lastAnswer = useRef(new Set<string>());
|
||||
|
||||
return useMemo(() => {
|
||||
if (sharedResolution) {
|
||||
return new Set(usernames.filter((username) => sharedResolution.resolvedMentionUsernames.has(username)));
|
||||
if (shared) {
|
||||
return new Set(usernames.filter((username) => shared.resolvedMentionUsernames.has(username)));
|
||||
}
|
||||
if (!mentionUsers) {
|
||||
return new Set<string>();
|
||||
if (mentionUsers) {
|
||||
lastAnswer.current = new Set(Array.from(mentionUsers.entries()).flatMap(([username, user]) => (user ? [username] : [])));
|
||||
}
|
||||
|
||||
return new Set(Array.from(mentionUsers.entries()).flatMap(([username, user]) => (user ? [username] : [])));
|
||||
}, [mentionUsers, sharedResolution, usernames]);
|
||||
return lastAnswer.current;
|
||||
}, [mentionUsers, shared, usernames]);
|
||||
}
|
||||
|
||||
export function useResolvedUser(name: string, options?: { enabled?: boolean }) {
|
||||
+150
-75
@@ -10,8 +10,10 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { memoServiceClient } from "@/connect";
|
||||
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
|
||||
import { memoShareKeys } from "@/hooks/useMemoShareQueries";
|
||||
import { userKeys } from "@/hooks/useUserQueries";
|
||||
import { DEFAULT_LIST_MEMOS_PAGE_SIZE } from "@/lib/constants";
|
||||
import { shouldRetry } from "@/lib/query-client";
|
||||
@@ -58,112 +60,181 @@ function discardUnavailableMemo(client: QueryClient, name: string) {
|
||||
const relations = memo.relations.filter((relation) => relation.memo?.name !== name && relation.relatedMemo?.name !== name);
|
||||
return relations.length === memo.relations.length ? memo : { ...memo, relations };
|
||||
};
|
||||
const stripList = (data: ListMemosResponse): ListMemosResponse => {
|
||||
const memos = data.memos.filter((memo) => memo.name !== name).map(stripRelations);
|
||||
return memos.length === data.memos.length && memos.every((memo, index) => memo === data.memos[index]) ? data : { ...data, memos };
|
||||
};
|
||||
for (const [key, data] of client.getQueriesData<MemoCollectionQueryData | Memo | null>({ queryKey: memoKeys.all })) {
|
||||
let next = data;
|
||||
if (isMemoListResponse(data)) next = stripList(data);
|
||||
else if (isInfiniteMemoListData(data)) {
|
||||
const pages = data.pages.map(stripList);
|
||||
if (pages.some((page, index) => page !== data.pages[index])) next = { ...data, pages };
|
||||
} else if (key[1] === "detail" && data && "name" in data && data.name !== name) next = stripRelations(data);
|
||||
for (const [key, data] of client.getQueriesData<unknown>({ queryKey: memoKeys.all })) {
|
||||
let next: unknown;
|
||||
if (isMemo(data)) next = data.name === name ? data : stripRelations(data);
|
||||
else next = mapMemoCollection(data, (memos) => filterMemos(memos, (memo) => memo.name !== name, stripRelations));
|
||||
if (next !== data) client.setQueryData(key, next);
|
||||
}
|
||||
}
|
||||
|
||||
type MemoPatch = Partial<Memo> & Pick<Memo, "name">;
|
||||
type MemoCollectionQueryData = ListMemosResponse | InfiniteData<ListMemosResponse>;
|
||||
|
||||
// The shapes a memo query holds: a memo list response (`memos`), a comment list
|
||||
// response (`comments`), a bare array (the calendar month), the infinite-query
|
||||
// pages of either response, or one memo (a detail or a shared memo).
|
||||
|
||||
function isMemo(data: unknown): data is Memo {
|
||||
return typeof data === "object" && data !== null && typeof (data as { name?: unknown }).name === "string" && "content" in data;
|
||||
}
|
||||
|
||||
function isMemoListResponse(data: unknown): data is ListMemosResponse {
|
||||
return typeof data === "object" && data !== null && Array.isArray((data as { memos?: unknown }).memos);
|
||||
}
|
||||
|
||||
function isInfiniteMemoListData(data: unknown): data is InfiniteData<ListMemosResponse> {
|
||||
function isMemoCommentsResponse(data: unknown): data is { comments: Memo[] } {
|
||||
return typeof data === "object" && data !== null && Array.isArray((data as { comments?: unknown }).comments);
|
||||
}
|
||||
|
||||
function isInfiniteData(data: unknown): data is InfiniteData<unknown> {
|
||||
return typeof data === "object" && data !== null && Array.isArray((data as { pages?: unknown }).pages);
|
||||
}
|
||||
|
||||
function patchMemoListResponse(response: ListMemosResponse, update: MemoPatch): ListMemosResponse {
|
||||
let changed = false;
|
||||
const memos = response.memos.map((memo) => {
|
||||
if (memo.name !== update.name) {
|
||||
return memo;
|
||||
}
|
||||
function memosOfPage(page: unknown): Memo[] | undefined {
|
||||
if (Array.isArray(page)) return page as Memo[];
|
||||
if (isMemoListResponse(page)) return page.memos;
|
||||
if (isMemoCommentsResponse(page)) return page.comments;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Replaces a page's memos, keeping the page's reference when the memos did not change. */
|
||||
function withMemos<T>(page: T, memos: Memo[]): T {
|
||||
if (memosOfPage(page) === memos) return page;
|
||||
if (Array.isArray(page)) return memos as T;
|
||||
if (isMemoListResponse(page)) return { ...page, memos } as T;
|
||||
return { ...(page as object), comments: memos } as T;
|
||||
}
|
||||
|
||||
/** Maps every page of memos in a collection query, keeping references where nothing changed. */
|
||||
function mapMemoCollection<T>(data: T, map: (memos: Memo[]) => Memo[]): T {
|
||||
if (isInfiniteData(data)) {
|
||||
const pages = data.pages.map((page) => mapMemoCollection(page, map));
|
||||
return pages.some((page, index) => page !== data.pages[index]) ? ({ ...data, pages } as T) : data;
|
||||
}
|
||||
const memos = memosOfPage(data);
|
||||
return memos ? withMemos(data, map(memos)) : data;
|
||||
}
|
||||
|
||||
function filterMemos(memos: Memo[], keep: (memo: Memo) => boolean, map: (memo: Memo) => Memo = (memo) => memo): Memo[] {
|
||||
const next = memos.filter(keep).map(map);
|
||||
return next.length === memos.length && next.every((memo, index) => memo === memos[index]) ? memos : next;
|
||||
}
|
||||
|
||||
function patchMemos(memos: Memo[], update: MemoPatch): Memo[] {
|
||||
let changed = false;
|
||||
const next = memos.map((memo) => {
|
||||
if (memo.name !== update.name) return memo;
|
||||
changed = true;
|
||||
return { ...memo, ...update };
|
||||
});
|
||||
|
||||
return changed ? { ...response, memos } : response;
|
||||
return changed ? next : memos;
|
||||
}
|
||||
|
||||
function patchMemoListQueryData<T>(data: T | undefined, update: MemoPatch): T | undefined {
|
||||
if (!data) {
|
||||
return data;
|
||||
function* memosInQueryData(data: unknown): Generator<Memo> {
|
||||
if (isMemo(data)) {
|
||||
yield data;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isMemoListResponse(data)) {
|
||||
return patchMemoListResponse(data, update) as T;
|
||||
const pages = isInfiniteData(data) ? data.pages : [data];
|
||||
for (const page of pages) {
|
||||
const memos = memosOfPage(page);
|
||||
if (memos) yield* memos;
|
||||
}
|
||||
|
||||
if (isInfiniteMemoListData(data)) {
|
||||
let changed = false;
|
||||
const pages = data.pages.map((page) => {
|
||||
const patchedPage = patchMemoListResponse(page, update);
|
||||
if (patchedPage !== page) {
|
||||
changed = true;
|
||||
}
|
||||
return patchedPage;
|
||||
});
|
||||
|
||||
return (changed ? { ...data, pages } : data) as T;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function findMemoInListResponse(response: ListMemosResponse, name: string): Memo | undefined {
|
||||
return response.memos.find((memo) => memo.name === name);
|
||||
}
|
||||
|
||||
function findMemoInQueryData(data: unknown, name: string): Memo | undefined {
|
||||
if (!data) {
|
||||
return undefined;
|
||||
for (const memo of memosInQueryData(data)) {
|
||||
if (memo.name === name) return memo;
|
||||
}
|
||||
|
||||
if (isMemoListResponse(data)) {
|
||||
return findMemoInListResponse(data, name);
|
||||
}
|
||||
|
||||
if (isInfiniteMemoListData(data)) {
|
||||
for (const page of data.pages) {
|
||||
const memo = findMemoInListResponse(page, name);
|
||||
if (memo) {
|
||||
return memo;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The query roots that hold memos: the memo queries, and shared memos under their tokens. */
|
||||
const MEMO_QUERY_ROOTS = [memoKeys.all, memoShareKeys.all] as const;
|
||||
|
||||
/**
|
||||
* Looks a memo up by name in the collections already fetched (lists, comments,
|
||||
* the calendar month): a seed for a detail query that would otherwise refetch
|
||||
* a memo the page already shows. A detail cached as unavailable (`null`) wins.
|
||||
*/
|
||||
export function findMemoInCollectionQueries(queryClient: QueryClient, name: string, freshOnly = false): Memo | undefined {
|
||||
if (queryClient.getQueryData(memoKeys.detail(name)) === null) return undefined;
|
||||
for (const [key, data] of queryClient.getQueriesData<unknown>({ queryKey: memoKeys.all })) {
|
||||
if (isMemo(data)) continue;
|
||||
const state = queryClient.getQueryState(key);
|
||||
if (freshOnly && (!state || state.isInvalidated || state.dataUpdatedAt < Date.now() - 10_000)) continue;
|
||||
const memo = findMemoInQueryData(data, name);
|
||||
if (memo) {
|
||||
return memo;
|
||||
}
|
||||
if (memo) return memo;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The freshest copy of a memo any query holds, by name: a detail, a shared memo, or
|
||||
* an entry in a list, comment page or month. `null` when a detail query recorded it as
|
||||
* unavailable, `undefined` when no query holds it.
|
||||
*/
|
||||
export function findMemoRecord(queryClient: QueryClient, name: string): Memo | null | undefined {
|
||||
if (queryClient.getQueryData(memoKeys.detail(name)) === null) return null;
|
||||
let found: Memo | undefined;
|
||||
let foundAt = -1;
|
||||
for (const root of MEMO_QUERY_ROOTS) {
|
||||
for (const query of queryClient.getQueryCache().findAll({ queryKey: root })) {
|
||||
if (query.state.dataUpdatedAt <= foundAt) continue;
|
||||
const memo = findMemoInQueryData(query.state.data, name);
|
||||
if (memo) {
|
||||
found = memo;
|
||||
foundAt = query.state.dataUpdatedAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function patchMemoInCollectionQueries(queryClient: QueryClient, update: MemoPatch) {
|
||||
queryClient.setQueriesData<MemoCollectionQueryData>({ queryKey: memoKeys.all }, (data) => patchMemoListQueryData(data, update));
|
||||
queryClient.setQueriesData<unknown>({ queryKey: memoKeys.all }, (data: unknown) =>
|
||||
isMemo(data) ? data : mapMemoCollection(data, (memos) => patchMemos(memos, update)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A memo by name, read from whatever query already holds it, with no request of its
|
||||
* own: a card in a list reads the list's copy and follows the list's refetches and the
|
||||
* mutations' optimistic patches. Returns `null` for a memo recorded as unavailable and
|
||||
* `undefined` for one no query holds.
|
||||
*/
|
||||
export function useMemoRecord(name: string): Memo | null | undefined {
|
||||
const queryClient = useQueryClient();
|
||||
const subscribe = useCallback(
|
||||
(onChange: () => void) =>
|
||||
queryClient.getQueryCache().subscribe((event) => {
|
||||
const root = event.query.queryKey[0];
|
||||
if (MEMO_QUERY_ROOTS.some((key) => key[0] === root)) onChange();
|
||||
}),
|
||||
[queryClient],
|
||||
);
|
||||
const getSnapshot = useCallback(() => findMemoRecord(queryClient, name), [queryClient, name]);
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
||||
}
|
||||
|
||||
/**
|
||||
* A memo by name for a surface that shows it: the copy a query already holds, or else
|
||||
* one fetch of the detail. Unlike `useMemo`, it never refetches on its own, so a list
|
||||
* of cards costs no requests beyond the list's.
|
||||
*/
|
||||
export function useMemoByName(name: string, options?: { enabled?: boolean }) {
|
||||
const record = useMemoRecord(name);
|
||||
const query = useQuery({
|
||||
...memoDetailQueryOptions(name),
|
||||
enabled: (options?.enabled ?? true) && record === undefined,
|
||||
});
|
||||
const data = record ?? undefined;
|
||||
return {
|
||||
data,
|
||||
isUnavailable: record === null,
|
||||
isLoading: record === undefined && query.isLoading,
|
||||
error: record === undefined ? query.error : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function useMemos(request: Partial<ListMemosRequest> = {}) {
|
||||
@@ -229,20 +300,22 @@ export function useLinkMetadata(url: string, options?: { enabled?: boolean }) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates a memo, or a comment on `parent`; the server fills the comment's parent and relation. */
|
||||
export function useCreateMemo() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (memoToCreate: Memo) => {
|
||||
const memo = await memoServiceClient.createMemo({ memo: memoToCreate });
|
||||
return memo;
|
||||
mutationFn: async ({ memo, parent }: { memo: Memo; parent?: string }) => {
|
||||
return parent ? await memoServiceClient.createMemoComment({ parent, comment: memo }) : await memoServiceClient.createMemo({ memo });
|
||||
},
|
||||
onSuccess: (newMemo) => {
|
||||
// Invalidate memo lists to refetch
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
|
||||
// Add new memo to cache
|
||||
onSuccess: (newMemo, { parent }) => {
|
||||
queryClient.setQueryData(memoKeys.detail(newMemo.name), newMemo);
|
||||
// Invalidate user stats
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
|
||||
if (parent) {
|
||||
// The parent's comment list and its comment count.
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.comments(parent) });
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.detail(parent) });
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
|
||||
// Creating a memo can bind previously unlinked attachments.
|
||||
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
|
||||
@@ -302,7 +375,9 @@ export function useUpdateMemo() {
|
||||
// Invalidate lists to refresh
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
|
||||
if (updatedMemo.parent) {
|
||||
// The parent's comment list, and the parent itself, which carries the comment relation.
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.comments(updatedMemo.parent) });
|
||||
queryClient.invalidateQueries({ queryKey: memoKeys.detail(updatedMemo.parent) });
|
||||
}
|
||||
// Invalidate user stats
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
|
||||
|
||||
@@ -33,8 +33,8 @@ export const headingTypeClass = (level: HeadingLevel): string => headingTypeClas
|
||||
|
||||
/**
|
||||
* Tag pill styling for the memo view. Split into two tokens so the view can swap
|
||||
* `defaultColor` for a custom tag color (MemoContent/enhance.ts). The composer
|
||||
* colors tags as text instead (MemoEditor/Editor/editor.css).
|
||||
* `defaultColor` for a custom tag color (MemoEditor/view/MemoContentView.tsx). The composer
|
||||
* colors tags as text instead (MemoEditor/MemoMarkdown.tsx).
|
||||
*/
|
||||
export const tagStyles = {
|
||||
/** Shape, padding, and typography — always applied. */
|
||||
|
||||
@@ -204,9 +204,9 @@ export const memoMentionOptions = (isResolved: (username: string) => boolean): P
|
||||
|
||||
interface MemoExtensionOptions {
|
||||
/** `tags()` class and attributes, for the memo view's pills and colors. */
|
||||
readonly tags?: Pick<TagsOptions, "class" | "attributes">;
|
||||
readonly tags?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
|
||||
/** `mentions()` class and attributes, for links to the people who exist. */
|
||||
readonly mentions?: Pick<TagsOptions, "class" | "attributes">;
|
||||
readonly mentions?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -352,6 +352,9 @@ export const memoEditorLabels = (t: ReturnType<typeof useTranslate>): Partial<La
|
||||
alignRight: t("editor.blocks.align-right"),
|
||||
tableSection: t("editor.blocks.table"),
|
||||
imageSection: t("editor.blocks.image"),
|
||||
imageAlignLeft: t("editor.blocks.image-align-left"),
|
||||
imageAlignCenter: t("editor.blocks.image-align-center"),
|
||||
imageAlignRight: t("editor.blocks.image-align-right"),
|
||||
resetImageSize: t("editor.blocks.reset-image-size"),
|
||||
altText: t("editor.blocks.alt-text"),
|
||||
altTextPlaceholder: t("editor.blocks.alt-text-placeholder"),
|
||||
|
||||
@@ -247,6 +247,9 @@
|
||||
"align-left": "يسار",
|
||||
"align-center": "وسط",
|
||||
"align-right": "يمين",
|
||||
"image-align-left": "محاذاة لليسار",
|
||||
"image-align-center": "محاذاة للوسط",
|
||||
"image-align-right": "محاذاة لليمين",
|
||||
"text-style": "نمط النص",
|
||||
"image": "صورة",
|
||||
"reset-image-size": "إعادة تعيين الحجم",
|
||||
|
||||
@@ -344,6 +344,9 @@
|
||||
"align-left": "Sol",
|
||||
"align-center": "Mərkəz",
|
||||
"align-right": "Sağ",
|
||||
"image-align-left": "Sola düzləndir",
|
||||
"image-align-center": "Mərkəzə düzləndir",
|
||||
"image-align-right": "Sağa düzləndir",
|
||||
"text-style": "Mətn üslubu",
|
||||
"image": "Şəkil",
|
||||
"reset-image-size": "Ölçünü sıfırla",
|
||||
|
||||
@@ -285,6 +285,9 @@
|
||||
"align-left": "Вляво",
|
||||
"align-center": "Центрирано",
|
||||
"align-right": "Вдясно",
|
||||
"image-align-left": "Подравняване вляво",
|
||||
"image-align-center": "Центриране",
|
||||
"image-align-right": "Подравняване вдясно",
|
||||
"text-style": "Стил на текста",
|
||||
"image": "Изображение",
|
||||
"reset-image-size": "Нулиране на размера",
|
||||
|
||||
@@ -247,6 +247,9 @@
|
||||
"align-left": "Esquerra",
|
||||
"align-center": "Centre",
|
||||
"align-right": "Dreta",
|
||||
"image-align-left": "Alinea a l'esquerra",
|
||||
"image-align-center": "Centra",
|
||||
"image-align-right": "Alinea a la dreta",
|
||||
"text-style": "Estil de text",
|
||||
"image": "Imatge",
|
||||
"reset-image-size": "Restableix la mida",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user