From 3bea6df0300a64d1baf3dd57e735a1d496f5905d Mon Sep 17 00:00:00 2001 From: boojack Date: Sun, 18 Oct 2026 12:11:55 +0800 Subject: [PATCH] refactor(web): one memo component, MemoEditor, with view and edit modes (#6481) --- AGENTS.md | 1 + web/package.json | 2 +- web/pnpm-lock.yaml | 10 +- .../CalendarView/CalendarDayCell.tsx | 2 +- .../components/CalendarView/CalendarView.tsx | 8 +- web/src/components/MapView/MapView.tsx | 4 +- .../MemoActionMenu/MemoShareImagePreview.tsx | 4 +- web/src/components/MemoCommentSection.tsx | 53 +--- web/src/components/MemoContent/enhance.ts | 55 ----- web/src/components/MemoContent/index.tsx | 198 --------------- web/src/components/MemoContent/types.ts | 23 -- .../MemoDetailSidebar/MemoDetailSidebar.tsx | 2 +- .../MemoDetailSidebar/MemoOutline.tsx | 2 +- web/src/components/MemoEditor/MemoEditor.tsx | 232 ++++++++++++++++++ .../components/MemoEditor/MemoMarkdown.tsx | 138 +++++++++++ web/src/components/MemoEditor/README.md | 193 +++++---------- .../MemoEditor/components/EditorContent.tsx | 78 ------ .../{index.tsx => edit/EditSession.tsx} | 64 ++--- .../{Editor/index.tsx => edit/Editor.tsx} | 69 +----- .../{ => edit}/Toolbar/AudienceMenu.tsx | 0 .../{ => edit}/Toolbar/EditorToolbar.tsx | 0 .../{ => edit}/Toolbar/InsertMenu.tsx | 0 .../MemoEditor/{ => edit}/Toolbar/index.ts | 0 .../components/AudioRecorderPanel.tsx | 0 .../edit/components/EditorContent.tsx | 74 ++++++ .../{ => edit}/components/EditorMetadata.tsx | 0 .../components/EditorSuggestions.tsx | 0 .../components/FocusModeOverlay.tsx | 0 .../components/TimestampPopover.tsx | 0 .../{ => edit}/components/VoiceWaveform.tsx | 0 .../MemoEditor/{ => edit}/components/index.ts | 0 .../MemoEditor/{ => edit}/constants.ts | 0 .../MemoEditor/{Editor => edit}/controller.ts | 58 +---- .../components/MemoEditor/edit/draftKey.ts | 56 +++++ .../MemoEditor/{Editor => edit}/editor.css | 0 .../MemoEditor/{Editor => edit}/extensions.ts | 19 +- .../MemoEditor/{ => edit}/hooks/index.ts | 0 .../hooks/useAttachmentTranscription.ts | 0 .../{ => edit}/hooks/useAudioRecorder.ts | 0 .../{ => edit}/hooks/useAudioWaveform.ts | 0 .../{ => edit}/hooks/useAutoSave.ts | 11 +- .../{ => edit}/hooks/useBlobUrls.ts | 0 .../{ => edit}/hooks/useFileUpload.ts | 0 .../{ => edit}/hooks/useFocusMode.ts | 0 .../{ => edit}/hooks/useInlineImageUpload.ts | 0 .../{ => edit}/hooks/useLinkMemo.ts | 0 .../{ => edit}/hooks/useLocation.ts | 0 .../MemoEditor/edit/hooks/useMemoInit.ts | 50 ++++ .../{ => edit}/hooks/useMemoSave.ts | 42 ++-- .../{ => edit}/hooks/useSourceMode.ts | 0 .../MemoEditor/edit/initialState.ts | 73 ++++++ .../{ => edit}/services/cacheService.ts | 5 +- .../{ => edit}/services/errorService.ts | 0 .../MemoEditor/{ => edit}/services/index.ts | 0 .../services/mediaMetadataService.ts | 0 .../{ => edit}/services/memoService.ts | 28 +-- .../services/transcriptionService.ts | 0 .../{ => edit}/services/uploadService.ts | 0 .../{ => edit}/services/validationService.ts | 0 .../MemoEditor/{ => edit}/state/actions.ts | 0 .../MemoEditor/{ => edit}/state/context.tsx | 0 .../MemoEditor/{ => edit}/state/index.ts | 0 .../MemoEditor/{ => edit}/state/reducer.ts | 0 .../MemoEditor/{ => edit}/state/types.ts | 0 .../MemoEditor/{ => edit}/types/attachment.ts | 0 .../MemoEditor/{ => edit}/types/components.ts | 17 +- .../{ => edit}/types/editorController.ts | 2 +- .../MemoEditor/{ => edit}/types/index.ts | 2 +- .../MemoEditor/{ => edit}/types/insertMenu.ts | 0 .../{Editor => edit}/uploadAnchors.ts | 0 .../utils/deriveDefaultCreateTime.ts | 0 .../MemoEditor/hooks/useMemoInit.ts | 103 -------- web/src/components/MemoEditor/index.ts | 10 + web/src/components/MemoEditor/loader.ts | 15 -- .../MemoEditor/useMemoDecorations.ts | 87 +++++++ .../view}/LinkMetadataCard.tsx | 0 .../MemoEditor/view/MemoContentView.tsx | 153 ++++++++++++ .../view}/headings.ts | 0 .../components/MemoEditor/view/linkCards.ts | 46 ++++ .../view}/useSearchMatchHighlight.ts | Bin .../view}/useTagNavigation.ts | 2 +- .../Attachment/AttachmentListEditor.tsx | 4 +- .../MemoMetadata/Location/LocationDialog.tsx | 2 +- .../components/MemoPanel/MemoPanelList.tsx | 14 +- .../components/MemoPreview/MemoPreview.tsx | 7 +- .../components/MemoReactionListView/hooks.ts | 2 +- web/src/components/MemoView/MemoView.tsx | 72 ++---- .../components/MemoView/MemoViewContext.tsx | 5 + .../MemoView/components/MemoBody.tsx | 47 +++- .../MemoView/components/MemoHeader.tsx | 49 +++- .../PagedMemoList/PagedMemoList.tsx | 2 +- web/src/contexts/GlobalMemoEditorContext.tsx | 27 +- .../MentionResolutionContext.tsx | 29 +-- web/src/hooks/useMemoQueries.ts | 225 +++++++++++------ web/src/lib/markdownStyles.ts | 4 +- web/src/lib/memo-markdown.ts | 7 +- web/src/locales/ar.json | 3 + web/src/locales/az.json | 3 + web/src/locales/bg.json | 3 + web/src/locales/ca.json | 3 + web/src/locales/cs.json | 3 + web/src/locales/da.json | 3 + web/src/locales/de.json | 3 + web/src/locales/el.json | 3 + web/src/locales/en-GB.json | 3 + web/src/locales/en.json | 3 + web/src/locales/es.json | 3 + web/src/locales/et.json | 3 + web/src/locales/fa.json | 3 + web/src/locales/fi.json | 3 + web/src/locales/fr.json | 3 + web/src/locales/gl.json | 3 + web/src/locales/he.json | 3 + web/src/locales/hi.json | 3 + web/src/locales/hr.json | 3 + web/src/locales/hu.json | 3 + web/src/locales/id.json | 3 + web/src/locales/it.json | 3 + web/src/locales/ja.json | 3 + web/src/locales/ka-GE.json | 3 + web/src/locales/ko.json | 3 + web/src/locales/lt.json | 3 + web/src/locales/lv.json | 3 + web/src/locales/mr.json | 3 + web/src/locales/nb.json | 3 + web/src/locales/nl.json | 3 + web/src/locales/nn.json | 3 + web/src/locales/pl.json | 3 + web/src/locales/pt-BR.json | 3 + web/src/locales/pt-PT.json | 3 + web/src/locales/ro.json | 3 + web/src/locales/ru.json | 3 + web/src/locales/sk.json | 3 + web/src/locales/sl.json | 3 + web/src/locales/sr.json | 3 + web/src/locales/sv.json | 3 + web/src/locales/th.json | 3 + web/src/locales/tr.json | 3 + web/src/locales/uk.json | 3 + web/src/locales/vi.json | 3 + web/src/locales/zh-Hans.json | 3 + web/src/locales/zh-Hant.json | 3 + web/src/pages/Home.tsx | 14 +- web/src/pages/MemoDetail.tsx | 2 +- web/tests/audience-menu.test.tsx | 8 +- web/tests/calendar-day-snapshot.test.tsx | 2 +- web/tests/derive-default-create-time.test.ts | 2 +- web/tests/draft-key.test.ts | 57 +++++ web/tests/editor-commit-button.test.tsx | 8 +- web/tests/editor-controller.test.tsx | 8 +- .../editor-inline-image-validation.test.ts | 4 +- web/tests/editor-suggestions.test.tsx | 9 +- web/tests/editor-tag-autocomplete.test.ts | 2 +- web/tests/editor.test.tsx | 19 +- web/tests/focus-mode-exit-button.test.tsx | 2 +- web/tests/global-memo-editor.test.tsx | 72 ++---- web/tests/helpers/memo-save-operations.ts | 20 ++ web/tests/home-loading-boundary.test.tsx | 7 +- web/tests/inline-image-upload-files.test.ts | 6 +- web/tests/insert-menu.test.tsx | 6 +- web/tests/map-view.test.tsx | 16 +- web/tests/media-metadata-exif-fixture.test.ts | 2 +- web/tests/media-metadata-service.test.ts | 2 +- web/tests/memo-body-compact.test.tsx | 6 +- web/tests/memo-comment-section.test.tsx | 22 +- ...nt.test.tsx => memo-content-view.test.tsx} | 8 +- web/tests/memo-detail-access.test.tsx | 2 +- web/tests/memo-editor-cache.test.ts | 2 +- web/tests/memo-editor-paste-files.test.tsx | 11 +- web/tests/memo-editor-relations.test.ts | 17 +- web/tests/memo-editor-source-mode.test.tsx | 16 +- web/tests/memo-editor-space-move.test.ts | 11 +- web/tests/memo-editor-timestamps.test.tsx | 15 +- web/tests/memo-editor-transcription.test.tsx | 17 +- web/tests/memo-editor-upload-retry.test.tsx | 15 +- web/tests/memo-editor-view.test.tsx | 98 ++++++++ web/tests/memo-header-navigation.test.tsx | 27 ++ web/tests/memo-outline-headings.test.ts | 2 +- web/tests/memo-panel-list.test.tsx | 4 +- web/tests/memo-record.test.tsx | 190 ++++++++++++++ web/tests/paged-memo-list.test.tsx | 2 +- web/tests/query-deduplication.test.tsx | 2 +- web/tests/search-match-highlight.test.tsx | 2 +- web/tests/transcription-service.test.ts | 2 +- web/tests/upload-media-metadata.test.ts | 8 +- web/tests/upload-service.test.ts | 2 +- web/tests/usage-limit-errors.test.ts | 2 +- .../use-attachment-transcription.test.tsx | 4 +- web/tests/use-auto-save.test.tsx | 8 +- web/tests/use-inline-image-upload.test.tsx | 12 +- web/tests/use-memo-init.test.tsx | 152 +++++------- web/tests/use-memo-save.test.tsx | 25 +- 192 files changed, 2207 insertions(+), 1370 deletions(-) delete mode 100644 web/src/components/MemoContent/enhance.ts delete mode 100644 web/src/components/MemoContent/index.tsx delete mode 100644 web/src/components/MemoContent/types.ts create mode 100644 web/src/components/MemoEditor/MemoEditor.tsx create mode 100644 web/src/components/MemoEditor/MemoMarkdown.tsx delete mode 100644 web/src/components/MemoEditor/components/EditorContent.tsx rename web/src/components/MemoEditor/{index.tsx => edit/EditSession.tsx} (90%) rename web/src/components/MemoEditor/{Editor/index.tsx => edit/Editor.tsx} (55%) rename web/src/components/MemoEditor/{ => edit}/Toolbar/AudienceMenu.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/Toolbar/EditorToolbar.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/Toolbar/InsertMenu.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/Toolbar/index.ts (100%) rename web/src/components/MemoEditor/{ => edit}/components/AudioRecorderPanel.tsx (100%) create mode 100644 web/src/components/MemoEditor/edit/components/EditorContent.tsx rename web/src/components/MemoEditor/{ => edit}/components/EditorMetadata.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/components/EditorSuggestions.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/components/FocusModeOverlay.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/components/TimestampPopover.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/components/VoiceWaveform.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/components/index.ts (100%) rename web/src/components/MemoEditor/{ => edit}/constants.ts (100%) rename web/src/components/MemoEditor/{Editor => edit}/controller.ts (62%) create mode 100644 web/src/components/MemoEditor/edit/draftKey.ts rename web/src/components/MemoEditor/{Editor => edit}/editor.css (100%) rename web/src/components/MemoEditor/{Editor => edit}/extensions.ts (78%) rename web/src/components/MemoEditor/{ => edit}/hooks/index.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useAttachmentTranscription.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useAudioRecorder.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useAudioWaveform.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useAutoSave.ts (89%) rename web/src/components/MemoEditor/{ => edit}/hooks/useBlobUrls.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useFileUpload.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useFocusMode.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useInlineImageUpload.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useLinkMemo.ts (100%) rename web/src/components/MemoEditor/{ => edit}/hooks/useLocation.ts (100%) create mode 100644 web/src/components/MemoEditor/edit/hooks/useMemoInit.ts rename web/src/components/MemoEditor/{ => edit}/hooks/useMemoSave.ts (81%) rename web/src/components/MemoEditor/{ => edit}/hooks/useSourceMode.ts (100%) create mode 100644 web/src/components/MemoEditor/edit/initialState.ts rename web/src/components/MemoEditor/{ => edit}/services/cacheService.ts (96%) rename web/src/components/MemoEditor/{ => edit}/services/errorService.ts (100%) rename web/src/components/MemoEditor/{ => edit}/services/index.ts (100%) rename web/src/components/MemoEditor/{ => edit}/services/mediaMetadataService.ts (100%) rename web/src/components/MemoEditor/{ => edit}/services/memoService.ts (88%) rename web/src/components/MemoEditor/{ => edit}/services/transcriptionService.ts (100%) rename web/src/components/MemoEditor/{ => edit}/services/uploadService.ts (100%) rename web/src/components/MemoEditor/{ => edit}/services/validationService.ts (100%) rename web/src/components/MemoEditor/{ => edit}/state/actions.ts (100%) rename web/src/components/MemoEditor/{ => edit}/state/context.tsx (100%) rename web/src/components/MemoEditor/{ => edit}/state/index.ts (100%) rename web/src/components/MemoEditor/{ => edit}/state/reducer.ts (100%) rename web/src/components/MemoEditor/{ => edit}/state/types.ts (100%) rename web/src/components/MemoEditor/{ => edit}/types/attachment.ts (100%) rename web/src/components/MemoEditor/{ => edit}/types/components.ts (90%) rename web/src/components/MemoEditor/{ => edit}/types/editorController.ts (96%) rename web/src/components/MemoEditor/{ => edit}/types/index.ts (95%) rename web/src/components/MemoEditor/{ => edit}/types/insertMenu.ts (100%) rename web/src/components/MemoEditor/{Editor => edit}/uploadAnchors.ts (100%) rename web/src/components/MemoEditor/{ => edit}/utils/deriveDefaultCreateTime.ts (100%) delete mode 100644 web/src/components/MemoEditor/hooks/useMemoInit.ts create mode 100644 web/src/components/MemoEditor/index.ts delete mode 100644 web/src/components/MemoEditor/loader.ts create mode 100644 web/src/components/MemoEditor/useMemoDecorations.ts rename web/src/components/{MemoContent => MemoEditor/view}/LinkMetadataCard.tsx (100%) create mode 100644 web/src/components/MemoEditor/view/MemoContentView.tsx rename web/src/components/{MemoContent => MemoEditor/view}/headings.ts (100%) create mode 100644 web/src/components/MemoEditor/view/linkCards.ts rename web/src/components/{MemoContent => MemoEditor/view}/useSearchMatchHighlight.ts (100%) rename web/src/components/{MemoContent => MemoEditor/view}/useTagNavigation.ts (93%) rename web/src/{components/MemoContent => contexts}/MentionResolutionContext.tsx (79%) create mode 100644 web/tests/draft-key.test.ts create mode 100644 web/tests/helpers/memo-save-operations.ts rename web/tests/{memo-content.test.tsx => memo-content-view.test.tsx} (97%) create mode 100644 web/tests/memo-editor-view.test.tsx create mode 100644 web/tests/memo-record.test.tsx diff --git a/AGENTS.md b/AGENTS.md index 558dfe477..da12b67a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/web/package.json b/web/package.json index e71284501..adfb40d02 100644 --- a/web/package.json +++ b/web/package.json @@ -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", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index acbde7baa..e26b11909 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -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) diff --git a/web/src/components/CalendarView/CalendarDayCell.tsx b/web/src/components/CalendarView/CalendarDayCell.tsx index 6bf849331..8a232b5a9 100644 --- a/web/src/components/CalendarView/CalendarDayCell.tsx +++ b/web/src/components/CalendarView/CalendarDayCell.tsx @@ -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"; diff --git a/web/src/components/CalendarView/CalendarView.tsx b/web/src/components/CalendarView/CalendarView.tsx index 1c805af9b..9f7c6989e 100644 --- a/web/src/components/CalendarView/CalendarView.tsx +++ b/web/src/components/CalendarView/CalendarView.tsx @@ -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 diff --git a/web/src/components/MapView/MapView.tsx b/web/src/components/MapView/MapView.tsx index c8646ec2c..8764c1d7f 100644 --- a/web/src/components/MapView/MapView.tsx +++ b/web/src/components/MapView/MapView.tsx @@ -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), diff --git a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx index 5ff105497..e80b596ae 100644 --- a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx +++ b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx @@ -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(({ w
- ( const t = useTranslate(); const currentUser = useCurrentUser(); const [showEditor, setShowEditor] = useState(false); - const [isEditorLoading, setIsEditorLoading] = useState(false); - const [EditorComponent, setEditorComponent] = useState>(); const sectionRef = useRef(null); const canCreateComment = !!currentUser && memo.state === State.NORMAL; @@ -42,9 +39,8 @@ const MemoCommentSection = forwardRef( 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('.memo-editor-root[contenteditable="true"]'); @@ -53,25 +49,15 @@ const MemoCommentSection = forwardRef( }, []); 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( {comments.length === 0 ? ( showCreateButton && (
-
) @@ -118,20 +94,17 @@ const MemoCommentSection = forwardRef( onPointerEnter={preloadEditor} onFocus={preloadEditor} onClick={openEditor} - disabled={isEditorLoading} > - {isEditorLoading && } {t("memo.comment.write-a-comment")} )}
)} - {showEditor && EditorComponent && ( + {showEditor && (
- setShowEditor(false)} diff --git a/web/src/components/MemoContent/enhance.ts b/web/src/components/MemoContent/enhance.ts deleted file mode 100644 index ee8aefafa..000000000 --- a/web/src/components/MemoContent/enhance.ts +++ /dev/null @@ -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(); -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(`[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); diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsx deleted file mode 100644 index 8390197b7..000000000 --- a/web/src/components/MemoContent/index.tsx +++ /dev/null @@ -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(); - const fallback = ( - - {href} - - ); - return ; -}; - -/** - * 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(null); - useSearchMatchHighlight(contentRef, useContentSearchTerms()); - const [editor, setEditor] = useState(null); - const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => ""); - const editorKey = MERMAID_FENCE.test(content) ? colorScheme : undefined; - const [islands, setIslands] = useState([]); - - // 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(".mbe-tag")?.dataset.tag; - if (tag) { - event.stopPropagation(); - navigateToTag(tag); - return; - } - const mention = target.closest(".mbe-mention[data-resolved]")?.dataset.mention; - if (mention) { - event.stopPropagation(); - navigate(getCreatorHomePath(mention)); - } - }; - - return ( -
-
- - {islands.map((island) => createPortal(, island.target, island.key))} -
-
- ); -}; - -export default memo(MemoContent); diff --git a/web/src/components/MemoContent/types.ts b/web/src/components/MemoContent/types.ts deleted file mode 100644 index db530e49f..000000000 --- a/web/src/components/MemoContent/types.ts +++ /dev/null @@ -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; -} diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx index c1cf37a74..980609c1a 100644 --- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx +++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx @@ -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"; diff --git a/web/src/components/MemoDetailSidebar/MemoOutline.tsx b/web/src/components/MemoDetailSidebar/MemoOutline.tsx index c70c87fc9..ee120a721 100644 --- a/web/src/components/MemoDetailSidebar/MemoOutline.tsx +++ b/web/src/components/MemoDetailSidebar/MemoOutline.tsx @@ -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"; diff --git a/web/src/components/MemoEditor/MemoEditor.tsx b/web/src/components/MemoEditor/MemoEditor.tsx new file mode 100644 index 000000000..032deef07 --- /dev/null +++ b/web/src/components/MemoEditor/MemoEditor.tsx @@ -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 => + 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:` or + * `map:`. 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 ; + if (props.mode === "edit") return ; + return ; +}; + +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 ( + + ); +}; + +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 = ; + if (!memo) return fallback; + const identity: MemoEditIdentity = { kind: "edit", name }; + return ( + + + + ); +}; + +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 : ( +
+ ); + return ( + + + + ); +}; + +interface EditingSessionProps extends MemoEditingProps { + identity: MemoEditIdentity; + memo?: Parameters[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 ( + + + + ); +}; diff --git a/web/src/components/MemoEditor/MemoMarkdown.tsx b/web/src/components/MemoEditor/MemoMarkdown.tsx new file mode 100644 index 000000000..df6ae6b92 --- /dev/null +++ b/web/src/components/MemoEditor/MemoMarkdown.tsx @@ -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; + 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; + /** 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 = (ref: Ref | 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(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 ( + 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} + /> + ); +}; diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md index b3e45f389..f4cc3d2c8 100644 --- a/web/src/components/MemoEditor/README.md +++ b/web/src/components/MemoEditor/README.md @@ -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 + // view; the owner can tick tasks + // edit in place + // new comment + // 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 ; 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:`, `comment:`, `new:[:]`. `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 `
` 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. - 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. diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx deleted file mode 100644 index 7ddde9301..000000000 --- a/web/src/components/MemoEditor/components/EditorContent.tsx +++ /dev/null @@ -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( - ({ placeholder, sourceMode, onSubmit, onFiles, tagsSetting }, ref) => { - const t = useTranslate(); - const wrapperRef = useRef(null); - const sourceTagRef = useRef(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 ( -
- - {/* 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 && ( - - - } - > - {sourceLabel} - - {t("editor.switch-to-rich-text")} - - )} -
- ); - }, -); - -EditorContent.displayName = "EditorContent"; diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/edit/EditSession.tsx similarity index 90% rename from web/src/components/MemoEditor/index.tsx rename to web/src/components/MemoEditor/edit/EditSession.tsx index d031149b7..223fb0deb 100644 --- a/web/src/components/MemoEditor/index.tsx +++ b/web/src/components/MemoEditor/edit/EditSession.tsx @@ -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) => ( - - - -); - -const MemoEditorImpl: React.FC = ({ +/** + * 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 = ({ className, - cacheKey, + draftKey, + frameless, memo, parentMemoName, suggestions = [], defaultSpace, - defaultLocation, autoFocus, onFocusModeExit, onFocusModeChange, @@ -71,7 +72,7 @@ const MemoEditorImpl: React.FC = ({ }, [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 = ({ // 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 = ({ // 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 = ({ }, [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 = ({ 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 = ({
= ({ sourceMode={sourceMode} onSubmit={handleSave} onFiles={handleEditorFiles} - tagsSetting={userTagsSetting} /> {isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && ( @@ -425,5 +417,3 @@ const MemoEditorImpl: React.FC = ({ ); }; - -export default MemoEditor; diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/edit/Editor.tsx similarity index 55% rename from web/src/components/MemoEditor/Editor/index.tsx rename to web/src/components/MemoEditor/edit/Editor.tsx index c2d31f442..2ae10b854 100644 --- a/web/src/components/MemoEditor/Editor/index.tsx +++ b/web/src/components/MemoEditor/edit/Editor.tsx @@ -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) { - 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(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([]); 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([]); - 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>(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 (
- 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" />
diff --git a/web/src/components/MemoEditor/Toolbar/AudienceMenu.tsx b/web/src/components/MemoEditor/edit/Toolbar/AudienceMenu.tsx similarity index 100% rename from web/src/components/MemoEditor/Toolbar/AudienceMenu.tsx rename to web/src/components/MemoEditor/edit/Toolbar/AudienceMenu.tsx diff --git a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx b/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx similarity index 100% rename from web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx rename to web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/edit/Toolbar/InsertMenu.tsx similarity index 100% rename from web/src/components/MemoEditor/Toolbar/InsertMenu.tsx rename to web/src/components/MemoEditor/edit/Toolbar/InsertMenu.tsx diff --git a/web/src/components/MemoEditor/Toolbar/index.ts b/web/src/components/MemoEditor/edit/Toolbar/index.ts similarity index 100% rename from web/src/components/MemoEditor/Toolbar/index.ts rename to web/src/components/MemoEditor/edit/Toolbar/index.ts diff --git a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx b/web/src/components/MemoEditor/edit/components/AudioRecorderPanel.tsx similarity index 100% rename from web/src/components/MemoEditor/components/AudioRecorderPanel.tsx rename to web/src/components/MemoEditor/edit/components/AudioRecorderPanel.tsx diff --git a/web/src/components/MemoEditor/edit/components/EditorContent.tsx b/web/src/components/MemoEditor/edit/components/EditorContent.tsx new file mode 100644 index 000000000..68d1e62a0 --- /dev/null +++ b/web/src/components/MemoEditor/edit/components/EditorContent.tsx @@ -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(({ placeholder, sourceMode, onSubmit, onFiles }, ref) => { + const t = useTranslate(); + const wrapperRef = useRef(null); + const sourceTagRef = useRef(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 ( +
+ + {/* 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 && ( + + + } + > + {sourceLabel} + + {t("editor.switch-to-rich-text")} + + )} +
+ ); +}); + +EditorContent.displayName = "EditorContent"; diff --git a/web/src/components/MemoEditor/components/EditorMetadata.tsx b/web/src/components/MemoEditor/edit/components/EditorMetadata.tsx similarity index 100% rename from web/src/components/MemoEditor/components/EditorMetadata.tsx rename to web/src/components/MemoEditor/edit/components/EditorMetadata.tsx diff --git a/web/src/components/MemoEditor/components/EditorSuggestions.tsx b/web/src/components/MemoEditor/edit/components/EditorSuggestions.tsx similarity index 100% rename from web/src/components/MemoEditor/components/EditorSuggestions.tsx rename to web/src/components/MemoEditor/edit/components/EditorSuggestions.tsx diff --git a/web/src/components/MemoEditor/components/FocusModeOverlay.tsx b/web/src/components/MemoEditor/edit/components/FocusModeOverlay.tsx similarity index 100% rename from web/src/components/MemoEditor/components/FocusModeOverlay.tsx rename to web/src/components/MemoEditor/edit/components/FocusModeOverlay.tsx diff --git a/web/src/components/MemoEditor/components/TimestampPopover.tsx b/web/src/components/MemoEditor/edit/components/TimestampPopover.tsx similarity index 100% rename from web/src/components/MemoEditor/components/TimestampPopover.tsx rename to web/src/components/MemoEditor/edit/components/TimestampPopover.tsx diff --git a/web/src/components/MemoEditor/components/VoiceWaveform.tsx b/web/src/components/MemoEditor/edit/components/VoiceWaveform.tsx similarity index 100% rename from web/src/components/MemoEditor/components/VoiceWaveform.tsx rename to web/src/components/MemoEditor/edit/components/VoiceWaveform.tsx diff --git a/web/src/components/MemoEditor/components/index.ts b/web/src/components/MemoEditor/edit/components/index.ts similarity index 100% rename from web/src/components/MemoEditor/components/index.ts rename to web/src/components/MemoEditor/edit/components/index.ts diff --git a/web/src/components/MemoEditor/constants.ts b/web/src/components/MemoEditor/edit/constants.ts similarity index 100% rename from web/src/components/MemoEditor/constants.ts rename to web/src/components/MemoEditor/edit/constants.ts diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/edit/controller.ts similarity index 62% rename from web/src/components/MemoEditor/Editor/controller.ts rename to web/src/components/MemoEditor/edit/controller.ts index 469b4111e..b870e07ab 100644 --- a/web/src/components/MemoEditor/Editor/controller.ts +++ b/web/src/components/MemoEditor/edit/controller.ts @@ -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(); } diff --git a/web/src/components/MemoEditor/edit/draftKey.ts b/web/src/components/MemoEditor/edit/draftKey.ts new file mode 100644 index 000000000..6a4298de2 --- /dev/null +++ b/web/src/components/MemoEditor/edit/draftKey.ts @@ -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 = { + 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. + } +} diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/edit/editor.css similarity index 100% rename from web/src/components/MemoEditor/Editor/editor.css rename to web/src/components/MemoEditor/edit/editor.css diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/edit/extensions.ts similarity index 78% rename from web/src/components/MemoEditor/Editor/extensions.ts rename to web/src/components/MemoEditor/edit/extensions.ts index f64730a23..f5f7485af 100644 --- a/web/src/components/MemoEditor/Editor/extensions.ts +++ b/web/src/components/MemoEditor/edit/extensions.ts @@ -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({ diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/edit/hooks/index.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/index.ts rename to web/src/components/MemoEditor/edit/hooks/index.ts diff --git a/web/src/components/MemoEditor/hooks/useAttachmentTranscription.ts b/web/src/components/MemoEditor/edit/hooks/useAttachmentTranscription.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useAttachmentTranscription.ts rename to web/src/components/MemoEditor/edit/hooks/useAttachmentTranscription.ts diff --git a/web/src/components/MemoEditor/hooks/useAudioRecorder.ts b/web/src/components/MemoEditor/edit/hooks/useAudioRecorder.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useAudioRecorder.ts rename to web/src/components/MemoEditor/edit/hooks/useAudioRecorder.ts diff --git a/web/src/components/MemoEditor/hooks/useAudioWaveform.ts b/web/src/components/MemoEditor/edit/hooks/useAudioWaveform.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useAudioWaveform.ts rename to web/src/components/MemoEditor/edit/hooks/useAudioWaveform.ts diff --git a/web/src/components/MemoEditor/hooks/useAutoSave.ts b/web/src/components/MemoEditor/edit/hooks/useAutoSave.ts similarity index 89% rename from web/src/components/MemoEditor/hooks/useAutoSave.ts rename to web/src/components/MemoEditor/edit/hooks/useAutoSave.ts index 1f68e6464..458910967 100644 --- a/web/src/components/MemoEditor/hooks/useAutoSave.ts +++ b/web/src/components/MemoEditor/edit/hooks/useAutoSave.ts @@ -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(draftFromState(store.getState())); const discardedDraftRef = useRef(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 }; }; diff --git a/web/src/components/MemoEditor/hooks/useBlobUrls.ts b/web/src/components/MemoEditor/edit/hooks/useBlobUrls.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useBlobUrls.ts rename to web/src/components/MemoEditor/edit/hooks/useBlobUrls.ts diff --git a/web/src/components/MemoEditor/hooks/useFileUpload.ts b/web/src/components/MemoEditor/edit/hooks/useFileUpload.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useFileUpload.ts rename to web/src/components/MemoEditor/edit/hooks/useFileUpload.ts diff --git a/web/src/components/MemoEditor/hooks/useFocusMode.ts b/web/src/components/MemoEditor/edit/hooks/useFocusMode.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useFocusMode.ts rename to web/src/components/MemoEditor/edit/hooks/useFocusMode.ts diff --git a/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts b/web/src/components/MemoEditor/edit/hooks/useInlineImageUpload.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useInlineImageUpload.ts rename to web/src/components/MemoEditor/edit/hooks/useInlineImageUpload.ts diff --git a/web/src/components/MemoEditor/hooks/useLinkMemo.ts b/web/src/components/MemoEditor/edit/hooks/useLinkMemo.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useLinkMemo.ts rename to web/src/components/MemoEditor/edit/hooks/useLinkMemo.ts diff --git a/web/src/components/MemoEditor/hooks/useLocation.ts b/web/src/components/MemoEditor/edit/hooks/useLocation.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useLocation.ts rename to web/src/components/MemoEditor/edit/hooks/useLocation.ts diff --git a/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts b/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts new file mode 100644 index 000000000..5583d988c --- /dev/null +++ b/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts @@ -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; + /** 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 | 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 }; +}; diff --git a/web/src/components/MemoEditor/hooks/useMemoSave.ts b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts similarity index 81% rename from web/src/components/MemoEditor/hooks/useMemoSave.ts rename to web/src/components/MemoEditor/edit/hooks/useMemoSave.ts index 27106817b..c9493a179 100644 --- a/web/src/components/MemoEditor/hooks/useMemoSave.ts +++ b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts @@ -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 { 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[] = [ - 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, ]); } diff --git a/web/src/components/MemoEditor/hooks/useSourceMode.ts b/web/src/components/MemoEditor/edit/hooks/useSourceMode.ts similarity index 100% rename from web/src/components/MemoEditor/hooks/useSourceMode.ts rename to web/src/components/MemoEditor/edit/hooks/useSourceMode.ts diff --git a/web/src/components/MemoEditor/edit/initialState.ts b/web/src/components/MemoEditor/edit/initialState.ts new file mode 100644 index 000000000..b6b9a0fec --- /dev/null +++ b/web/src/components/MemoEditor/edit/initialState.ts @@ -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, + }; +} diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/edit/services/cacheService.ts similarity index 96% rename from web/src/components/MemoEditor/services/cacheService.ts rename to web/src/components/MemoEditor/edit/services/cacheService.ts index fc21d5f0b..35ace5718 100644 --- a/web/src/components/MemoEditor/services/cacheService.ts +++ b/web/src/components/MemoEditor/edit/services/cacheService.ts @@ -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) => { diff --git a/web/src/components/MemoEditor/services/errorService.ts b/web/src/components/MemoEditor/edit/services/errorService.ts similarity index 100% rename from web/src/components/MemoEditor/services/errorService.ts rename to web/src/components/MemoEditor/edit/services/errorService.ts diff --git a/web/src/components/MemoEditor/services/index.ts b/web/src/components/MemoEditor/edit/services/index.ts similarity index 100% rename from web/src/components/MemoEditor/services/index.ts rename to web/src/components/MemoEditor/edit/services/index.ts diff --git a/web/src/components/MemoEditor/services/mediaMetadataService.ts b/web/src/components/MemoEditor/edit/services/mediaMetadataService.ts similarity index 100% rename from web/src/components/MemoEditor/services/mediaMetadataService.ts rename to web/src/components/MemoEditor/edit/services/mediaMetadataService.ts diff --git a/web/src/components/MemoEditor/services/memoService.ts b/web/src/components/MemoEditor/edit/services/memoService.ts similarity index 88% rename from web/src/components/MemoEditor/services/memoService.ts rename to web/src/components/MemoEditor/edit/services/memoService.ts index 56dd3eea1..f72965a43 100644 --- a/web/src/components/MemoEditor/services/memoService.ts +++ b/web/src/components/MemoEditor/edit/services/memoService.ts @@ -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; + updateMemo: (update: Partial, updateMask: string[]) => Promise; + /** Creates a memo, or a comment on `parent`. */ + createMemo: (memo: Memo, parent?: string) => Promise; +} + 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), - 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 }; }, diff --git a/web/src/components/MemoEditor/services/transcriptionService.ts b/web/src/components/MemoEditor/edit/services/transcriptionService.ts similarity index 100% rename from web/src/components/MemoEditor/services/transcriptionService.ts rename to web/src/components/MemoEditor/edit/services/transcriptionService.ts diff --git a/web/src/components/MemoEditor/services/uploadService.ts b/web/src/components/MemoEditor/edit/services/uploadService.ts similarity index 100% rename from web/src/components/MemoEditor/services/uploadService.ts rename to web/src/components/MemoEditor/edit/services/uploadService.ts diff --git a/web/src/components/MemoEditor/services/validationService.ts b/web/src/components/MemoEditor/edit/services/validationService.ts similarity index 100% rename from web/src/components/MemoEditor/services/validationService.ts rename to web/src/components/MemoEditor/edit/services/validationService.ts diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/edit/state/actions.ts similarity index 100% rename from web/src/components/MemoEditor/state/actions.ts rename to web/src/components/MemoEditor/edit/state/actions.ts diff --git a/web/src/components/MemoEditor/state/context.tsx b/web/src/components/MemoEditor/edit/state/context.tsx similarity index 100% rename from web/src/components/MemoEditor/state/context.tsx rename to web/src/components/MemoEditor/edit/state/context.tsx diff --git a/web/src/components/MemoEditor/state/index.ts b/web/src/components/MemoEditor/edit/state/index.ts similarity index 100% rename from web/src/components/MemoEditor/state/index.ts rename to web/src/components/MemoEditor/edit/state/index.ts diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/edit/state/reducer.ts similarity index 100% rename from web/src/components/MemoEditor/state/reducer.ts rename to web/src/components/MemoEditor/edit/state/reducer.ts diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/edit/state/types.ts similarity index 100% rename from web/src/components/MemoEditor/state/types.ts rename to web/src/components/MemoEditor/edit/state/types.ts diff --git a/web/src/components/MemoEditor/types/attachment.ts b/web/src/components/MemoEditor/edit/types/attachment.ts similarity index 100% rename from web/src/components/MemoEditor/types/attachment.ts rename to web/src/components/MemoEditor/edit/types/attachment.ts diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/edit/types/components.ts similarity index 90% rename from web/src/components/MemoEditor/types/components.ts rename to web/src/components/MemoEditor/edit/types/components.ts index 656b5d1dd..c6d87ecc5 100644 --- a/web/src/components/MemoEditor/types/components.ts +++ b/web/src/components/MemoEditor/edit/types/components.ts @@ -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; } /** diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/edit/types/editorController.ts similarity index 96% rename from web/src/components/MemoEditor/types/editorController.ts rename to web/src/components/MemoEditor/edit/types/editorController.ts index cf4ea4b14..fcb8e5c83 100644 --- a/web/src/components/MemoEditor/types/editorController.ts +++ b/web/src/components/MemoEditor/edit/types/editorController.ts @@ -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; diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/edit/types/index.ts similarity index 95% rename from web/src/components/MemoEditor/types/index.ts rename to web/src/components/MemoEditor/edit/types/index.ts index 5c99c7d2a..d4d48cecd 100644 --- a/web/src/components/MemoEditor/types/index.ts +++ b/web/src/components/MemoEditor/edit/types/index.ts @@ -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"; diff --git a/web/src/components/MemoEditor/types/insertMenu.ts b/web/src/components/MemoEditor/edit/types/insertMenu.ts similarity index 100% rename from web/src/components/MemoEditor/types/insertMenu.ts rename to web/src/components/MemoEditor/edit/types/insertMenu.ts diff --git a/web/src/components/MemoEditor/Editor/uploadAnchors.ts b/web/src/components/MemoEditor/edit/uploadAnchors.ts similarity index 100% rename from web/src/components/MemoEditor/Editor/uploadAnchors.ts rename to web/src/components/MemoEditor/edit/uploadAnchors.ts diff --git a/web/src/components/MemoEditor/utils/deriveDefaultCreateTime.ts b/web/src/components/MemoEditor/edit/utils/deriveDefaultCreateTime.ts similarity index 100% rename from web/src/components/MemoEditor/utils/deriveDefaultCreateTime.ts rename to web/src/components/MemoEditor/edit/utils/deriveDefaultCreateTime.ts diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts deleted file mode 100644 index add599a35..000000000 --- a/web/src/components/MemoEditor/hooks/useMemoInit.ts +++ /dev/null @@ -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; - 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 | 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 }; -}; diff --git a/web/src/components/MemoEditor/index.ts b/web/src/components/MemoEditor/index.ts new file mode 100644 index 000000000..80f7633e5 --- /dev/null +++ b/web/src/components/MemoEditor/index.ts @@ -0,0 +1,10 @@ +export { + type MemoDraftSeed, + type MemoEditingProps, + MemoEditor, + type MemoEditorDraftProps, + type MemoEditorEditProps, + type MemoEditorProps, + type MemoEditorViewProps, + preloadMemoEditing, +} from "./MemoEditor"; diff --git a/web/src/components/MemoEditor/loader.ts b/web/src/components/MemoEditor/loader.ts deleted file mode 100644 index e10dfb497..000000000 --- a/web/src/components/MemoEditor/loader.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { loadWithReload } from "@/utils/lazy"; - -type MemoEditorModule = typeof import("."); - -let memoEditorModulePromise: Promise | 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 => { - memoEditorModulePromise ??= loadWithReload(() => import(".")).catch((error) => { - memoEditorModulePromise = undefined; - throw error; - }); - return memoEditorModulePromise; -}; diff --git a/web/src/components/MemoEditor/useMemoDecorations.ts b/web/src/components/MemoEditor/useMemoDecorations.ts new file mode 100644 index 000000000..f235133eb --- /dev/null +++ b/web/src/components/MemoEditor/useMemoDecorations.ts @@ -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; + /** `mentions()` class, attributes and click: the primary color for people who exist. */ + readonly mentions: Pick; +} + +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; + }, + }, + }), + [], + ); +} diff --git a/web/src/components/MemoContent/LinkMetadataCard.tsx b/web/src/components/MemoEditor/view/LinkMetadataCard.tsx similarity index 100% rename from web/src/components/MemoContent/LinkMetadataCard.tsx rename to web/src/components/MemoEditor/view/LinkMetadataCard.tsx diff --git a/web/src/components/MemoEditor/view/MemoContentView.tsx b/web/src/components/MemoEditor/view/MemoContentView.tsx new file mode 100644 index 000000000..40e3bd689 --- /dev/null +++ b/web/src/components/MemoEditor/view/MemoContentView.tsx @@ -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(); + const fallback = ( + + {href} + + ); + return ; +}; + +/** 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(null); + useSearchMatchHighlight(contentRef, useContentSearchTerms()); + const [editor, setEditor] = useState(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([]); + 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 ( +
+
+ navigate(getCreatorHomePath(username))} + className="memo-content-root" + /> + {cards.map((card) => createPortal(, card.element, String(card.key)))} +
+
+ ); +}; + +export const MemoContentView = memo(MemoContentViewImpl); diff --git a/web/src/components/MemoContent/headings.ts b/web/src/components/MemoEditor/view/headings.ts similarity index 100% rename from web/src/components/MemoContent/headings.ts rename to web/src/components/MemoEditor/view/headings.ts diff --git a/web/src/components/MemoEditor/view/linkCards.ts b/web/src/components/MemoEditor/view/linkCards.ts new file mode 100644 index 000000000..7acbb0ef3 --- /dev/null +++ b/web/src/components/MemoEditor/view/linkCards.ts @@ -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); + }, + }, +}); diff --git a/web/src/components/MemoContent/useSearchMatchHighlight.ts b/web/src/components/MemoEditor/view/useSearchMatchHighlight.ts similarity index 100% rename from web/src/components/MemoContent/useSearchMatchHighlight.ts rename to web/src/components/MemoEditor/view/useSearchMatchHighlight.ts diff --git a/web/src/components/MemoContent/useTagNavigation.ts b/web/src/components/MemoEditor/view/useTagNavigation.ts similarity index 93% rename from web/src/components/MemoContent/useTagNavigation.ts rename to web/src/components/MemoEditor/view/useTagNavigation.ts index acb8b47ef..31dfca5a3 100644 --- a/web/src/components/MemoContent/useTagNavigation.ts +++ b/web/src/components/MemoEditor/view/useTagNavigation.ts @@ -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 diff --git a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx index 87e7eb0a9..346bec14e 100644 --- a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx +++ b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx @@ -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, diff --git a/web/src/components/MemoMetadata/Location/LocationDialog.tsx b/web/src/components/MemoMetadata/Location/LocationDialog.tsx index d3b918a09..fecc5882a 100644 --- a/web/src/components/MemoMetadata/Location/LocationDialog.tsx +++ b/web/src/components/MemoMetadata/Location/LocationDialog.tsx @@ -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"; diff --git a/web/src/components/MemoPanel/MemoPanelList.tsx b/web/src/components/MemoPanel/MemoPanelList.tsx index 6cedf3e89..01842f1e7 100644 --- a/web/src/components/MemoPanel/MemoPanelList.tsx +++ b/web/src/components/MemoPanel/MemoPanelList.tsx @@ -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:`; 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; + defaults?: Pick; /** 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 ? ( { setComposingFor(undefined); diff --git a/web/src/components/MemoPreview/MemoPreview.tsx b/web/src/components/MemoPreview/MemoPreview.tsx index 268770c3f..71a19083f 100644 --- a/web/src/components/MemoPreview/MemoPreview.tsx +++ b/web/src/components/MemoPreview/MemoPreview.tsx @@ -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 && (
- +
) ); diff --git a/web/src/components/MemoReactionListView/hooks.ts b/web/src/components/MemoReactionListView/hooks.ts index cf9f3a1b8..f544632f8 100644 --- a/web/src/components/MemoReactionListView/hooks.ts +++ b/web/src/components/MemoReactionListView/hooks.ts @@ -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"; diff --git a/web/src/components/MemoView/MemoView.tsx b/web/src/components/MemoView/MemoView.tsx index f8a0898cd..5ee970ed4 100644 --- a/web/src/components/MemoView/MemoView.tsx +++ b/web/src/components/MemoView/MemoView.tsx @@ -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((props, ref) => { showSpace, } = props; const cardRef = useRef(null); - const [showEditor, setShowEditor] = useState(false); - const [EditorComponent, setEditorComponent] = useState>(); + const [isEditing, setIsEditing] = useState(false); const [cardWidth, setCardWidth] = useState(0); const currentUser = useCurrentUser(); @@ -70,27 +55,23 @@ const MemoView = forwardRef((props, ref) => { const toggleBlurVisibility = useCallback(() => setShowBlurredContent((prev) => !prev), []); const { previewState, openPreview, setPreviewOpen } = useImagePreview(); - const editorHostRef = useRef(null); const focusMountedEditor = useCallback(() => { - const editorRoot = editorHostRef.current?.querySelector('.memo-editor-root[contenteditable="true"]'); - const fallbackInput = editorHostRef.current?.querySelector("textarea, input"); + const editorRoot = cardRef.current?.querySelector('.memo-editor-root[contenteditable="true"]'); + const fallbackInput = cardRef.current?.querySelector("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((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((props, ref) => { readonly, showBlurredContent, blurred, + isEditing, openEditor, + closeEditor, + onEditorFocusModeChange: handleFocusModeChange, toggleBlurVisibility, openPreview, }), @@ -177,7 +161,10 @@ const MemoView = forwardRef((props, ref) => { readonly, showBlurredContent, blurred, + isEditing, openEditor, + closeEditor, + handleFocusModeChange, toggleBlurVisibility, openPreview, ], @@ -222,26 +209,7 @@ const MemoView = forwardRef((props, ref) => { article ); - return ( - - {showEditor && EditorComponent ? ( -
- -
- ) : ( - memoDisplay - )} -
- ); + return {memoDisplay}; }); MemoView.displayName = "MemoView"; diff --git a/web/src/components/MemoView/MemoViewContext.tsx b/web/src/components/MemoView/MemoViewContext.tsx index a973c7869..250c89d90 100644 --- a/web/src/components/MemoView/MemoViewContext.tsx +++ b/web/src/components/MemoView/MemoViewContext.tsx @@ -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; } diff --git a/web/src/components/MemoView/components/MemoBody.tsx b/web/src/components/MemoView/components/MemoBody.tsx index c51c3d1c8..11030ea39 100644 --- a/web/src/components/MemoView/components/MemoBody.tsx +++ b/web/src/components/MemoView/components/MemoBody.tsx @@ -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 = ({ 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 = ({ 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 ( +
+ +
+ ); + } + return (
@@ -55,15 +81,12 @@ const MemoBody: React.FC = ({ compact }) => { {/* Compact bounds the whole body — attachments included — behind one Show more. Reactions stay outside so they never hide under the fade. */} - = ({ 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 = ({ timeDisplay = "relative", showC : undefined, }; const spaceMetadata = showSpace && 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 ( +
+
+ +
+
+ ); + } 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 = ({ timeDisplay = "relative", showC
{/* The time stays visible while the creator and Space badge can shrink and truncate. */}
- {showCreator && creator && } + {showsCreator && creator && } = ({ timeDisplay = "relative", showC /> {spaceMetadata}
- {memo.name === newMemoName && ( - - {t("memo.new-badge")} - - )} + {isNew && }
@@ -103,12 +117,21 @@ const MemoHeader: React.FC = ({ timeDisplay = "relative", showC ); }; +const NewBadge = () => { + const t = useTranslate(); + return ( + + {t("memo.new-badge")} + + ); +}; + /** * 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 }) => ( <> = ({ creator }) => ( {creator.displayName || creator.username} - + {withSeparator && ( + + )} ); diff --git a/web/src/components/PagedMemoList/PagedMemoList.tsx b/web/src/components/PagedMemoList/PagedMemoList.tsx index 8e05d2787..f8a7be4bd 100644 --- a/web/src/components/PagedMemoList/PagedMemoList.tsx +++ b/web/src/components/PagedMemoList/PagedMemoList.tsx @@ -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"; diff --git a/web/src/contexts/GlobalMemoEditorContext.tsx b/web/src/contexts/GlobalMemoEditorContext.tsx index 27f9fcb50..071def8c2 100644 --- a/web/src/contexts/GlobalMemoEditorContext.tsx +++ b/web/src/contexts/GlobalMemoEditorContext.tsx @@ -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>(); // 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(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 && ( {t("editor.new-memo")} - 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()); 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(); + 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 }) { diff --git a/web/src/hooks/useMemoQueries.ts b/web/src/hooks/useMemoQueries.ts index 81d920898..1a1be2606 100644 --- a/web/src/hooks/useMemoQueries.ts +++ b/web/src/hooks/useMemoQueries.ts @@ -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({ 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({ 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 & Pick; -type MemoCollectionQueryData = ListMemosResponse | InfiniteData; + +// 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 { +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 { 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(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(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(data: T | undefined, update: MemoPatch): T | undefined { - if (!data) { - return data; +function* memosInQueryData(data: unknown): Generator { + 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({ 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({ queryKey: memoKeys.all }, (data) => patchMemoListQueryData(data, update)); + queryClient.setQueriesData({ 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 = {}) { @@ -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() }); diff --git a/web/src/lib/markdownStyles.ts b/web/src/lib/markdownStyles.ts index abb835559..b78b2072c 100644 --- a/web/src/lib/markdownStyles.ts +++ b/web/src/lib/markdownStyles.ts @@ -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. */ diff --git a/web/src/lib/memo-markdown.ts b/web/src/lib/memo-markdown.ts index 74616e205..826c5473d 100644 --- a/web/src/lib/memo-markdown.ts +++ b/web/src/lib/memo-markdown.ts @@ -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; + readonly tags?: Pick; /** `mentions()` class and attributes, for links to the people who exist. */ - readonly mentions?: Pick; + readonly mentions?: Pick; } /** @@ -352,6 +352,9 @@ export const memoEditorLabels = (t: ReturnType): Partial { const { filters } = useMemoFilterContext(); const { memoFilter: contextFilter, selectedSpaceName, creatorUsername } = useSpaceContext(); const defaultCreateTime = useMemo(() => deriveDefaultCreateTimeFromFilters(filters), [filters]); - // Doubles as the remount key: the draft cache only reloads on mount, so the editor - // has to be rebuilt for the new Space rather than just re-pointed at another cache. - const editorCacheKey = spaceScopedCacheKey("home-memo-editor", selectedSpaceName); const memoFilter = useMemoFilters({ includeMemoViews: true, @@ -67,13 +63,11 @@ const Home = () => { return ( ); diff --git a/web/src/pages/MemoDetail.tsx b/web/src/pages/MemoDetail.tsx index 8b9b1f66c..81ba600af 100644 --- a/web/src/pages/MemoDetail.tsx +++ b/web/src/pages/MemoDetail.tsx @@ -3,7 +3,6 @@ import { ArrowUpLeftFromCircleIcon } from "lucide-react"; import { useCallback, useEffect, useMemo as useReactMemo, useRef, useState } from "react"; import { Link, Navigate, useLocation, useParams } from "react-router-dom"; import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection"; -import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext"; import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder"; import MemoView, { type MemoViewHandle } from "@/components/MemoView"; import { computeCommentAmount } from "@/components/MemoView/MemoViewContext"; @@ -11,6 +10,7 @@ import { createMemoNavigationState, resolveMemoDetailOrigin } from "@/components import { useAppSidebar } from "@/contexts/AppSidebarContext"; import { useAuth } from "@/contexts/AuthContext"; import { useInstance } from "@/contexts/InstanceContext"; +import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext"; import useMemoDetailError from "@/hooks/useMemoDetailError"; import { useInfiniteMemoComments, useMemo } from "@/hooks/useMemoQueries"; import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQueries"; diff --git a/web/tests/audience-menu.test.tsx b/web/tests/audience-menu.test.tsx index b4a1ae177..388a0ebdc 100644 --- a/web/tests/audience-menu.test.tsx +++ b/web/tests/audience-menu.test.tsx @@ -1,8 +1,8 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -import { createInitialState, EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/state"; -import AudienceMenu from "@/components/MemoEditor/Toolbar/AudienceMenu"; -import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar"; +import { createInitialState, EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/edit/state"; +import AudienceMenu from "@/components/MemoEditor/edit/Toolbar/AudienceMenu"; +import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar"; import { Visibility } from "@/types/proto/api/memo_service_pb"; const spacesQuery = vi.hoisted(() => ({ @@ -14,7 +14,7 @@ const spacesQuery = vi.hoisted(() => ({ isError: false, refetch: vi.fn(), })); -vi.mock("@/components/MemoEditor/Toolbar/InsertMenu", () => ({ default: () => null })); +vi.mock("@/components/MemoEditor/edit/Toolbar/InsertMenu", () => ({ default: () => null })); vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/test" }) })); vi.mock("@/hooks/useSpaceQueries", () => ({ useSpaces: () => spacesQuery })); diff --git a/web/tests/calendar-day-snapshot.test.tsx b/web/tests/calendar-day-snapshot.test.tsx index 9c630c810..b55f83731 100644 --- a/web/tests/calendar-day-snapshot.test.tsx +++ b/web/tests/calendar-day-snapshot.test.tsx @@ -11,7 +11,7 @@ const users: Record ({ +vi.mock("@/contexts/MentionResolutionContext", () => ({ useResolvedUser: (name: string, options?: { enabled?: boolean }) => (options?.enabled ? users[name] : undefined), useResolvedUsersByNames: (names: string[]) => new Map(names.map((name) => [name, users[name]])), })); diff --git a/web/tests/derive-default-create-time.test.ts b/web/tests/derive-default-create-time.test.ts index 19437d62e..afc88b8bf 100644 --- a/web/tests/derive-default-create-time.test.ts +++ b/web/tests/derive-default-create-time.test.ts @@ -4,7 +4,7 @@ import { deriveDefaultCreateTimeFromFilters, restampDefaultCreateTime, withTimeOfDay, -} from "@/components/MemoEditor/utils/deriveDefaultCreateTime"; +} from "@/components/MemoEditor/edit/utils/deriveDefaultCreateTime"; import type { MemoFilter } from "@/contexts/MemoFilterContext"; describe("deriveDefaultCreateTimeFromFilters", () => { diff --git a/web/tests/draft-key.test.ts b/web/tests/draft-key.test.ts new file mode 100644 index 000000000..feef85a59 --- /dev/null +++ b/web/tests/draft-key.test.ts @@ -0,0 +1,57 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { draftKeyFor, legacyDraftKeyFor, migrateLegacyDraft } from "@/components/MemoEditor/edit/draftKey"; +import { cacheService } from "@/components/MemoEditor/edit/services/cacheService"; + +describe("draft keys", () => { + it("follow what is edited", () => { + expect(draftKeyFor({ kind: "edit", name: "memos/a" })).toBe("edit:memos/a"); + expect(draftKeyFor({ kind: "comment", parent: "memos/a" })).toBe("comment:memos/a"); + expect(draftKeyFor({ kind: "new", scope: "home" })).toBe("new:home"); + expect(draftKeyFor({ kind: "new", scope: "home", space: "spaces/work" })).toBe("new:home:spaces/work"); + expect(draftKeyFor({ kind: "new", scope: "calendar:2026-10-18" })).toBe("new:calendar:2026-10-18"); + }); + + it("name the key each host chose before, where one existed", () => { + expect(legacyDraftKeyFor({ kind: "comment", parent: "memos/a" })).toBe("memos/a-comment"); + expect(legacyDraftKeyFor({ kind: "new", scope: "home" })).toBe("home-memo-editor"); + expect(legacyDraftKeyFor({ kind: "new", scope: "global", space: "spaces/x" })).toBe("global-memo-editor:spaces/x"); + expect(legacyDraftKeyFor({ kind: "new", scope: "calendar:2026-10-18" })).toBe("calendar-day-editor:2026-10-18"); + expect(legacyDraftKeyFor({ kind: "new", scope: "map:users/1:all:35,135" })).toBe("map-editor:users/1:all:35,135"); + expect(legacyDraftKeyFor({ kind: "new", scope: "elsewhere" })).toBeUndefined(); + expect(legacyDraftKeyFor({ kind: "edit", name: "memos/a" })).toBeUndefined(); + }); +}); + +describe("migrateLegacyDraft", () => { + beforeEach(() => { + const storage = new Map(); + vi.stubGlobal("localStorage", { + getItem: vi.fn((key: string) => storage.get(key) ?? null), + setItem: vi.fn((key: string, value: string) => storage.set(key, value)), + removeItem: vi.fn((key: string) => storage.delete(key)), + }); + }); + afterEach(() => vi.unstubAllGlobals()); + + it("moves a draft from the old key to the new one, once", () => { + const identity = { kind: "new", scope: "home", space: "spaces/work" } as const; + const oldKey = cacheService.key("users/1", "home-memo-editor:spaces/work"); + const newKey = cacheService.key("users/1", draftKeyFor(identity)); + cacheService.saveNow(oldKey, { content: "Unfinished", attachments: [] }); + + migrateLegacyDraft("users/1", identity); + + expect(cacheService.loadDraft(newKey).content).toBe("Unfinished"); + expect(localStorage.getItem(oldKey)).toBeNull(); + }); + + it("keeps a draft already under the new key", () => { + const identity = { kind: "comment", parent: "memos/a" } as const; + cacheService.saveNow(cacheService.key("users/1", "memos/a-comment"), { content: "old", attachments: [] }); + cacheService.saveNow(cacheService.key("users/1", draftKeyFor(identity)), { content: "new", attachments: [] }); + + migrateLegacyDraft("users/1", identity); + + expect(cacheService.loadDraft(cacheService.key("users/1", draftKeyFor(identity))).content).toBe("new"); + }); +}); diff --git a/web/tests/editor-commit-button.test.tsx b/web/tests/editor-commit-button.test.tsx index 6745d6611..23d6f9923 100644 --- a/web/tests/editor-commit-button.test.tsx +++ b/web/tests/editor-commit-button.test.tsx @@ -1,10 +1,10 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; -import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state"; -import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar"; +import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state"; +import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar"; -vi.mock("@/components/MemoEditor/Toolbar/InsertMenu", () => ({ default: () => null })); -vi.mock("@/components/MemoEditor/Toolbar/AudienceMenu", () => ({ default: () => null })); +vi.mock("@/components/MemoEditor/edit/Toolbar/InsertMenu", () => ({ default: () => null })); +vi.mock("@/components/MemoEditor/edit/Toolbar/AudienceMenu", () => ({ default: () => null })); vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); let dispatchSaving: ((saving: boolean) => void) | undefined; diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx index 98c7715fd..b4557fa02 100644 --- a/web/tests/editor-controller.test.tsx +++ b/web/tests/editor-controller.test.tsx @@ -2,14 +2,16 @@ import { render } from "@testing-library/react"; import type { EditorMode } from "@usememos/editor"; import { createRef } from "react"; import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; -import type { UploadAnchorDescriptor } from "@/components/MemoEditor/Editor/uploadAnchors"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; +import Editor from "@/components/MemoEditor/edit/Editor"; +import type { EditorController } from "@/components/MemoEditor/edit/types/editorController"; +import type { UploadAnchorDescriptor } from "@/components/MemoEditor/edit/uploadAnchors"; vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }), + userDetailQueryOptions: () => ({}), })); +vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: undefined }) })); function setup(value = "", mode: EditorMode = "rich") { const ref = createRef(); diff --git a/web/tests/editor-inline-image-validation.test.ts b/web/tests/editor-inline-image-validation.test.ts index 1c6d5d2c9..29b7e4b1d 100644 --- a/web/tests/editor-inline-image-validation.test.ts +++ b/web/tests/editor-inline-image-validation.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; -import { validationService } from "@/components/MemoEditor/services/validationService"; -import { createInitialState } from "@/components/MemoEditor/state"; +import { validationService } from "@/components/MemoEditor/edit/services/validationService"; +import { createInitialState } from "@/components/MemoEditor/edit/state"; describe("inline image editor validation", () => { test("blocks saving while an inline image insertion is unresolved", () => { diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsx index e38dc3d1b..43751476c 100644 --- a/web/tests/editor-suggestions.test.tsx +++ b/web/tests/editor-suggestions.test.tsx @@ -1,15 +1,16 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { useRef } from "react"; import { describe, expect, it, vi } from "vitest"; -import { EditorContent } from "@/components/MemoEditor/components/EditorContent"; -import { EditorSuggestions, SuggestionsBar } from "@/components/MemoEditor/components/EditorSuggestions"; -import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; +import { EditorContent } from "@/components/MemoEditor/edit/components/EditorContent"; +import { EditorSuggestions, SuggestionsBar } from "@/components/MemoEditor/edit/components/EditorSuggestions"; +import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state"; +import type { EditorController } from "@/components/MemoEditor/edit/types/editorController"; import { getMemoSuggestions, type MemoSuggestion } from "@/lib/memo-suggestions"; import { Visibility } from "@/types/proto/api/memo_service_pb"; vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) })); +vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: undefined }) })); /** A caret at `offset` in block `block`. */ const caret = (block: number, offset: number) => ({ anchor: { block, offset }, focus: { block, offset } }); diff --git a/web/tests/editor-tag-autocomplete.test.ts b/web/tests/editor-tag-autocomplete.test.ts index f6405a517..8c251200f 100644 --- a/web/tests/editor-tag-autocomplete.test.ts +++ b/web/tests/editor-tag-autocomplete.test.ts @@ -1,6 +1,6 @@ import { matchToken, type SuggestionAllowContext, scanTags } from "@usememos/editor"; import { describe, expect, it } from "vitest"; -import { allowTagSuggestion, rankTags } from "@/components/MemoEditor/Editor/extensions"; +import { allowTagSuggestion, rankTags } from "@/components/MemoEditor/edit/extensions"; const match = matchToken(scanTags); diff --git a/web/tests/editor.test.tsx b/web/tests/editor.test.tsx index 7e9fad15d..c1a2ffc11 100644 --- a/web/tests/editor.test.tsx +++ b/web/tests/editor.test.tsx @@ -2,14 +2,15 @@ import { create } from "@bufbuild/protobuf"; import { render, waitFor } from "@testing-library/react"; import { createRef } from "react"; import { describe, expect, it, vi } from "vitest"; -import Editor from "@/components/MemoEditor/Editor"; -import type { EditorController } from "@/components/MemoEditor/types/editorController"; +import Editor from "@/components/MemoEditor/edit/Editor"; +import type { EditorController } from "@/components/MemoEditor/edit/types/editorController"; import { UserSetting_TagsSettingSchema } from "@/types/proto/api/user_service_pb"; import { ColorSchema } from "@/types/proto/google/type/color_pb"; const queries = vi.hoisted(() => ({ useTagCounts: vi.fn(() => ({ data: {} })), users: new Map(), + tagsSetting: undefined as unknown, })); vi.mock("@/hooks/useUserQueries", () => ({ @@ -17,7 +18,9 @@ vi.mock("@/hooks/useUserQueries", () => ({ useUsersByUsernames: (usernames: string[]) => ({ data: usernames.length ? new Map(usernames.map((username) => [username, queries.users.get(username)])) : undefined, }), + userDetailQueryOptions: () => ({}), })); +vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: queries.tagsSetting }) })); const baseProps = { className: "x", @@ -89,18 +92,20 @@ describe("Editor", () => { expect(root?.style.getPropertyValue("--mbe-placeholder")).toBe('"有什么想法?"'); }); - it("draws tags as the memo view does, in their custom colors", async () => { - const tagsSetting = create(UserSetting_TagsSettingSchema, { - tags: { work: { backgroundColor: create(ColorSchema, { red: 1, green: 0, blue: 0 }) } }, - }); + it("draws tags as the memo view does, in the viewer's custom colors", async () => { + queries.tagsSetting = undefined; const { container, rerender } = render(); const tag = (name: string) => container.querySelector(`.mbe-tag[data-tag="${name}"]`); expect(tag("life")).toHaveClass("rounded-full", "border-primary"); expect(tag("work")).not.toHaveAttribute("style"); - rerender(); + queries.tagsSetting = create(UserSetting_TagsSettingSchema, { + tags: { work: { backgroundColor: create(ColorSchema, { red: 1, green: 0, blue: 0 }) } }, + }); + rerender(); await waitFor(() => expect(tag("work")?.getAttribute("style")).toContain("color-mix")); expect(tag("work")).not.toHaveClass("border-primary"); + queries.tagsSetting = undefined; }); it("draws mentions of people who exist as the memo view does", async () => { diff --git a/web/tests/focus-mode-exit-button.test.tsx b/web/tests/focus-mode-exit-button.test.tsx index 2df835612..d467020e3 100644 --- a/web/tests/focus-mode-exit-button.test.tsx +++ b/web/tests/focus-mode-exit-button.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; -import { FocusModeExitButton } from "@/components/MemoEditor/components/FocusModeOverlay"; +import { FocusModeExitButton } from "@/components/MemoEditor/edit/components/FocusModeOverlay"; vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key })); diff --git a/web/tests/global-memo-editor.test.tsx b/web/tests/global-memo-editor.test.tsx index e764903f2..e5d1b261d 100644 --- a/web/tests/global-memo-editor.test.tsx +++ b/web/tests/global-memo-editor.test.tsx @@ -1,7 +1,7 @@ -import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { useState } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { MemoEditorProps } from "@/components/MemoEditor/types"; +import type { MemoEditorDraftProps } from "@/components/MemoEditor"; import { GlobalMemoEditorProvider, useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext"; const DIALOG = { name: "editor.new-memo" }; @@ -13,8 +13,9 @@ vi.mock("@/hooks/useMemoSuggestions", () => ({ const mocks = vi.hoisted(() => ({ currentUser: { name: "users/test" } as { name: string } | undefined, isUserSettingsInitialized: true, - editorProps: undefined as MemoEditorProps | undefined, - loadMemoEditor: vi.fn(), + editorProps: undefined as MemoEditorDraftProps | undefined, + preload: vi.fn(), + renderEditor: ((_props: MemoEditorDraftProps) => null) as (props: MemoEditorDraftProps) => React.ReactNode, setMobileOpen: vi.fn(), setQuickFindOpen: vi.fn(), selectedSpaceName: undefined as string | undefined, @@ -28,8 +29,10 @@ vi.mock("react-router-dom", async (importOriginal) => ({ useLocation: () => ({ pathname: mocks.pathname }), })); -vi.mock("@/components/MemoEditor/loader", () => ({ - loadMemoEditor: mocks.loadMemoEditor, +vi.mock("@/components/MemoEditor", () => ({ + preloadMemoEditing: mocks.preload, + // Looked up at render time, after the mock component below exists. + MemoEditor: (props: MemoEditorDraftProps) => mocks.renderEditor(props), })); vi.mock("@/contexts/AppSidebarContext", () => ({ @@ -56,7 +59,7 @@ vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key, })); -const MockMemoEditor = (props: MemoEditorProps) => { +const MockMemoEditor = (props: MemoEditorDraftProps) => { mocks.editorProps = props; return (
@@ -122,6 +125,8 @@ const openViaTrigger = async () => { return trigger; }; +mocks.renderEditor = (props) => ; + const expectClosed = () => waitFor(() => expect(screen.queryByRole("dialog", DIALOG)).not.toBeInTheDocument()); describe("GlobalMemoEditorProvider", () => { @@ -129,7 +134,6 @@ describe("GlobalMemoEditorProvider", () => { mocks.currentUser = { name: "users/test" }; mocks.isUserSettingsInitialized = true; mocks.editorProps = undefined; - mocks.loadMemoEditor.mockResolvedValue({ default: MockMemoEditor }); mocks.setMobileOpen.mockClear(); mocks.setQuickFindOpen.mockClear(); mocks.selectedSpaceName = undefined; @@ -200,7 +204,7 @@ describe("GlobalMemoEditorProvider", () => { // exits by dismissing this dialog rather than collapsing inline. expect(mocks.editorProps).toMatchObject({ autoFocus: true, - cacheKey: "global-memo-editor", + draft: { scope: "global", space: undefined }, suggestions: [{ id: "tag:work" }], onFocusModeExit: expect.any(Function), }); @@ -265,42 +269,10 @@ describe("GlobalMemoEditorProvider", () => { fireEvent.click(screen.getByRole("button", { name: "Open editor" })); - expect(mocks.loadMemoEditor).not.toHaveBeenCalled(); + expect(mocks.preload).not.toHaveBeenCalled(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); - it("invalidates a pending open request across sign-out and same-user sign-in", async () => { - let resolveEditorLoad!: (module: { default: typeof MockMemoEditor }) => void; - mocks.loadMemoEditor.mockReturnValue( - new Promise((resolve) => { - resolveEditorLoad = resolve; - }), - ); - const view = renderProvider(); - - fireEvent.click(screen.getByRole("button", { name: "Open editor" })); - expect(mocks.loadMemoEditor).toHaveBeenCalledOnce(); - - mocks.currentUser = undefined; - view.rerender( - - - , - ); - mocks.currentUser = { name: "users/test" }; - view.rerender( - - - , - ); - - await act(async () => { - resolveEditorLoad({ default: MockMemoEditor }); - }); - - expect(screen.queryByRole("dialog", DIALOG)).not.toBeInTheDocument(); - }); - it("does not resurrect an open composer after the same user signs out and back in", async () => { const view = renderProvider(); fireEvent.click(screen.getByRole("button", { name: "Open editor" })); @@ -329,7 +301,7 @@ describe("GlobalMemoEditorProvider", () => { fireEvent.keyDown(window, { key: "m", shiftKey: true, metaKey: true }); - expect(mocks.loadMemoEditor).not.toHaveBeenCalled(); + expect(mocks.preload).not.toHaveBeenCalled(); }); it("disables new memo while the route Space is unresolved or inaccessible", () => { @@ -338,7 +310,7 @@ describe("GlobalMemoEditorProvider", () => { mocks.isSpaceReady = false; renderProvider(); fireEvent.click(screen.getByRole("button", { name: "Open editor" })); - expect(mocks.loadMemoEditor).not.toHaveBeenCalled(); + expect(mocks.preload).not.toHaveBeenCalled(); }); it("snapshots the selected Space when opening the composer", async () => { @@ -346,14 +318,12 @@ describe("GlobalMemoEditorProvider", () => { await openViaTrigger(); expect(mocks.editorProps).toMatchObject({ - cacheKey: "global-memo-editor:spaces/product", - defaultSpace: "spaces/product", + draft: { scope: "global", space: "spaces/product" }, }); mocks.selectedSpaceName = "spaces/other"; expect(mocks.editorProps).toMatchObject({ - cacheKey: "global-memo-editor:spaces/product", - defaultSpace: "spaces/product", + draft: { scope: "global", space: "spaces/product" }, }); }); @@ -367,8 +337,7 @@ describe("GlobalMemoEditorProvider", () => { await openViaTrigger(); expect(mocks.editorProps).toMatchObject({ - cacheKey: "global-memo-editor:spaces/product", - defaultSpace: "spaces/product", + draft: { scope: "global", space: "spaces/product" }, }); }); @@ -390,8 +359,7 @@ describe("GlobalMemoEditorProvider", () => { await openViaTrigger(); expect(mocks.editorProps).toMatchObject({ - cacheKey: "global-memo-editor", - defaultSpace: undefined, + draft: { scope: "global", space: undefined }, }); }); }); diff --git a/web/tests/helpers/memo-save-operations.ts b/web/tests/helpers/memo-save-operations.ts new file mode 100644 index 000000000..4bef8621c --- /dev/null +++ b/web/tests/helpers/memo-save-operations.ts @@ -0,0 +1,20 @@ +import { create } from "@bufbuild/protobuf"; +import { FieldMaskSchema } from "@bufbuild/protobuf/wkt"; +import type { MemoSaveOperations } from "@/components/MemoEditor/edit/services/memoService"; +import { memoServiceClient } from "@/connect"; +import { MemoSchema } from "@/types/proto/api/memo_service_pb"; + +/** + * Save operations over the bare (mocked) client, shaping requests as the memo + * mutation hooks do, for tests of the service's own logic. + */ +export const clientSaveOperations: MemoSaveOperations = { + getMemo: (name) => memoServiceClient.getMemo({ name }), + updateMemo: (update, paths) => + memoServiceClient.updateMemo({ + memo: create(MemoSchema, update as Record), + updateMask: create(FieldMaskSchema, { paths }), + }), + createMemo: (memo, parent) => + parent ? memoServiceClient.createMemoComment({ parent, comment: memo }) : memoServiceClient.createMemo({ memo }), +}; diff --git a/web/tests/home-loading-boundary.test.tsx b/web/tests/home-loading-boundary.test.tsx index 9130595ce..b3350aae3 100644 --- a/web/tests/home-loading-boundary.test.tsx +++ b/web/tests/home-loading-boundary.test.tsx @@ -16,7 +16,7 @@ const state = vi.hoisted(() => ({ })); vi.mock("@/components/MemoEditor", () => ({ - default: (props: Record) => { + MemoEditor: (props: Record) => { state.editorProps = props; return
; }, @@ -110,7 +110,7 @@ describe("", () => { expect(screen.getByTestId("memo-editor")).toBeInTheDocument(); expect(screen.getByTestId("memo-view")).toBeInTheDocument(); expect(state.listProps).toMatchObject({ contextFilter: undefined }); - expect(state.editorProps).toMatchObject({ cacheKey: "home-memo-editor", defaultSpace: undefined }); + expect(state.editorProps).toMatchObject({ draft: { scope: "home", space: undefined } }); expect(state.editorProps?.autoFocus).toEqual(expect.any(Function)); expect(state.editorProps?.suggestions).toEqual([{ id: "tag:work" }]); expect(state.filterOptions).not.toHaveProperty("creatorName"); @@ -131,8 +131,7 @@ describe("", () => { expect(state.listProps).toMatchObject({ contextFilter: 'space == "spaces/product"' }); expect(state.editorProps).toMatchObject({ - cacheKey: "home-memo-editor:spaces/product", - defaultSpace: "spaces/product", + draft: { scope: "home", space: "spaces/product" }, }); }); }); diff --git a/web/tests/inline-image-upload-files.test.ts b/web/tests/inline-image-upload-files.test.ts index 904dc39a5..e5dff8a45 100644 --- a/web/tests/inline-image-upload-files.test.ts +++ b/web/tests/inline-image-upload-files.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; -import { pairAppleLivePhotoFiles } from "@/components/MemoEditor/hooks"; -import { splitInlineLocalFiles } from "@/components/MemoEditor/hooks/useInlineImageUpload"; -import type { LocalFile } from "@/components/MemoEditor/types/attachment"; +import { pairAppleLivePhotoFiles } from "@/components/MemoEditor/edit/hooks"; +import { splitInlineLocalFiles } from "@/components/MemoEditor/edit/hooks/useInlineImageUpload"; +import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment"; import { MotionMediaRole } from "@/types/proto/api/attachment_service_pb"; const localFile = (name: string, type: string): LocalFile => ({ diff --git a/web/tests/insert-menu.test.tsx b/web/tests/insert-menu.test.tsx index a7bea8aa7..4dcbabba7 100644 --- a/web/tests/insert-menu.test.tsx +++ b/web/tests/insert-menu.test.tsx @@ -1,8 +1,8 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { beforeAll, describe, expect, test, vi } from "vitest"; -import { createInitialState, EditorProvider } from "@/components/MemoEditor/state"; -import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar"; -import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu"; +import { createInitialState, EditorProvider } from "@/components/MemoEditor/edit/state"; +import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar"; +import InsertMenu from "@/components/MemoEditor/edit/Toolbar/InsertMenu"; vi.mock("@/utils/i18n", async (importOriginal) => ({ ...(await importOriginal()), diff --git a/web/tests/map-view.test.tsx b/web/tests/map-view.test.tsx index 118590fa7..32949e2f9 100644 --- a/web/tests/map-view.test.tsx +++ b/web/tests/map-view.test.tsx @@ -4,11 +4,11 @@ import type { ReactNode } from "react"; import { MemoryRouter } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MapView } from "@/components/MapView/MapView"; -import type { MemoEditorProps } from "@/components/MemoEditor/types"; +import type { MemoEditorDraftProps } from "@/components/MemoEditor"; import { type Memo, MemoSchema } from "@/types/proto/api/memo_service_pb"; const mocks = vi.hoisted(() => ({ - editor: {} as MemoEditorProps, + editor: {} as MemoEditorDraftProps, refetch: vi.fn(), toast: vi.fn(), memos: [] as Memo[], @@ -35,13 +35,13 @@ vi.mock("@/components/MapView/useMapMemos", () => ({ })); vi.mock("@/components/MapView/useMapPins", () => ({ useMapPins: () => new Map() })); vi.mock("@/components/MemoEditor", () => ({ - default: (props: MemoEditorProps) => { + MemoEditor: (props: MemoEditorDraftProps) => { mocks.editor = props; return
; }, })); vi.mock("@/components/MemoView", () => ({ default: () =>

Memo

})); -vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({ +vi.mock("@/contexts/MentionResolutionContext", () => ({ MentionResolutionProvider: ({ children }: { children: ReactNode }) => children, })); vi.mock("@/contexts/NewMemoContext", () => ({ NewMemoProvider: ({ children }: { children: ReactNode }) => children })); @@ -94,8 +94,8 @@ describe("map composer", () => { it("seeds the selected point and Space and releases controls after save", async () => { mocks.refetch.mockResolvedValue({ data: { pages: [{ memos: [item] }] } }); start(); - expect(mocks.editor.defaultSpace).toBe("spaces/travel"); - expect(mocks.editor.defaultLocation).toEqual(item.location); + expect(mocks.editor.draft.space).toBe("spaces/travel"); + expect(mocks.editor.draft.location).toEqual(item.location); act(() => mocks.editor.onSavingChange?.(true)); expect(screen.getByTestId("panel")).toHaveAttribute("data-busy", "true"); act(() => mocks.editor.onConfirm?.("memos/one")); @@ -133,7 +133,7 @@ describe("map place labels", () => { it("never copies another author's label into a new memo", () => { mocks.memos = [other]; start("memo=memos%2Ftwo"); - expect(mocks.editor.defaultLocation).toMatchObject({ latitude: 35, longitude: 135, placeholder: "35.0000°, 135.0000°" }); + expect(mocks.editor.draft.location).toMatchObject({ latitude: 35, longitude: 135, placeholder: "35.0000°, 135.0000°" }); // A single author's label still titles their own memos. expect(screen.getByTestId("panel")).toHaveAttribute("data-title", "Mom's house"); }); @@ -143,7 +143,7 @@ describe("map place labels", () => { start("memo=memos%2Ftwo&memo=memos%2Fone"); expect(screen.getByTestId("panel")).toHaveAttribute("data-title", "35.0000°, 135.0000°"); // The writer's own label at the point is theirs to reuse. - expect(mocks.editor.defaultLocation).toMatchObject({ placeholder: "Kyoto" }); + expect(mocks.editor.draft.location).toMatchObject({ placeholder: "Kyoto" }); }); }); diff --git a/web/tests/media-metadata-exif-fixture.test.ts b/web/tests/media-metadata-exif-fixture.test.ts index 4d8ce499a..34fefc792 100644 --- a/web/tests/media-metadata-exif-fixture.test.ts +++ b/web/tests/media-metadata-exif-fixture.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mediaMetadataService } from "@/components/MemoEditor/services/mediaMetadataService"; +import { mediaMetadataService } from "@/components/MemoEditor/edit/services/mediaMetadataService"; describe("mediaMetadataService EXIF fixture", () => { beforeEach(() => { diff --git a/web/tests/media-metadata-service.test.ts b/web/tests/media-metadata-service.test.ts index dc43f40c1..68b73b3f7 100644 --- a/web/tests/media-metadata-service.test.ts +++ b/web/tests/media-metadata-service.test.ts @@ -8,7 +8,7 @@ vi.mock("exifr", () => ({ parse: mocks.parseExif, })); -import { mediaMetadataService } from "@/components/MemoEditor/services/mediaMetadataService"; +import { mediaMetadataService } from "@/components/MemoEditor/edit/services/mediaMetadataService"; describe("mediaMetadataService", () => { beforeEach(() => { diff --git a/web/tests/memo-body-compact.test.tsx b/web/tests/memo-body-compact.test.tsx index 996c793f5..2bff6de79 100644 --- a/web/tests/memo-body-compact.test.tsx +++ b/web/tests/memo-body-compact.test.tsx @@ -21,12 +21,12 @@ vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key, })); -vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({ +vi.mock("@/contexts/MentionResolutionContext", () => ({ useResolvedMentionUsernames: () => new Set(), })); -vi.mock("@/components/MemoContent", () => ({ - default: ({ content }: { content: string }) =>
{content}
, +vi.mock("@/components/MemoEditor/MemoEditor", () => ({ + MemoEditor: ({ name }: { name: string }) =>
{mockState.memo.content ?? name}
, })); vi.mock("@/hooks/useMemoQueries", () => ({ diff --git a/web/tests/memo-comment-section.test.tsx b/web/tests/memo-comment-section.test.tsx index be5fcda93..4b736066d 100644 --- a/web/tests/memo-comment-section.test.tsx +++ b/web/tests/memo-comment-section.test.tsx @@ -3,31 +3,28 @@ import { render, screen } from "@testing-library/react"; import { act, createRef } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection"; -import type { MemoEditorProps } from "@/components/MemoEditor/types"; import { State } from "@/types/proto/api/common_pb"; import { MemoSchema } from "@/types/proto/api/memo_service_pb"; const mocks = vi.hoisted(() => ({ currentUser: { name: "users/alice" } as { name: string } | undefined, - loadMemoEditor: vi.fn(), })); -vi.mock("@/components/MemoEditor/loader", () => ({ loadMemoEditor: mocks.loadMemoEditor })); +vi.mock("@/components/MemoEditor", () => ({ + preloadMemoEditing: () => Promise.resolve(), + MemoEditor: ({ autoFocus, draft }: { autoFocus?: boolean; draft: { parent?: string } }) => ( +
+