AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(editor): remember outline folding per note and add bulk controls
tianma-if49225fb67b67
diff --git a/apps/web/src/components/EditorOutline.tsx b/apps/web/src/components/EditorOutline.tsxindex 1d1c9b03..f1ebbe9a 100644--- a/apps/web/src/components/EditorOutline.tsx+++ b/apps/web/src/components/EditorOutline.tsx@@ -1,15 +1,19 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";import { createPortal } from "react-dom";+import type { Transaction } from "@tiptap/pm/state";import type { Editor } from "@tiptap/react";-import { ChevronDown, ChevronRight, ListTree } from "lucide-react";+import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown, ListTree } from "lucide-react";import { useTranslation } from "react-i18next";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { buildOutlineTree, type OutlineItem, type OutlineTreeItem } from "@/lib/editor-outline";+import { mapCollapsedOutlinePositions, readOutlineSnapshot, restoreOutlinePositions, writeOutlineSnapshot, type OutlineSnapshot } from "@/lib/editor-outline-state";import { cn } from "@/lib/utils";import { EDITOR_OUTLINE_WIDTH } from "@/lib/workspace-ui";type EditorOutlineProps = {editor: Editor | null;+ memoId: string;+ editingMemoIdRef: RefObject<string | null>;scrollContainer: HTMLDivElement | null;// Non-scrolling slot at the editor pane's top-right. The collapsed button// portals here so it stays put while the note scrolls.@@ -35,13 +39,9 @@ const getOutlineItems = (editor: Editor): OutlineItem[] => {}const text = node.textContent.trim();- if (text) {- items.push({- level: Number(node.attrs.level) || 1,- pos,- text,- });- }+ // Keep empty headings in the identity snapshot: clearing a title before+ // retyping it must not discard its folding choice.+ items.push({ level: Number(node.attrs.level) || 1, pos, text });});return items;@@ -53,7 +53,7 @@ const sameOutlineItems = (left: OutlineItem[], right: OutlineItem[]) =>return other?.level === item.level && other.pos === item.pos && other.text === item.text;});-export const EditorOutline = ({ editor, scrollContainer, collapsedAnchor, collapsed, shortcutLabel, onCollapsedChange }: EditorOutlineProps) => {+export const EditorOutline = ({ editor, memoId, editingMemoIdRef, scrollContainer, collapsedAnchor, collapsed, shortcutLabel, onCollapsedChange }: EditorOutlineProps) => {const { t } = useTranslation();const [items, setItems] = useState<OutlineItem[]>([]);const [activePos, setActivePos] = useState<number | null>(null);@@ -61,15 +61,63 @@ export const EditorOutline = ({ editor, scrollContainer, collapsedAnchor, collapconst scrollTrackingPausedUntilRef = useRef(0);const tree = useMemo(() => buildOutlineTree(items), [items]);- const refresh = useCallback(() => {- if (!editor || editor.isDestroyed) {- setItems([]);- return;- }+ const snapshotRef = useRef<OutlineSnapshot>({ items: [], collapsed: [] });+ const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const save = useCallback(() => {+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);+ saveTimerRef.current = setTimeout(() => {+ writeOutlineSnapshot(memoId, snapshotRef.current);+ saveTimerRef.current = null;+ }, 250);+ }, [memoId]);++ useEffect(() => {+ if (!editor || editor.isDestroyed || editingMemoIdRef.current !== memoId) return;+ const initialItems = getOutlineItems(editor);+ const initialCollapsed = restoreOutlinePositions(readOutlineSnapshot(memoId), initialItems);+ snapshotRef.current = { items: initialItems, collapsed: [...initialCollapsed] };+ setItems(initialItems.filter((item) => item.text));+ setCollapsedPositions(initialCollapsed);++ const refresh = ({ transaction }: { transaction: Transaction }) => {+ if (!transaction.docChanged || editingMemoIdRef.current !== memoId || editor.isDestroyed) return;+ const nextItems = getOutlineItems(editor);+ const previous = snapshotRef.current;+ // Draft hydration, source-mode edits and remote refreshes may replace the+ // entire document. Transaction positions cannot identify headings then.+ const replacesDocument = transaction.mapping.maps.some((map) => {+ let replaces = false;+ map.forEach((from, to) => { if (from === 0 && to >= transaction.before.content.size) replaces = true; });+ return replaces;+ });+ const nextCollapsed = replacesDocument+ ? restoreOutlinePositions(previous, nextItems)+ : mapCollapsedOutlinePositions(new Set(previous.collapsed), transaction.mapping, nextItems);+ snapshotRef.current = { items: nextItems, collapsed: [...nextCollapsed] };+ const visibleItems = nextItems.filter((item) => item.text);+ setItems((current) => sameOutlineItems(current, visibleItems) ? current : visibleItems);+ setCollapsedPositions(nextCollapsed);+ save();+ };+ const flush = () => {+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);+ saveTimerRef.current = null;+ writeOutlineSnapshot(memoId, snapshotRef.current);+ };+ editor.on("transaction", refresh);+ window.addEventListener("pagehide", flush);+ return () => {+ editor.off("transaction", refresh);+ window.removeEventListener("pagehide", flush);+ flush();+ };+ }, [editor, memoId, editingMemoIdRef, save]);- const nextItems = getOutlineItems(editor);- setItems((currentItems) => (sameOutlineItems(currentItems, nextItems) ? currentItems : nextItems));- }, [editor]);+ const changeCollapsedPositions = (next: Set<number>) => {+ snapshotRef.current = { ...snapshotRef.current, collapsed: [...next] };+ setCollapsedPositions(next);+ writeOutlineSnapshot(memoId, snapshotRef.current);+ };const updateActiveItem = useCallback(() => {if (!editor || editor.isDestroyed || items.length === 0) {@@ -87,31 +135,20 @@ export const EditorOutline = ({ editor, scrollContainer, collapsedAnchor, collap}, [editor, items]);useEffect(() => {- refresh();if (!editor) {return;}- editor.on("update", refresh);editor.on("selectionUpdate", updateActiveItem);return () => {- editor.off("update", refresh);editor.off("selectionUpdate", updateActiveItem);};- }, [editor, refresh, updateActiveItem]);+ }, [editor, updateActiveItem]);useEffect(() => {updateActiveItem();}, [updateActiveItem]);- useEffect(() => {- const availablePositions = new Set(items.map((item) => item.pos));- setCollapsedPositions((current) => {- const next = new Set([...current].filter((pos) => availablePositions.has(pos)));- return next.size === current.size ? current : next;- });- }, [items]);-useEffect(() => {if (!scrollContainer || items.length === 0) {return;@@ -185,17 +222,22 @@ export const EditorOutline = ({ editor, scrollContainer, collapsedAnchor, collap};const toggleItem = (pos: number) => {- setCollapsedPositions((current) => {- const next = new Set(current);- if (next.has(pos)) {- next.delete(pos);- } else {- next.add(pos);- }- return next;- });+ const next = new Set(snapshotRef.current.collapsed);+ if (next.has(pos)) next.delete(pos);+ else next.add(pos);+ changeCollapsedPositions(next);};+ const parentPositions = useMemo(() => {+ const positions: number[] = [];+ const visit = (nodes: OutlineTreeItem[]) => nodes.forEach((node) => {+ if (node.children.length) positions.push(node.pos);+ visit(node.children);+ });+ visit(tree);+ return positions;+ }, [tree]);+const renderItems = (treeItems: OutlineTreeItem[], depth = 0) => (<ol className={cn("space-y-0.5", depth > 0 && "py-0.5")}>{treeItems.map((item) => {@@ -309,6 +351,29 @@ export const EditorOutline = ({ editor, scrollContainer, collapsedAnchor, collap</TooltipTrigger><TooltipContent side="left">{outlineToggleLabel}</TooltipContent></Tooltip>+ {!collapsed && parentPositions.length > 0 && (+ <div className="flex shrink-0 items-center gap-0.5">+ {([+ ["editor.collapseAllOutline", ChevronsDownUp, true],+ ["editor.expandAllOutline", ChevronsUpDown, false],+ ] as const).map(([label, Icon, collapseAll]) => (+ <Tooltip key={label}>+ <TooltipTrigger asChild>+ <button+ type="button"+ className="flex h-7 w-7 items-center justify-center rounded text-slate-500 hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-900/20 disabled:opacity-40"+ aria-label={t(label)}+ disabled={collapseAll ? parentPositions.every((pos) => collapsedPositions.has(pos)) : collapsedPositions.size === 0}+ onClick={() => changeCollapsedPositions(new Set(collapseAll ? parentPositions : []))}+ >+ <Icon className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ </TooltipTrigger>+ <TooltipContent>{t(label)}</TooltipContent>+ </Tooltip>+ ))}+ </div>+ )}</div>{!collapsed && (diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 357d97a0..a7393779 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -4611,8 +4611,11 @@ const RichEditorPane = ({noteProse={noteProse}/>)}- {showDocumentOutline && (+ {showDocumentOutline && memo && hydratedEditorMemoId === memo.id && (<EditorOutline+ key={memo.id}+ memoId={memo.id}+ editingMemoIdRef={editingMemoIdRef}editor={editor}scrollContainer={editorScrollContainer}collapsedAnchor={collapsedOutlineAnchor}diff --git a/apps/web/src/lib/editor-outline-state.test.mjs b/apps/web/src/lib/editor-outline-state.test.mjsnew file mode 100644index 00000000..a735f776--- /dev/null+++ b/apps/web/src/lib/editor-outline-state.test.mjs@@ -0,0 +1,93 @@+import { describe, expect, test } from "bun:test";+import { Schema } from "@tiptap/pm/model";+import { Transform } from "@tiptap/pm/transform";+import { mapCollapsedOutlinePositions, readOutlineSnapshot, restoreOutlinePositions, writeOutlineSnapshot } from "./editor-outline-state";++const schema = new Schema({ nodes: {+ doc: { content: "block+" },+ heading: { group: "block", content: "text*", attrs: { level: { default: 1 } } },+ paragraph: { group: "block", content: "text*" },+ text: {},+} });+const heading = (text, level = 1) => schema.node("heading", { level }, schema.text(text));+const outline = (doc) => {+ const items = [];+ doc.descendants((node, pos) => {+ if (node.type.name === "heading") items.push({ pos, level: node.attrs.level, text: node.textContent.trim() });+ });+ return items;+};++describe("outline identity during editing", () => {+ test("tracks renamed duplicate headings and shifts caused by preceding edits", () => {+ const doc = schema.node("doc", null, [heading("Same"), heading("Child", 2), heading("Same"), heading("Child", 2)]);+ const items = outline(doc);+ const pos = items[2].pos;+ const tr = new Transform(doc).insert(0, schema.node("paragraph", null, schema.text("Inserted body")));+ const shifted = tr.mapping.map(pos);+ tr.insert(shifted + 2, schema.text(" renamed"));+ const result = mapCollapsedOutlinePositions(new Set([pos]), tr.mapping, outline(tr.doc));+ expect([...result]).toEqual([shifted]);+ expect(outline(tr.doc).find((item) => item.pos === shifted).text).toContain("renamed");+ });++ test("does not transfer state to an inserted replacement at the same position", () => {+ const doc = schema.node("doc", null, [heading("Deleted"), heading("Survivor")]);+ const tr = new Transform(doc).replaceWith(0, doc.child(0).nodeSize, heading("Replacement"));+ expect([...mapCollapsedOutlinePositions(new Set([0]), tr.mapping, outline(tr.doc))]).toEqual([]);+ });++ test("keeps identity while clearing a title and retyping it in separate transactions", () => {+ const doc = schema.node("doc", null, [heading("Before"), heading("Child", 2)]);+ const cleared = new Transform(doc).delete(1, 7);+ const collapsed = mapCollapsedOutlinePositions(new Set([0]), cleared.mapping, outline(cleared.doc));+ const retyped = new Transform(cleared.doc).insert(1, schema.text("After"));+ expect([...mapCollapsedOutlinePositions(collapsed, retyped.mapping, outline(retyped.doc))]).toEqual([0]);+ });++ test("keeps folding when changing heading level", () => {+ const doc = schema.node("doc", null, [heading("Title"), heading("Child", 3)]);+ const tr = new Transform(doc).setNodeMarkup(0, undefined, { level: 2 });+ expect([...mapCollapsedOutlinePositions(new Set([0]), tr.mapping, outline(tr.doc))]).toEqual([0]);+ });++ test("retains state when replacing all text inside a heading", () => {+ const doc = schema.node("doc", null, [heading("Before"), heading("Child", 2)]);+ const tr = new Transform(doc).replaceWith(1, 7, schema.text("After"));+ expect([...mapCollapsedOutlinePositions(new Set([0]), tr.mapping, outline(tr.doc))]).toEqual([0]);+ });+});++describe("outline restoration", () => {+ test("restores saved renamed titles after reopening with changed body positions", () => {+ const items = [{ pos: 0, level: 1, text: "Renamed" }, { pos: 10, level: 2, text: "Child" }];+ expect([...restoreOutlinePositions({ items, collapsed: [0] }, items.map((item) => ({ ...item, pos: item.pos + 20 })))]).toEqual([20]);+ });++ test("restores unique headings after external changes, leaving new and ambiguous headings open", () => {+ const old = outline(schema.node("doc", null, [heading("Same"), heading("Same"), heading("Unique")]));+ const next = outline(schema.node("doc", null, [heading("New"), heading("Same"), heading("Same"), heading("Unique")]));+ expect([...restoreOutlinePositions({ items: old, collapsed: old.map((item) => item.pos) }, next)]).toEqual([next[3].pos]);+ });++ test("keeps each note independent and tolerates malformed or unavailable storage", () => {+ const previousWindow = globalThis.window;+ const storage = new Map();+ globalThis.window = { localStorage: { getItem: (key) => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value) } };+ try {+ const snapshot = { items: [{ pos: 0, level: 1, text: "Title" }], collapsed: [0] };+ writeOutlineSnapshot("note-a", snapshot);+ writeOutlineSnapshot("note-b", { ...snapshot, collapsed: [] });+ expect(readOutlineSnapshot("note-a")).toEqual(snapshot);+ expect(readOutlineSnapshot("note-b").collapsed).toEqual([]);+ storage.set("edgeever.editor.outline.v1.bad", '{"items":[null],"collapsed":[]}');+ expect(readOutlineSnapshot("bad")).toBeNull();+ window.localStorage.setItem = () => { throw new Error("quota"); };+ writeOutlineSnapshot("unavailable", snapshot);+ expect(readOutlineSnapshot("unavailable")).toEqual(snapshot);+ } finally {+ if (previousWindow === undefined) delete globalThis.window;+ else globalThis.window = previousWindow;+ }+ });+});diff --git a/apps/web/src/lib/editor-outline-state.ts b/apps/web/src/lib/editor-outline-state.tsnew file mode 100644index 00000000..7aa42e8e--- /dev/null+++ b/apps/web/src/lib/editor-outline-state.ts@@ -0,0 +1,70 @@+import type { Mapping } from "@tiptap/pm/transform";+import type { OutlineItem } from "./editor-outline";++export type OutlineSnapshot = { items: OutlineItem[]; collapsed: number[] };+const storageKey = (memoId: string) => `edgeever.editor.outline.v1.${encodeURIComponent(memoId)}`;+const unsaved = new Map<string, OutlineSnapshot>();++export const readOutlineSnapshot = (memoId: string): OutlineSnapshot | null => {+ if (unsaved.has(memoId)) return unsaved.get(memoId)!;+ try {+ const value = JSON.parse(window.localStorage.getItem(storageKey(memoId)) ?? "null");+ if (!value || !Array.isArray(value.items) || !Array.isArray(value.collapsed)) return null;+ if (!value.items.every((item: OutlineItem) => item && Number.isInteger(item.pos) && item.pos >= 0+ && Number.isInteger(item.level) && item.level >= 1 && item.level <= 6 && typeof item.text === "string")+ || !value.collapsed.every((pos: number) => Number.isInteger(pos) && pos >= 0)) return null;+ return value;+ } catch {+ return null;+ }+};++export const writeOutlineSnapshot = (memoId: string, snapshot: OutlineSnapshot) => {+ try {+ window.localStorage.setItem(storageKey(memoId), JSON.stringify(snapshot));+ unsaved.delete(memoId);+ } catch {+ // Keep navigation choices usable when storage is unavailable or full.+ unsaved.set(memoId, snapshot);+ if (unsaved.size > 50) unsaved.delete(unsaved.keys().next().value!);+ }+};++// Transactions preserve identity through renames, duplicate titles and position+// shifts without adding attributes to the user's document. Deleted headings+// must never transfer their state to a replacement at the same position.+export const mapCollapsedOutlinePositions = (+ collapsed: ReadonlySet<number>, mapping: Mapping, items: OutlineItem[],+): Set<number> => {+ const available = new Set(items.map((item) => item.pos));+ const result = new Set<number>();+ for (const pos of collapsed) {+ const mapped = mapping.mapResult(pos, 1);+ // Heading-level changes replace the opening token but preserve its+ // content. A full node deletion/replacement removes both anchors.+ const survives = !mapped.deleted || !mapping.mapResult(pos + 1, 1).deleted;+ if (survives && available.has(mapped.pos)) result.add(mapped.pos);+ }+ return result;+};++export const restoreOutlinePositions = (snapshot: OutlineSnapshot | null, items: OutlineItem[]): Set<number> => {+ if (!snapshot) return new Set();+ const collapsed = new Set(snapshot.collapsed);+ const identity = (item: OutlineItem) => JSON.stringify([item.level, item.text]);+ // The same heading sequence also handles edits to intervening body text.+ if (snapshot.items.length === items.length && snapshot.items.every((item, i) => identity(item) === identity(items[i]!))) {+ return new Set(items.filter((_, i) => collapsed.has(snapshot.items[i]!.pos)).map((item) => item.pos));+ }+ const oldCounts = new Map<string, number>();+ const newCounts = new Map<string, number>();+ for (const item of snapshot.items) oldCounts.set(identity(item), (oldCounts.get(identity(item)) ?? 0) + 1);+ for (const item of items) newCounts.set(identity(item), (newCounts.get(identity(item)) ?? 0) + 1);+ const collapsedIdentities = new Set(snapshot.items.filter((item) => collapsed.has(item.pos)).map(identity));+ // After external edits, only restore unambiguous matches. Newly added or+ // renamed headings default to expanded rather than guessing by position.+ return new Set(items.filter((item) => {+ const key = identity(item);+ return oldCounts.get(key) === 1 && newCounts.get(key) === 1 && collapsedIdentities.has(key);+ }).map((item) => item.pos));+};diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 595b3f50..4b7c7aff 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2796,6 +2796,8 @@ export const enUS = {outline: "Outline",showOutline: "Show outline",hideOutline: "Hide outline",+ collapseAllOutline: "Collapse all headings",+ expandAllOutline: "Expand all headings",collapseOutlineHeading: "Collapse {{name}}",expandOutlineHeading: "Expand {{name}}",},diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 08d22b8b..f709b12f 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2785,6 +2785,8 @@ export const ja = {outline: "アウトライン",showOutline: "アウトラインを表示",hideOutline: "アウトラインを隠す",+ collapseAllOutline: "すべての見出しを折りたたむ",+ expandAllOutline: "すべての見出しを展開",collapseOutlineHeading: "{{name}} を閉じる",expandOutlineHeading: "{{name}} を開く",},diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 057e76c1..51b2cbe5 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2785,6 +2785,8 @@ export const pl = {outline: "Konspekt",showOutline: "Pokaż konspekt",hideOutline: "Ukryj konspekt",+ collapseAllOutline: "Zwiń wszystkie nagłówki",+ expandAllOutline: "Rozwiń wszystkie nagłówki",collapseOutlineHeading: "Zwiń {{name}}",expandOutlineHeading: "Rozwiń {{name}}",},diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex 0fc5f853..2f35b7f3 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -2796,6 +2796,8 @@ export const ru = {outline: "Оглавление",showOutline: "Показать оглавление",hideOutline: "Скрыть оглавление",+ collapseAllOutline: "Свернуть все заголовки",+ expandAllOutline: "Развернуть все заголовки",collapseOutlineHeading: "Свернуть {{name}}",expandOutlineHeading: "Развернуть {{name}}",},diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 10b952a2..cd79c4f8 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2794,6 +2794,8 @@ export const zhCN = {outline: "文档大纲",showOutline: "显示文档大纲",hideOutline: "隐藏文档大纲",+ collapseAllOutline: "折叠全部标题",+ expandAllOutline: "展开全部标题",collapseOutlineHeading: "收起 {{name}}",expandOutlineHeading: "展开 {{name}}",},