UNPKG

mind-elixir

Version:

Mind elixir is a free open source mind map core.

279 lines (278 loc) • 12.6 kB
import './outliner.css'; import type { NodeObj } from '../types/index'; import type { OutlinerOptions } from './types'; /** * A mind-elixir outliner — ONE document, TWO views. * * The outline renders `mei.nodeData` in place (same reference, no clone), routes * every mutation to the map through the map's own node operations, and re-reads * the tree whenever the map's undo/redo journal moves. It therefore owns **no * data and no history of its own**: an edit made in the outline is a map edit, a * `Ctrl+Z` from either view walks one timeline, and a change made on the map — * including one made programmatically — shows up here. * * ```ts * const mei = new MindElixir({ el: '#map', allowUndo: true }) * await mei.init(data) * const outliner = new Outliner({ el: '#outline', mei }) * ``` * * Sync runs on BOTH of the map's channels: the shared journal (structural edits, * undo/redo — collapse/expand lands there too) and the map's `operation` event, * which covers silent internal operations that record no entry of their own. Both * merge into one render per tick. * * A node that the map does not render — i.e. inside a collapsed branch — has no * element to operate on, so outline gestures on it are no-ops; unfolding the * branch in the map makes it work again. That is mind-elixir's own API shape: * every node operation takes a `Topic` element, not a `NodeObj`. */ export declare class Outliner { private el; private breadcrumbEl; private itemsEl; /** The map's live root (`mei.nodeData`), never a copy — assigned by {@link bindRoot}. */ private root; /** The map's journal (`mei.historyStack`). The outline subscribes to it and pushes nothing. */ private readonly history; private readonly mei; /** While true, a sync skips its render (patch-only topic commits). */ private suppressSync; /** A deferred sync is owed — see `scheduleSync`. */ private syncDirty; /** A deferred sync flush is already queued for the end of this tick. */ private syncQueued; private readonly; private markdown?; private i18n; private fileName?; private onChange?; private zoomedId; private editingId; /** * True until the end of the task in which compositionend fired. Safari fires * compositionend BEFORE the Enter/Esc that confirms the candidate, so those * keydowns arrive with `isComposing === false` — without this flag they would * run the structural keymap. Cleared by a 0 ms timer, so any keydown in a * LATER task is an ordinary command. */ private compositionJustEnded; private openMenuId; private draggedId; /** Set at dragstart so `dragover` needs neither a DOM scan nor a live lookup. */ private draggedContainer; private dropIndicator; /** id → reused DOM for every CURRENTLY RENDERED node (collapsed subtrees drop out). */ private views; /** Ids visited by the render in progress — anything left over gets unmounted. */ private seen; /** Change key for the breadcrumb, which is cheap to skip and expensive to rebuild. */ private breadcrumbSig; private disposers; constructor(options: OutlinerOptions); /** * A detached snapshot of what the outline currently shows: a bare `NodeObj` * tree, with the map's `parent` back-references stripped — `mei.stringifyData` * is mind-elixir's own serializer, so this is byte-for-byte * `mei.getData().nodeData` while the outline is not zoomed. Note the * difference from `mei.getData()` itself, which returns the whole document * (`nodeData`, `arrows`, `summaries`, `direction`, `theme`, `compact`). * * In focus mode the outline renders the focused subtree while `getData()` * reports the whole diagram, so this follows the OUTLINE's root. */ getData(): NodeObj; /** Insert an empty child under `id` in the map and focus it in the outline. */ addChild(id: string): void; destroy(): void; focusItem(id: string): void; /** * Point `this.root` at the live `mei.nodeData` and normalise it in place — no * clone, the map owns the data. * * Between `refresh` calls (undo/redo) this is the same reference, so the * assignment is a no-op and only the `ensureChildren` pass runs; a swapped * tree — a new document, or the subtree focus mode installs — re-points it. */ private bindRoot; /** * Look a node up with the map's own depth-first search. The outline keeps * neither a copy of the tree nor an index over it. */ private byId; private isRoot; private parentOf; /** * The previous sibling, straight off the map's `parent` back-references (kept * current by mind-elixir's `fillParent`) instead of a second tree walk. */ private prevSiblingOf; /** * Root-to-node path for the breadcrumb, walked upwards through `parent`. * * It stops at the rendered document root: in focus mode `mei.nodeData` is a * subtree whose `parent` still points into the map's backup tree, and the * breadcrumb must not show segments above what is on screen. */ private pathTo; /** * The node's element in the map. Null when the map does not render it — a node * inside a collapsed branch has no DOM, and every mind-elixir operation takes an * element, so such a node simply cannot be acted on from the outline. */ private meiEle; /** * Ask for a sync and RENDER NOW. Callers such as `applyOperation` focus a node * right after the map call, which needs the fresh DOM, so this channel stays * synchronous. * * Renders even if one already ran in this tick, because the notification that * brought us here may describe a NEWER tree than that render saw — see * `scheduleSync` for why the two channels must not share a coalescing window. */ private requestSync; /** * Deferred variant, wired to silent map operations on the bus. * * That channel reports mutations the journal does not announce: a tracked fold * pushes an entry (which renders synchronously through `requestSync`), while a * SILENT expand — `addChild` / move-into auto-expanding a collapsed target — * fires `operation` with `silent: true` and no history entry of its own, the * caller's operation acting as the announcement instead. * * So park the request for the end of the tick rather than rendering: if a * synchronous render follows in the same block it already covers this mutation * and clears the flag; if nothing follows, the microtask renders anyway — still * before the browser paints. Renders are never dropped, only coalesced. */ private scheduleSync; /** * Re-render the outline from the live map tree. Called on every journal * change, so it re-reads `this.root` (undo/redo may have swapped the tree) and * drops view state that may point at now-missing nodes. */ private rerenderFromMei; private emitChange; /** * Flush unsaved typing (from the outline editor) into the map via * `reshapeNode` so a following structural move cannot lose it. Skipped when * the text is unchanged (reshapeNode would push a no-op journal entry). */ private flushEditingText; private setNodeTopicBound; private expandBound; /** * Route ONE outline gesture to the map. * * Every case is a call into mind-elixir's own node operations: the outline * never touches the tree, and the operation the map fires is what records the * journal entry that brings us back here through `requestSync`. */ private applyOperation; /** Remove a node and its subtree from the map (never the document root). */ private deleteItem; /** * Bring the DOM in line with the data — WITHOUT tearing it down. * * The old implementation ran `itemsEl.innerHTML = ''` and rebuilt every node * from scratch, at a cost of ~17 elements and ~8 listeners per node on every * call (measured: 6 ms at 341 nodes, 21 ms at 1 365, 94 ms at 5 461). Because * nearly every public method funnelled through here — including opening the * `…` menu — a single-character change re-rendered the whole document. * * Now every node owns a persistent {@link ItemView}: a node whose data did not * change keeps its exact element, its listeners, its focus and its hover * state. Only nodes that actually differ are patched, and only containers that * actually moved are reparented. */ private render; /** * The breadcrumb holds only a handful of nodes, but rebuilding it means a DOM * teardown plus a fresh listener per segment. Skip it unless the labels moved. */ private renderBreadcrumb; /** * Reconcile one node and its subtree into `parentEl`, placing its container * directly after `cursor` — the previously placed sibling — so keeping * document order costs at most one `insertBefore` per node that moved. * * Returns this node's container, i.e. the cursor for the next sibling. */ private syncItem; /** Release the views this render did not visit: deleted nodes, folded subtrees. */ private unmountUnseen; /** * Build a node's DOM once. Deliberately listener-free: every interaction is * handled by the delegated handlers on `this.el` (see the events region), which * is what takes the per-node listener count from 8 to 0. */ private createItemView; /** Update only what actually changed. This is the hot path now. */ private patchItemView; /** * The `…` dropdown is derived state: it exists iff `openMenuId` names this * node. `setOpenMenu` drives it directly and a render re-syncs it — so opening * a menu no longer costs a whole-document rebuild. */ private syncDropdown; /** * Entries carry a `data-action` rather than a closure: a closure captured at * build time would go stale the moment the node is indented or moved, and on * a reused element it never gets rebuilt. */ private createDropdown; private toggleMenu; /** * Open the menu for `id`, or close it with `null`. Touches ONLY the two nodes * involved — no render, no breadcrumb, no per-node work. */ private setOpenMenu; private runMenuAction; private handleDragStart; private handleDragEnd; private handleDragOver; private handleDragLeave; private handleDrop; private clearDropIndicator; private writeTopicHtml; private escapeText; private getTopicEl; private liveEditingText; private handleFocusIn; /** Move the caret to the end of `el`'s contents. */ private placeCaretAtEnd; /** Remember that `view.topic` already shows `topic`'s rendered markup. */ private markTopicClean; private handleFocusOut; /** * The Enter/Esc that dismissed the candidate window is still in flight when * this fires — Chrome reports it with `isComposing: true`, Safari (which * ends the composition first) with `false`. Swallowing those two keys until * the end of this task covers both orderings without delaying anything. */ private handleCompositionEnd; private handleTopicKeydown; /** * Single click router for the whole list. Every node interaction used to be its * own listener — 5 per node, recreated on every render — which both cost time * and made "read the current value" depend on a closure that the incremental * renderer deliberately keeps alive. */ private handleClick; private handleDocumentMousedown; /** * Global Ctrl+Z / Ctrl+Y / Ctrl+Shift+Z — one journal for both views. * * The map binds the same shortcut on `mei.container` (see * `plugin/operationHistory`), so a keypress whose focus sits there is already * handled: matching it here as well would undo twice per keystroke. Everything * else — the focus in an outline topic, on an outline button, or nowhere in * particular — ends at `mei.undo` / `mei.redo`, i.e. the SAME journal. The * outline never keeps a stack of its own to step through. * * While a topic is being edited the browser's native contenteditable undo runs * first; only when it is exhausted do we step the journal. */ private handleGlobalKeydown; private zoomTo; }