@aionbuilders/nabu 0.1.0-alpha.9 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +523 -0
- package/LICENSE +21 -0
- package/README.md +82 -144
- package/dist/behaviors/text/RichText.svelte +25 -2
- package/dist/behaviors/text/index.d.ts +2 -0
- package/dist/behaviors/text/index.js +2 -0
- package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +5 -0
- package/dist/behaviors/text/markdown-shortcuts.extension.js +79 -0
- package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
- package/dist/behaviors/text/markdown-syntax.js +81 -0
- package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
- package/dist/behaviors/text/rich-text.extension.js +135 -53
- package/dist/behaviors/text/text.behavior.svelte.d.ts +217 -42
- package/dist/behaviors/text/text.behavior.svelte.js +657 -55
- package/dist/behaviors/text/typography.extension.d.ts +7 -0
- package/dist/behaviors/text/typography.extension.js +25 -0
- package/dist/blocks/Block.svelte +5 -2
- package/dist/blocks/BlockList.svelte +48 -0
- package/dist/blocks/BlockList.svelte.d.ts +17 -0
- package/dist/blocks/Nabu.svelte +180 -14
- package/dist/blocks/Nabu.svelte.d.ts +13 -0
- package/dist/blocks/block.extension.d.ts +3 -0
- package/dist/blocks/block.extension.js +8 -9
- package/dist/blocks/block.svelte.d.ts +356 -68
- package/dist/blocks/block.svelte.js +388 -42
- package/dist/blocks/blockquote/Blockquote.svelte +39 -0
- package/dist/blocks/blockquote/Blockquote.svelte.d.ts +11 -0
- package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -0
- package/dist/blocks/blockquote/blockquote.extension.js +80 -0
- package/dist/blocks/blockquote/blockquote.svelte.d.ts +63 -0
- package/dist/blocks/blockquote/blockquote.svelte.js +136 -0
- package/dist/blocks/blockquote/index.d.ts +3 -0
- package/dist/blocks/blockquote/index.js +3 -0
- package/dist/blocks/callout/Callout.svelte +67 -0
- package/dist/blocks/callout/Callout.svelte.d.ts +11 -0
- package/dist/blocks/callout/callout.extension.d.ts +4 -0
- package/dist/blocks/callout/callout.extension.js +84 -0
- package/dist/blocks/callout/callout.svelte.d.ts +80 -0
- package/dist/blocks/callout/callout.svelte.js +189 -0
- package/dist/blocks/callout/index.d.ts +3 -0
- package/dist/blocks/callout/index.js +3 -0
- package/dist/blocks/chunks.d.ts +49 -0
- package/dist/blocks/chunks.js +90 -0
- package/dist/blocks/code/Code.svelte +84 -0
- package/dist/blocks/code/Code.svelte.d.ts +11 -0
- package/dist/blocks/code/code.extension.d.ts +4 -0
- package/dist/blocks/code/code.extension.js +88 -0
- package/dist/blocks/code/code.svelte.d.ts +68 -0
- package/dist/blocks/code/code.svelte.js +245 -0
- package/dist/blocks/code/index.d.ts +3 -0
- package/dist/blocks/code/index.js +3 -0
- package/dist/blocks/container.utils.d.ts +85 -13
- package/dist/blocks/container.utils.js +338 -178
- package/dist/blocks/dialogue/Dialogue.svelte +8 -2
- package/dist/blocks/dialogue/dialogue.svelte.d.ts +36 -23
- package/dist/blocks/dialogue/dialogue.svelte.js +51 -45
- package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
- package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
- package/dist/blocks/dialogue/index.d.ts +12 -1
- package/dist/blocks/dialogue/index.js +51 -35
- package/dist/blocks/divider/Divider.svelte +28 -0
- package/dist/blocks/divider/Divider.svelte.d.ts +11 -0
- package/dist/blocks/divider/divider.extension.d.ts +23 -0
- package/dist/blocks/divider/divider.extension.js +153 -0
- package/dist/blocks/divider/divider.svelte.d.ts +54 -0
- package/dist/blocks/divider/divider.svelte.js +89 -0
- package/dist/blocks/divider/index.d.ts +3 -0
- package/dist/blocks/divider/index.js +3 -0
- package/dist/blocks/file/File.svelte +56 -0
- package/dist/blocks/file/File.svelte.d.ts +11 -0
- package/dist/blocks/file/file.extension.d.ts +4 -0
- package/dist/blocks/file/file.extension.js +27 -0
- package/dist/blocks/file/file.svelte.d.ts +29 -0
- package/dist/blocks/file/file.svelte.js +77 -0
- package/dist/blocks/file/index.d.ts +3 -0
- package/dist/blocks/file/index.js +3 -0
- package/dist/blocks/heading/Heading.svelte +2 -1
- package/dist/blocks/heading/heading.svelte.d.ts +27 -34
- package/dist/blocks/heading/heading.svelte.js +72 -60
- package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
- package/dist/blocks/heading/index.d.ts +2 -2
- package/dist/blocks/heading/index.js +33 -8
- package/dist/blocks/image/Image.svelte +41 -0
- package/dist/blocks/image/Image.svelte.d.ts +11 -0
- package/dist/blocks/image/image.extension.d.ts +5 -0
- package/dist/blocks/image/image.extension.js +34 -0
- package/dist/blocks/image/image.svelte.d.ts +61 -0
- package/dist/blocks/image/image.svelte.js +114 -0
- package/dist/blocks/image/index.d.ts +3 -0
- package/dist/blocks/image/index.js +3 -0
- package/dist/blocks/index.d.ts +11 -1
- package/dist/blocks/index.js +11 -1
- package/dist/blocks/list/List.svelte +9 -2
- package/dist/blocks/list/ListItem.svelte +44 -7
- package/dist/blocks/list/convert.d.ts +20 -0
- package/dist/blocks/list/convert.js +92 -0
- package/dist/blocks/list/hooks/onBeforeInput.hook.js +60 -26
- package/dist/blocks/list/html-flat.d.ts +78 -0
- package/dist/blocks/list/html-flat.js +244 -0
- package/dist/blocks/list/indent.d.ts +86 -0
- package/dist/blocks/list/indent.js +205 -0
- package/dist/blocks/list/index.d.ts +7 -3
- package/dist/blocks/list/index.js +43 -31
- package/dist/blocks/list/list-item.svelte.d.ts +43 -17
- package/dist/blocks/list/list-item.svelte.js +143 -93
- package/dist/blocks/list/list.behavior.svelte.d.ts +7 -4
- package/dist/blocks/list/list.behavior.svelte.js +10 -5
- package/dist/blocks/list/list.svelte.d.ts +101 -23
- package/dist/blocks/list/list.svelte.js +136 -114
- package/dist/blocks/list/markdown.d.ts +149 -0
- package/dist/blocks/list/markdown.js +442 -0
- package/dist/blocks/list/normalize.d.ts +11 -0
- package/dist/blocks/list/normalize.js +396 -0
- package/dist/blocks/list/paste.d.ts +45 -0
- package/dist/blocks/list/paste.js +242 -0
- package/dist/blocks/list/step-back.d.ts +24 -0
- package/dist/blocks/list/step-back.js +87 -0
- package/dist/blocks/list/to-list.d.ts +7 -0
- package/dist/blocks/list/to-list.js +44 -0
- package/dist/blocks/list/todos-toggle.d.ts +20 -0
- package/dist/blocks/list/todos-toggle.js +48 -0
- package/dist/blocks/list/todos.svelte.d.ts +35 -0
- package/dist/blocks/list/todos.svelte.js +76 -0
- package/dist/blocks/media/index.d.ts +2 -0
- package/dist/blocks/media/index.js +2 -0
- package/dist/blocks/media/markdown.d.ts +12 -0
- package/dist/blocks/media/markdown.js +26 -0
- package/dist/blocks/media/media-block.svelte.d.ts +107 -0
- package/dist/blocks/media/media-block.svelte.js +181 -0
- package/dist/blocks/media/media.helpers.d.ts +24 -0
- package/dist/blocks/media/media.helpers.js +88 -0
- package/dist/blocks/megablock.svelte.d.ts +50 -19
- package/dist/blocks/megablock.svelte.js +115 -74
- package/dist/blocks/move.d.ts +23 -0
- package/dist/blocks/move.js +92 -0
- package/dist/blocks/nabu.svelte.d.ts +846 -75
- package/dist/blocks/nabu.svelte.js +1990 -182
- package/dist/blocks/paragraph/Paragraph.svelte +1 -0
- package/dist/blocks/paragraph/index.d.ts +2 -2
- package/dist/blocks/paragraph/index.js +35 -16
- package/dist/blocks/paragraph/paragraph.svelte.d.ts +49 -35
- package/dist/blocks/paragraph/paragraph.svelte.js +81 -69
- package/dist/blocks/paragraph/table.html.d.ts +9 -0
- package/dist/blocks/paragraph/table.html.js +111 -0
- package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
- package/dist/blocks/paragraph/table.markdown.js +90 -0
- package/dist/blocks/region/Region.svelte +264 -0
- package/dist/blocks/region/Region.svelte.d.ts +11 -0
- package/dist/blocks/region/actions.d.ts +135 -0
- package/dist/blocks/region/actions.js +402 -0
- package/dist/blocks/region/close.d.ts +35 -0
- package/dist/blocks/region/close.js +130 -0
- package/dist/blocks/region/commands.d.ts +6 -0
- package/dist/blocks/region/commands.js +277 -0
- package/dist/blocks/region/create.d.ts +72 -0
- package/dist/blocks/region/create.js +208 -0
- package/dist/blocks/region/end-marker.d.ts +35 -0
- package/dist/blocks/region/end-marker.js +51 -0
- package/dist/blocks/region/facts.d.ts +69 -0
- package/dist/blocks/region/facts.js +152 -0
- package/dist/blocks/region/format.d.ts +91 -0
- package/dist/blocks/region/format.js +260 -0
- package/dist/blocks/region/index.d.ts +14 -0
- package/dist/blocks/region/index.js +14 -0
- package/dist/blocks/region/insert.d.ts +59 -0
- package/dist/blocks/region/insert.js +102 -0
- package/dist/blocks/region/messages.d.ts +254 -0
- package/dist/blocks/region/messages.js +131 -0
- package/dist/blocks/region/normalize.d.ts +7 -0
- package/dist/blocks/region/normalize.js +170 -0
- package/dist/blocks/region/region.extension.d.ts +58 -0
- package/dist/blocks/region/region.extension.js +119 -0
- package/dist/blocks/region/region.svelte.d.ts +221 -0
- package/dist/blocks/region/region.svelte.js +582 -0
- package/dist/blocks/region/regions.svelte.d.ts +141 -0
- package/dist/blocks/region/regions.svelte.js +276 -0
- package/dist/blocks/region/serialize.d.ts +57 -0
- package/dist/blocks/region/serialize.js +112 -0
- package/dist/blocks/region/types.d.ts +255 -0
- package/dist/blocks/region/types.js +204 -0
- package/dist/blocks/selection.svelte.d.ts +106 -8
- package/dist/blocks/selection.svelte.js +632 -74
- package/dist/blocks/subthread.d.ts +80 -0
- package/dist/blocks/subthread.js +167 -0
- package/dist/blocks/text-block.svelte.d.ts +70 -0
- package/dist/blocks/text-block.svelte.js +108 -0
- package/dist/blocks/toggle/Toggle.svelte +73 -0
- package/dist/blocks/toggle/Toggle.svelte.d.ts +11 -0
- package/dist/blocks/toggle/index.d.ts +3 -0
- package/dist/blocks/toggle/index.js +3 -0
- package/dist/blocks/toggle/markdown.d.ts +20 -0
- package/dist/blocks/toggle/markdown.js +112 -0
- package/dist/blocks/toggle/toggle.extension.d.ts +4 -0
- package/dist/blocks/toggle/toggle.extension.js +18 -0
- package/dist/blocks/toggle/toggle.svelte.d.ts +135 -0
- package/dist/blocks/toggle/toggle.svelte.js +352 -0
- package/dist/blocks/undo-selection.d.ts +175 -0
- package/dist/blocks/undo-selection.js +360 -0
- package/dist/blocks/video/Video.svelte +42 -0
- package/dist/blocks/video/Video.svelte.d.ts +11 -0
- package/dist/blocks/video/index.d.ts +3 -0
- package/dist/blocks/video/index.js +3 -0
- package/dist/blocks/video/video.extension.d.ts +4 -0
- package/dist/blocks/video/video.extension.js +27 -0
- package/dist/blocks/video/video.svelte.d.ts +29 -0
- package/dist/blocks/video/video.svelte.js +80 -0
- package/dist/extend.d.ts +55 -0
- package/dist/extend.js +88 -0
- package/dist/files/assets.clipboard.d.ts +77 -0
- package/dist/files/assets.clipboard.js +152 -0
- package/dist/files/files.svelte.d.ts +363 -0
- package/dist/files/files.svelte.js +897 -0
- package/dist/files/index.d.ts +3 -0
- package/dist/files/index.js +3 -0
- package/dist/files/outbox.d.ts +69 -0
- package/dist/files/outbox.js +48 -0
- package/dist/files/status.d.ts +65 -0
- package/dist/files/status.js +87 -0
- package/dist/files/store.d.ts +97 -0
- package/dist/files/store.js +65 -0
- package/dist/files/uploads.svelte.d.ts +174 -0
- package/dist/files/uploads.svelte.js +504 -0
- package/dist/index.d.ts +68 -6
- package/dist/index.js +117 -7
- package/dist/nabu-theme.css +112 -0
- package/dist/paste/html.paste.d.ts +74 -3
- package/dist/paste/html.paste.js +555 -83
- package/dist/paste/markdown-inline.d.ts +86 -0
- package/dist/paste/markdown-inline.js +528 -0
- package/dist/paste/markdown.paste.d.ts +2 -8
- package/dist/paste/markdown.paste.js +78 -94
- package/dist/paste/nabu.paste.d.ts +3 -0
- package/dist/paste/nabu.paste.js +29 -3
- package/dist/paste/plain-text.paste.d.ts +2 -2
- package/dist/paste/plain-text.paste.js +3 -3
- package/dist/persistence/asset-store.d.ts +51 -0
- package/dist/persistence/asset-store.js +103 -0
- package/dist/persistence/autosave.d.ts +53 -0
- package/dist/persistence/autosave.js +62 -0
- package/dist/persistence/compact.d.ts +162 -0
- package/dist/persistence/compact.js +141 -0
- package/dist/persistence/history.d.ts +77 -0
- package/dist/persistence/history.js +176 -0
- package/dist/persistence/indexeddb.d.ts +190 -4
- package/dist/persistence/indexeddb.js +333 -29
- package/dist/persistence/merge.d.ts +38 -0
- package/dist/persistence/merge.js +36 -0
- package/dist/persistence/outbox.d.ts +25 -0
- package/dist/persistence/outbox.js +40 -0
- package/dist/persistence/persistence.d.ts +70 -9
- package/dist/persistence/persistence.js +507 -35
- package/dist/persistence/recovery.d.ts +79 -0
- package/dist/persistence/recovery.js +79 -0
- package/dist/persistence/release.d.ts +34 -0
- package/dist/persistence/release.js +64 -0
- package/dist/persistence/state.svelte.d.ts +53 -0
- package/dist/persistence/state.svelte.js +48 -0
- package/dist/persistence/sync.d.ts +39 -0
- package/dist/persistence/sync.js +138 -0
- package/dist/persistence/tail.d.ts +42 -0
- package/dist/persistence/tail.js +103 -0
- package/dist/presets.d.ts +29 -24
- package/dist/presets.js +51 -14
- package/dist/themes/atelier.css +318 -0
- package/dist/ui/CommandChooser.svelte +153 -0
- package/dist/ui/CommandChooser.svelte.d.ts +13 -0
- package/dist/ui/CommandInvite.svelte +99 -0
- package/dist/ui/CommandInvite.svelte.d.ts +12 -0
- package/dist/ui/DragHandle.svelte +217 -0
- package/dist/ui/DragHandle.svelte.d.ts +11 -0
- package/dist/ui/FloatingToolbar.svelte +165 -0
- package/dist/ui/FloatingToolbar.svelte.d.ts +27 -0
- package/dist/ui/SlashMenu.svelte +215 -0
- package/dist/ui/SlashMenu.svelte.d.ts +33 -0
- package/dist/ui/anchor.d.ts +112 -0
- package/dist/ui/anchor.js +136 -0
- package/dist/ui/index.d.ts +10 -0
- package/dist/ui/index.js +15 -0
- package/dist/ui/slash-menu.svelte.d.ts +112 -0
- package/dist/ui/slash-menu.svelte.js +150 -0
- package/dist/utils/command-confirm.svelte.d.ts +349 -0
- package/dist/utils/command-confirm.svelte.js +673 -0
- package/dist/utils/commands.d.ts +328 -0
- package/dist/utils/commands.js +416 -0
- package/dist/utils/dom-scope.d.ts +14 -0
- package/dist/utils/dom-scope.js +20 -0
- package/dist/utils/drop.d.ts +160 -0
- package/dist/utils/drop.js +305 -0
- package/dist/utils/extensions.d.ts +488 -40
- package/dist/utils/extensions.js +300 -19
- package/dist/utils/html.d.ts +44 -0
- package/dist/utils/html.js +183 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/index.js +4 -0
- package/dist/utils/keys.d.ts +120 -0
- package/dist/utils/keys.js +248 -0
- package/dist/utils/links.d.ts +22 -0
- package/dist/utils/links.js +34 -0
- package/dist/utils/placeholders.d.ts +88 -0
- package/dist/utils/placeholders.js +91 -0
- package/dist/utils/selection.svelte.d.ts +47 -19
- package/dist/utils/selection.svelte.js +60 -10
- package/dist/utils/spellcheck.d.ts +9 -0
- package/dist/utils/spellcheck.js +17 -0
- package/dist/utils/tab.d.ts +31 -0
- package/dist/utils/tab.js +117 -0
- package/dist/utils/words.d.ts +7 -0
- package/dist/utils/words.js +62 -0
- package/dist/vite.d.ts +22 -0
- package/dist/vite.js +34 -0
- package/package.json +61 -22
- package/dist/blocks/zone/Zone.svelte +0 -258
- package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
- package/dist/blocks/zone/index.d.ts +0 -2
- package/dist/blocks/zone/index.js +0 -2
- package/dist/blocks/zone/zone.extension.d.ts +0 -2
- package/dist/blocks/zone/zone.extension.js +0 -221
- package/dist/blocks/zone/zone.svelte.d.ts +0 -112
- package/dist/blocks/zone/zone.svelte.js +0 -321
|
@@ -1,34 +1,239 @@
|
|
|
1
1
|
import { LoroDoc, UndoManager } from 'loro-crdt';
|
|
2
2
|
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
|
3
3
|
import { Block } from './block.svelte.js';
|
|
4
|
+
import { MegaBlock } from './megablock.svelte.js';
|
|
4
5
|
import { NabuSelection } from './selection.svelte.js';
|
|
5
|
-
import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, findDirectChildOf, findLCA } from './container.utils.js';
|
|
6
|
-
import {
|
|
6
|
+
import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, deleteRange, selectionRange, findDirectChildOf, findLCA, textBlocksInOrder } from './container.utils.js';
|
|
7
|
+
import { jsonToPasteBlocks, degradeUnknownBlocks, CLIPBOARD_FORMAT_VERSION, JSON_FORMAT_VERSION, isSupportedJsonVersion } from '../utils/extensions.js';
|
|
8
|
+
import { escapeHtml, sanitizePasteBlocks } from '../utils/html.js';
|
|
9
|
+
import { tick, flushSync } from 'svelte';
|
|
10
|
+
import { Files } from '../files/files.svelte.js';
|
|
7
11
|
import { Pulse } from '@aionbuilders/pulse';
|
|
12
|
+
import { CommandRegistry } from '../utils/commands.js';
|
|
13
|
+
import { CommandConfirmation } from '../utils/command-confirm.svelte.js';
|
|
14
|
+
import { normalizePlaceholders } from '../utils/placeholders.js';
|
|
15
|
+
import { normalizeLang } from '../utils/spellcheck.js';
|
|
16
|
+
import { resolveTabMode, handleTabKey, isModifierKey, DEFAULT_TAB_HINT } from '../utils/tab.js';
|
|
17
|
+
import { moveBlocks } from './move.js';
|
|
18
|
+
import { closestWithin } from '../utils/dom-scope.js';
|
|
19
|
+
import { captureSelection, explicitSelection, legacySelection, restoreSelection, keepSelection, makeEndpoint, resolveOffset, revealFocus } from './undo-selection.js';
|
|
20
|
+
import { LARGE_DOC } from './chunks.js';
|
|
21
|
+
import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
|
|
8
22
|
|
|
9
23
|
|
|
10
24
|
/**
|
|
11
25
|
* @import {Component} from "svelte";
|
|
12
26
|
* @import { LoroTreeNode, LoroTree } from "loro-crdt";
|
|
13
27
|
* @import {Extension} from '../utils/extensions.js';
|
|
28
|
+
* @import {DropPosition, DropTarget, DropKind} from '../utils/drop.js';
|
|
14
29
|
*/
|
|
15
30
|
|
|
16
31
|
/**
|
|
17
|
-
*
|
|
32
|
+
* The data map of a block's tree node: a `type` plus the block's own (open-ended) properties. Block classes narrow it
|
|
33
|
+
* with their own node typedef (`NabuNode<{text: LoroText}>`).
|
|
34
|
+
* @typedef {{type: string} & Record<string, any>} NabuNodeData
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @template {Object<string, any>} [T=Record<string, any>]
|
|
18
39
|
* @typedef {LoroTreeNode<{type: string} & T>} NabuNode
|
|
19
40
|
*/
|
|
20
41
|
|
|
21
42
|
/**
|
|
22
43
|
* @typedef {Object} NabuInit
|
|
44
|
+
* The options of an editor: the extensions to load, an initial snapshot, files, placeholders, readonly, language, Tab behaviour, keymap and
|
|
45
|
+
* command confirmation. Accepted by `new Nabu(init)`, by `createEditor` and the preset factories, and by `createPersistedEditor`.
|
|
23
46
|
* @property {Extension[]} [extensions]
|
|
24
47
|
* @property {Uint8Array<ArrayBufferLike>} [snapshot]
|
|
48
|
+
* @property {import('../files/files.svelte.js').FilesConfig} [files]
|
|
49
|
+
* @property {import('../utils/placeholders.js').PlaceholdersOption} [placeholders] - Hint text of empty blocks.
|
|
50
|
+
* `false`: none. `true` / omitted: defaults (shown on the empty block holding the cursor).
|
|
51
|
+
* Object: `{ show?: 'focus' | 'empty', text?: Record<blockType, string | false | ((block) => string | false)> }`.
|
|
52
|
+
* @property {boolean} [spellcheck] - Browser spellcheck on the editor (default `true`). `false` turns it off and adds the opt-out
|
|
53
|
+
* hints of the Grammarly extension (`data-gramm="false"`, ...). Code blocks are never spellchecked. Reactive: `nabu.spellcheck`.
|
|
54
|
+
* @property {boolean} [readonly] - Show the document without letting the user change it (default `false`). Reactive: `nabu.readonly`,
|
|
55
|
+
* assign to toggle live (`<NabuEditor readonly>` sets it). The editor root becomes `contenteditable="false"`; the engine ignores
|
|
56
|
+
* typing, paste, cut, drop, drag moves and every command / shortcut (undo and redo included). Copy, text selection and links
|
|
57
|
+
* keep working, and the floating UI (toolbar, slash menu, drag handle) hides itself. Code of the host is NOT restricted:
|
|
58
|
+
* `insert`, `importJSON`, `importMarkdown`, `importRemote`, `transact` still work, which is how a viewer loads its document.
|
|
59
|
+
* @property {string} [lang] - Language of the content, a BCP 47 tag (`'fr'`, `'en-GB'`). Set on the root as `lang`, so the browser's
|
|
60
|
+
* spellchecker, hyphenation and screen readers use it. Unset: inherits the page language. An invalid tag is ignored (warning).
|
|
61
|
+
* Reactive: `nabu.lang`.
|
|
62
|
+
* @property {'focus' | 'stay' | 'indent'} [tab] - What Tab / Shift+Tab do in a plain text block, where no block handles them
|
|
63
|
+
* structurally (list indent, code indentation and region titles keep their own meaning, whatever this says; P-41).
|
|
64
|
+
* `'focus'`: the browser default, Tab leaves the editor. `'stay'`: both keys are swallowed and the caret stays; Escape then Tab
|
|
65
|
+
* leaves (announced to screen readers, see `tabHint`). `'indent'`: Tab inserts a tab character at the caret (replacing a selection
|
|
66
|
+
* inside one block), Shift+Tab removes one right before it; several blocks selected: like `'stay'`. `'nest'` is planned, not
|
|
67
|
+
* implemented. Default: `tabDefault` (the factories of `presets.js` set it from the preset: Minimal / Text `'focus'`, Document /
|
|
68
|
+
* Full `'stay'`), else `'focus'`. An unknown value warns and uses the default. Reactive: `nabu.tab`.
|
|
69
|
+
* @property {'focus' | 'stay' | 'indent'} [tabDefault] - The mode used when `tab` is unset or invalid. Meant for the preset factories.
|
|
70
|
+
* @property {string | false} [tabHint] - Text announced on the editor root (`aria-description`) while `tab` traps the focus
|
|
71
|
+
* (`'stay'`, `'indent'`): default `"Press Escape then Tab to leave the editor"`; translate it here, `false` for none.
|
|
72
|
+
* Reactive: `nabu.tabHint`.
|
|
73
|
+
* @property {Record<string, string[]>} [keymap] - Replaces the keyboard shortcuts of commands (ADR 017): `{ 'mark:bold': ['Mod-Alt-b'] }`;
|
|
74
|
+
* `[]` disables a command's keys. Chords: see `utils/keys.js`; the same checks as for a declared key apply (reserved chords,
|
|
75
|
+
* a key without modifier needs the command's `when`).
|
|
76
|
+
* @property {import('../utils/command-confirm.svelte.js').CommandConfirmOptions} [commandConfirm] - Confirmation of commands asked by a
|
|
77
|
+
* key press (ADR 017 lot 2): `{ holdMs?: number (700), inviteMs?: number (5000), messages?: ConfirmMessages }`. `messages` are the
|
|
78
|
+
* texts of the prompts and outcomes announced to screen readers (English by default; each is a string or a function of the
|
|
79
|
+
* parameters, see `ConfirmMessages`); a command can override them with `confirm.messages`.
|
|
80
|
+
* @property {'mac' | 'other'} [platform] - Which platform's conventions `Mod` and the displayed shortcuts follow. Detected from the
|
|
81
|
+
* browser by default; set it for tests or server-side rendering.
|
|
25
82
|
*/
|
|
26
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Whether the character immediately before `pos` in a text behavior carries `name`.
|
|
86
|
+
* Used to decide the toggle direction for stored marks.
|
|
87
|
+
* @param {any} behavior @param {number} pos @param {string} name
|
|
88
|
+
* @returns {boolean}
|
|
89
|
+
*/
|
|
90
|
+
function inheritedMarkAt(behavior, pos, name) {
|
|
91
|
+
if (pos <= 0) return false;
|
|
92
|
+
const delta = behavior.delta;
|
|
93
|
+
let offset = 0;
|
|
94
|
+
for (const op of delta) {
|
|
95
|
+
if (typeof op.insert !== 'string') continue;
|
|
96
|
+
const end = offset + op.insert.length;
|
|
97
|
+
if (pos <= end) return !!(op.attributes && op.attributes[name]);
|
|
98
|
+
offset = end;
|
|
99
|
+
}
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* True for the input types that can trigger a block transform (typing / Enter), as opposed to
|
|
105
|
+
* deletions.
|
|
106
|
+
* @param {Event | { inputType?: string }} e
|
|
107
|
+
*/
|
|
108
|
+
export const isTransformInput = (e) => {
|
|
109
|
+
const type = /** @type {any} */ (e).inputType;
|
|
110
|
+
return type === 'insertText' || type === 'insertParagraph' || type === 'insertLineBreak' || type === 'insertSoftLineBreak';
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @typedef {Object} NabuInternals
|
|
115
|
+
* The engine machinery behind {@link Nabu#internals}. **Unstable**: may change in any version (see `docs/guides/extensions.md`,
|
|
116
|
+
* "Stability"). Methods are bound to the editor; their signatures are those of the `Nabu` methods of the same name.
|
|
117
|
+
* @property {Pulse} pulse The action bus behind `exec()`: `pulse.on(topic, handler)` observes or adds a topic at runtime.
|
|
118
|
+
* @property {CommandConfirmation} commandConfirm The confirmation controller of commands (hold / invite / choose): `start`, `stop`, `offer`, `choose`, `cancel`, `pending`.
|
|
119
|
+
* @property {Map<string, Array<(nabu: Nabu, ...args: any[]) => any>>} hooks Extension hooks by name, in registration order (the normalizers of `onBeforeTransaction`, the `onBeforeInput` handlers...).
|
|
120
|
+
* @property {WeakMap<Function, string>} hookOwners Hook function to the name of the extension that registered it.
|
|
121
|
+
* @property {import('../utils/extensions.js').InputRule[]} inputRules The input rules collected from the extensions.
|
|
122
|
+
* @property {import('../utils/extensions.js').PasteInterpreter[]} pasteInterpreters The paste interpreters collected from the extensions.
|
|
123
|
+
* @property {import('../utils/extensions.js').PasteFileHandler[]} pasteFileHandlers The paste file handlers, by priority.
|
|
124
|
+
* @property {UndoManager} undoManager The Loro undo manager (undo steps, merge window).
|
|
125
|
+
* @property {import('loro-crdt').LoroMap} content The free-form `content` map of the document.
|
|
126
|
+
* @property {import('../files/files.svelte.js').FilesConfig} fileConfig The resolved `files` option.
|
|
127
|
+
* @property {Record<string, boolean> | null} storedMarks Pending inline marks for the next typed character (reactive; assignable).
|
|
128
|
+
* @property {Nabu['toggleStoredMark']} toggleStoredMark
|
|
129
|
+
* @property {Nabu['clearStoredMarks']} clearStoredMarks
|
|
130
|
+
* @property {Nabu['noteTextChange']} noteTextChange
|
|
131
|
+
* @property {Nabu['captureUndoSelection']} captureUndoSelection Remember the selection for the undo step now being recorded.
|
|
132
|
+
* @property {Nabu['sealUndoEnd']} sealUndoEnd Close the "where did the last action end" mark of the undo history.
|
|
133
|
+
* @property {Nabu['updateRoots']} updateRoots Re-read the root blocks from the tree.
|
|
134
|
+
* @property {Nabu['deleteNode']} deleteNode Delete a block by node id (no commit).
|
|
135
|
+
* @property {Nabu['rearmTab']} rearmTab
|
|
136
|
+
* @property {string | undefined} tabDescription The `aria-description` the root carries while `tab` traps the focus.
|
|
137
|
+
* @property {Nabu['dispatchEventToSelection']} dispatchEventToSelection Route a native event to the block that holds the selection.
|
|
138
|
+
* @property {Nabu['handleKeydown']} handleKeydown The keydown pipeline (commands first, then hooks, then the block).
|
|
139
|
+
* @property {Nabu['handleBeforeinput']} handleBeforeinput
|
|
140
|
+
* @property {Nabu['beforeinput']} beforeinput
|
|
141
|
+
* @property {Nabu['handleCompositionStart']} handleCompositionStart
|
|
142
|
+
* @property {Nabu['handleCompositionUpdate']} handleCompositionUpdate
|
|
143
|
+
* @property {Nabu['handleCompositionEnd']} handleCompositionEnd
|
|
144
|
+
* @property {Nabu['handleMousedown']} handleMousedown
|
|
145
|
+
* @property {Nabu['handleCopy']} handleCopy Write the selection to a clipboard (every format).
|
|
146
|
+
* @property {Nabu['handleCut']} handleCut
|
|
147
|
+
* @property {Nabu['handlePaste']} handlePaste The paste pipeline (interpreters, files, `acceptPaste`).
|
|
148
|
+
* @property {Nabu['insertFragment']} insertFragment Insert a `PasteFragment` at the selection (what a paste does after interpreting).
|
|
149
|
+
* @property {Nabu['handleDragStart']} handleDragStart
|
|
150
|
+
* @property {Nabu['handleDragOver']} handleDragOver
|
|
151
|
+
* @property {Nabu['handleDragLeave']} handleDragLeave
|
|
152
|
+
* @property {Nabu['handleDragEnd']} handleDragEnd
|
|
153
|
+
* @property {Nabu['handleDrop']} handleDrop
|
|
154
|
+
* @property {Nabu['dropAt']} dropAt Drop a `DataTransfer` at a position, as the drag and drop does.
|
|
155
|
+
* @property {DropTarget | null} dropTarget The drop indicator being shown (reactive).
|
|
156
|
+
* @property {{ normalize: NabuSelection['normalize'], scheduleRepair: NabuSelection['scheduleRepair'], repairAfterRemoval: NabuSelection['repairAfterRemoval'], placements: number, attachRoot: NabuSelection['attachRoot'], owns: NabuSelection['owns'], scope: NabuSelection['scope'], root: HTMLElement | null }} selection The selection's own repair machinery, and the engine's root element: `attachRoot(el)` (what `Nabu.svelte` calls on mount, it returns the detach function), `root`, `owns(node)` (inside MY root, not in a nested editor) and `scope()` ('mine' | 'outside' | 'foreign': whose business the live DOM selection is).
|
|
157
|
+
*/
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The editor engine. It owns the document (a Loro CRDT), the block tree and its registry, the selection, the commands and the
|
|
161
|
+
* extensions, and runs the event, clipboard and drag and drop pipelines; `NabuEditor` renders it. Create one with `createEditor`
|
|
162
|
+
* (or a preset factory such as `createDocumentEditor`) rather than `new Nabu(...)`, then read and write the content through
|
|
163
|
+
* `serialize`, `importMarkdown`, `importJSON`, `exec` and `transact`. The members documented as public are the stable contract of
|
|
164
|
+
* `@aionbuilders/nabu/extend`; `internals` is the unstable door to the rest.
|
|
165
|
+
*/
|
|
27
166
|
export class Nabu {
|
|
28
167
|
/** @type {Pulse} */
|
|
29
168
|
#pulse = new Pulse();
|
|
30
169
|
/** @type {import('../utils/extensions.js').PasteInterpreter[]} */
|
|
31
170
|
#pasteInterpreters = [];
|
|
171
|
+
/** @type {import('../utils/extensions.js').PasteFileHandler[]} sorted by priority, highest first */
|
|
172
|
+
#pasteFileHandlers = [];
|
|
173
|
+
|
|
174
|
+
// ── IME composition state ────────────────────────────────────────────────
|
|
175
|
+
// During an active IME composition the browser mutates the DOM freely
|
|
176
|
+
// (insertCompositionText cannot be canceled). We switch to "DOM-first"
|
|
177
|
+
// for the duration of the composition and sync the result into Loro at
|
|
178
|
+
// compositionend. See issue #6.
|
|
179
|
+
#composing = false;
|
|
180
|
+
/**
|
|
181
|
+
* True during an IME composition: the browser owns the DOM, the caret must not be touched.
|
|
182
|
+
* @public
|
|
183
|
+
*/
|
|
184
|
+
get composing() { return this.#composing; }
|
|
185
|
+
/** @type {number | null} offset modèle au début de la composition (repli si le curseur Loro ne se résout pas) */
|
|
186
|
+
#compositionStartOffset = null;
|
|
187
|
+
/**
|
|
188
|
+
* Where the composed text goes, as Loro cursors (P-101): an edit of the SAME block before the caret during the composition
|
|
189
|
+
* (a programmatic insert, a direct `importRemote`) shifts it, a plain offset would not.
|
|
190
|
+
* @type {import('./undo-selection.js').Endpoint | null}
|
|
191
|
+
*/
|
|
192
|
+
#compositionAnchor = null;
|
|
193
|
+
/** The block a composition runs in, reactive: its placeholder is hidden meanwhile (P-103). @type {Block | null} */
|
|
194
|
+
#composingBlock = $state.raw(null);
|
|
195
|
+
/**
|
|
196
|
+
* The block holding the running composition, or null. Reactive.
|
|
197
|
+
* @public
|
|
198
|
+
*/
|
|
199
|
+
get composingBlock() { return this.#composingBlock; }
|
|
200
|
+
/** An undo group is open: the deletion of a selection replaced by a composition and the composed text are ONE undo step. */
|
|
201
|
+
#compositionGroup = false;
|
|
202
|
+
/** @type {Block | null} bloc cible au début de la composition */
|
|
203
|
+
#compositionStartBlock = null;
|
|
204
|
+
/** Configured UndoManager merge window (ms), restored after a paste isolation. */
|
|
205
|
+
#mergeInterval = 1000;
|
|
206
|
+
/** Undo steps still to push with merging disabled (paste / structural op / cut + the next one); 0 = not isolating. */
|
|
207
|
+
#isolatedSteps = 0;
|
|
208
|
+
#isolating = false;
|
|
209
|
+
/** True during the synchronous turn that started a structural undo step (see commit()). */
|
|
210
|
+
#structuralBurst = false;
|
|
211
|
+
/**
|
|
212
|
+
* Explicit caret to store with the NEXT pushed undo step (instead of the live selection): set by
|
|
213
|
+
* shortcut() so that undoing a block shortcut puts the caret back right after the typed trigger.
|
|
214
|
+
* @type {{ block: Block, offset: number } | null}
|
|
215
|
+
*/
|
|
216
|
+
#undoCursor = null;
|
|
217
|
+
/**
|
|
218
|
+
* The selection as it was before the change now being recorded, kept as Loro cursors (see undo-selection.js): refreshed by
|
|
219
|
+
* {@link Nabu#captureUndoSelection} while the model and the DOM agree, handed to the UndoManager when it pushes a step.
|
|
220
|
+
* @type {import('./undo-selection.js').UndoSelection | null}
|
|
221
|
+
*/
|
|
222
|
+
#undoSel = null;
|
|
223
|
+
/** Undo / redo whose render is still pending: they put the selection back themselves. */
|
|
224
|
+
#undoing = 0;
|
|
225
|
+
/** Value of `selection.placements` when `#undoSel` was captured: tells whether the editor placed the selection since. */
|
|
226
|
+
#undoSelPlacements = 0;
|
|
227
|
+
/** A selection fix-up after a text change is already scheduled. */
|
|
228
|
+
#keepPending = false;
|
|
229
|
+
/** Commits and undo / redo whose render is still pending: the DOM lags the model, so the selection must not be captured. */
|
|
230
|
+
#busy = 0;
|
|
231
|
+
/** Counter end of the undo step just pushed: the next settled selection is where that action ENDED (what redo restores). */
|
|
232
|
+
#endKey = /** @type {number | null} */ (null);
|
|
233
|
+
/** Counter end of the step being undone (set by its pop, read by the redo step pushed right after). */
|
|
234
|
+
#undoneEnd = /** @type {number | null} */ (null);
|
|
235
|
+
/** Selection where each recent action ended, by the counter end of its undo step. @type {Map<number, import('./undo-selection.js').UndoSelection>} */
|
|
236
|
+
#actionEnds = new Map();
|
|
32
237
|
|
|
33
238
|
/** @param {NabuInit} init */
|
|
34
239
|
constructor(init = {}) {
|
|
@@ -37,53 +242,94 @@ export class Nabu {
|
|
|
37
242
|
this.doc.import(init.snapshot);
|
|
38
243
|
}
|
|
39
244
|
|
|
245
|
+
/**
|
|
246
|
+
* The text selection of the editor (a reactive wrapper of the DOM selection, in terms of blocks).
|
|
247
|
+
* @type {NabuSelection}
|
|
248
|
+
* @public
|
|
249
|
+
*/
|
|
40
250
|
this.selection = new NabuSelection(this);
|
|
41
|
-
|
|
251
|
+
/**
|
|
252
|
+
* The document tree (Loro): one node per block, `node.data` holds the block's `type` and props.
|
|
253
|
+
* @public
|
|
254
|
+
*/
|
|
255
|
+
this.tree = /** @type {LoroTree<NabuNodeData>} */ (this.doc.getTree("blocks"));
|
|
42
256
|
this.content = this.doc.getMap("content");
|
|
43
257
|
|
|
44
258
|
// Initialize Undo/Redo Manager
|
|
45
259
|
this.undoManager = new UndoManager(this.doc, {
|
|
46
260
|
maxUndoSteps: 100,
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
261
|
+
// Background completions (e.g. a pasted file finishing its upload) are not undo steps of their own.
|
|
262
|
+
excludeOriginPrefixes: ['nabu:silent'],
|
|
263
|
+
mergeInterval: this.#mergeInterval,
|
|
264
|
+
onPush: (isUndo, range) => {
|
|
265
|
+
if (this.#isolatedSteps > 0) this.#isolatedSteps--;
|
|
266
|
+
// The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
|
|
267
|
+
// (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
|
|
268
|
+
// an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
|
|
269
|
+
const explicit = this.#undoCursor;
|
|
270
|
+
this.#undoCursor = null;
|
|
271
|
+
const ended = !isUndo && this.#undoneEnd !== null ? this.#actionEnds.get(this.#undoneEnd) : undefined;
|
|
272
|
+
const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? this.#undoSel) ?? legacySelection(this);
|
|
273
|
+
this.#endKey = isUndo ? range?.end ?? null : null;
|
|
274
|
+
return { value: /** @type {any} */ (stored), cursors: [] };
|
|
60
275
|
},
|
|
61
|
-
onPop: (
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const block = this.blocks.get(value.blockId);
|
|
67
|
-
if (block && block.behaviors?.has('text')) {
|
|
68
|
-
this.selection.setCursor(block, value.offset);
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
}
|
|
276
|
+
onPop: (isUndo, storedValue, range) => {
|
|
277
|
+
this.#undoneEnd = isUndo ? range?.end ?? null : null;
|
|
278
|
+
this.#endKey = null;
|
|
279
|
+
const value = /** @type {any} */ (storedValue?.value);
|
|
280
|
+
if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(this, value);
|
|
72
281
|
}
|
|
73
282
|
});
|
|
74
283
|
|
|
284
|
+
/**
|
|
285
|
+
* The extensions the editor was built with, in order.
|
|
286
|
+
* @type {Extension[]}
|
|
287
|
+
* @public
|
|
288
|
+
*/
|
|
75
289
|
this.extensions = init.extensions || [];
|
|
290
|
+
this.fileConfig = init.files || {};
|
|
291
|
+
this.placeholders = normalizePlaceholders(init.placeholders);
|
|
292
|
+
this.spellcheck = init.spellcheck !== false;
|
|
293
|
+
this.lang = init.lang;
|
|
294
|
+
this.readonly = !!init.readonly;
|
|
295
|
+
this.#tabDefault = resolveTabMode(init.tabDefault, 'focus', (message) => this.warn(message));
|
|
296
|
+
this.tab = init.tab;
|
|
297
|
+
if (typeof init.tabHint === 'string' || init.tabHint === false) this.tabHint = init.tabHint;
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Commands and keyboard shortcuts (ADR 017): `list()`, `get(id)`, `run(id, data)`. A plain snapshot API, the set of
|
|
301
|
+
* commands is fixed once the editor is built.
|
|
302
|
+
*/
|
|
303
|
+
this.commandConfirm = new CommandConfirmation(this, init.commandConfirm);
|
|
304
|
+
this.systems.set('command-confirm', { start: () => this.commandConfirm.start(), stop: () => this.commandConfirm.stop() });
|
|
305
|
+
/**
|
|
306
|
+
* Commands and keyboard shortcuts (ADR 017): `list()`, `get(id)`, `has(id)`, `run(id, data)`, `offer(id)`. A plain
|
|
307
|
+
* snapshot API; the set of commands is fixed once the editor is built.
|
|
308
|
+
* @type {CommandRegistry}
|
|
309
|
+
* @public
|
|
310
|
+
*/
|
|
311
|
+
this.commands = new CommandRegistry(this, { keymap: init.keymap, platform: init.platform });
|
|
312
|
+
// Engine commands first: they win a tie with an extension's command on the same chord.
|
|
313
|
+
this.#registerCommands('core', {
|
|
314
|
+
undo: { label: 'Undo', keys: ['Mod-z'], run: () => { this.undo(); } },
|
|
315
|
+
redo: { label: 'Redo', keys: ['Mod-Shift-z', 'Mod-y'], run: () => { this.redo(); } },
|
|
316
|
+
// Keyboard alternative to dragging (see move.js): `data.block` (a Block or its id) moves that block instead.
|
|
317
|
+
'block:move-up': { label: 'Move block up', keys: ['Mod-Shift-ArrowUp'], run: (_nabu, _ctx, data) => moveBlocks(this, 'up', data?.block ?? null) },
|
|
318
|
+
'block:move-down': { label: 'Move block down', keys: ['Mod-Shift-ArrowDown'], run: (_nabu, _ctx, data) => moveBlocks(this, 'down', data?.block ?? null) },
|
|
319
|
+
});
|
|
76
320
|
|
|
77
321
|
if (this.extensions?.length) {
|
|
78
322
|
for (const ext of this.extensions) {
|
|
79
323
|
if (ext.block) this.registry.set(ext.name, ext.block);
|
|
324
|
+
if (ext.block && ext.defaultBlock) this.defaultBlockType = ext.name;
|
|
80
325
|
if (ext.component) this.components.set(ext.name, ext.component);
|
|
81
326
|
if (ext.hooks) {
|
|
82
|
-
for (const [hookName, hookFn] of Object.entries(ext.hooks)) {
|
|
327
|
+
for (const [hookName, hookFn] of /** @type {[string, (nabu: Nabu, ...args: any[]) => any][]} */ (Object.entries(ext.hooks))) {
|
|
83
328
|
if (!this.hooks.has(hookName)) {
|
|
84
329
|
this.hooks.set(hookName, []);
|
|
85
330
|
}
|
|
86
|
-
this.hooks.get(hookName).push(hookFn);
|
|
331
|
+
/** @type {Array<(nabu: Nabu, ...args: any[]) => any>} */ (this.hooks.get(hookName)).push(hookFn);
|
|
332
|
+
this.hookOwners.set(hookFn, ext.name);
|
|
87
333
|
}
|
|
88
334
|
}
|
|
89
335
|
|
|
@@ -95,16 +341,32 @@ export class Nabu {
|
|
|
95
341
|
|
|
96
342
|
if (ext.actions) {
|
|
97
343
|
for (const [topic, handler] of Object.entries(ext.actions)) {
|
|
98
|
-
this.#pulse.on(topic, ({ event }) => handler(this, event.data, event.topic));
|
|
344
|
+
this.#pulse.on(topic, ({ event }) => { if (this.#readonly) return; return handler(this, event.data, event.topic); }); // read-only: actions are edits, they do nothing
|
|
99
345
|
}
|
|
100
346
|
}
|
|
101
347
|
|
|
348
|
+
if (ext.commands) this.#registerCommands(ext.name, ext.commands);
|
|
349
|
+
if (ext.commandContext) this.commands.addContextProvider(ext.commandContext, ext.name);
|
|
350
|
+
|
|
102
351
|
if (ext.pasteInterpreters?.length) {
|
|
103
352
|
for (const interpreter of ext.pasteInterpreters) {
|
|
104
353
|
this.#pasteInterpreters.push(interpreter);
|
|
105
354
|
}
|
|
106
355
|
}
|
|
107
356
|
|
|
357
|
+
if (ext.pasteFileHandlers?.length) {
|
|
358
|
+
this.#pasteFileHandlers.push(...ext.pasteFileHandlers);
|
|
359
|
+
this.#pasteFileHandlers.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (ext.inputRules?.length) {
|
|
363
|
+
for (const rule of ext.inputRules) {
|
|
364
|
+
this.inputRules.push(rule);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (ext.slashCommands?.length) this.slashCommands.push(...ext.slashCommands);
|
|
369
|
+
|
|
108
370
|
if (ext.loroTextStyles && Object.keys(ext.loroTextStyles).length) {
|
|
109
371
|
this.doc.configTextStyle(ext.loroTextStyles);
|
|
110
372
|
}
|
|
@@ -112,115 +374,326 @@ export class Nabu {
|
|
|
112
374
|
}
|
|
113
375
|
}
|
|
114
376
|
|
|
115
|
-
// Core actions
|
|
116
|
-
this
|
|
117
|
-
this.#pulse.on('redo', () => this.redo());
|
|
377
|
+
// Core actions (`undo`, `redo`) are commands, registered above.
|
|
378
|
+
this.commands.checkKeymap();
|
|
118
379
|
|
|
119
380
|
const roots = /** @type {NabuNode[]} */ (this.tree.roots());
|
|
120
381
|
if (roots?.length) {
|
|
121
382
|
for (const root of roots) {
|
|
122
383
|
const block = Block.load(this, root);
|
|
384
|
+
block.index = this.children.length;
|
|
123
385
|
this.children.push(block);
|
|
124
386
|
}
|
|
125
387
|
}
|
|
126
388
|
|
|
389
|
+
// Files: the local asset store, and the migration of a beta document whose files are still inside it (ADR 014 §3.7).
|
|
390
|
+
Files.get(this);
|
|
391
|
+
|
|
127
392
|
// this.doc.subscribe((event) => {
|
|
128
393
|
// // event.events contient un tableau listant TOUTES les opérations
|
|
129
394
|
// // (texte ajouté, nœuds déplacés, etc.) qui viennent d'être commitées.
|
|
130
395
|
// console.log("Rapport de la transaction :", event.events);
|
|
131
396
|
// });
|
|
132
397
|
|
|
398
|
+
// One event batch = one refresh. The affected containers are COLLECTED while the batch is read, then each is refreshed
|
|
399
|
+
// once (the root list at most once, every parent at most once): refreshing per action made an import / a mass undo / a
|
|
400
|
+
// big paste quadratic (P-104). The doc already holds the final state of the batch, so the order of the actions is moot.
|
|
133
401
|
this.tree.subscribe((event) => {
|
|
402
|
+
let rootsDirty = false;
|
|
403
|
+
/** @type {Set<string>} */
|
|
404
|
+
const parents = new Set();
|
|
405
|
+
/** @type {Set<string>} */
|
|
406
|
+
const retyped = new Set();
|
|
407
|
+
|
|
408
|
+
let removed = false;
|
|
134
409
|
event.events.forEach(e => {
|
|
135
410
|
if (e.diff.type === "tree") {
|
|
136
411
|
e.diff.diff.forEach(action => {
|
|
412
|
+
if (action.action === 'delete') removed = true;
|
|
137
413
|
if (action.action === 'create' || action.action === 'move' || action.action === 'delete') {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
if (action.
|
|
147
|
-
const oldParentId = action.oldParent.toString();
|
|
148
|
-
const oldParentBlock = this.blocks.get(oldParentId);
|
|
149
|
-
if (oldParentBlock) oldParentBlock.updateChildren();
|
|
150
|
-
}
|
|
414
|
+
// `parent` is set on create / move, `oldParent` on move / delete (a TreeDiffItem is a union of the three)
|
|
415
|
+
const { parent, oldParent } = /** @type {{ parent?: string, oldParent?: string }} */ (action);
|
|
416
|
+
if (parent) parents.add(parent.toString());
|
|
417
|
+
else rootsDirty = true;
|
|
418
|
+
|
|
419
|
+
if (oldParent) parents.add(oldParent.toString());
|
|
420
|
+
// A node that LEAVES the root for a container has no `oldParent` (the root is no node): the
|
|
421
|
+
// root list must be refreshed too, else the old element stays rendered next to the new one.
|
|
422
|
+
else if (action.action === 'move' && parent) rootsDirty = true;
|
|
151
423
|
}
|
|
152
424
|
})
|
|
153
425
|
}
|
|
154
426
|
|
|
155
427
|
if (e.diff.type === "map") {
|
|
156
|
-
|
|
157
428
|
const newType = e.diff.updated["type"];
|
|
158
429
|
if (newType !== undefined) {
|
|
159
430
|
const nodeId = e.path[1].toString();
|
|
160
431
|
const block = this.blocks.get(nodeId);
|
|
161
432
|
if (block && block.type !== newType) {
|
|
162
|
-
|
|
163
|
-
|
|
433
|
+
retyped.add(nodeId);
|
|
434
|
+
if (block.parent) parents.add(block.parent.id);
|
|
435
|
+
else rootsDirty = true;
|
|
164
436
|
}
|
|
165
437
|
}
|
|
166
438
|
}
|
|
167
439
|
})
|
|
440
|
+
|
|
441
|
+
if (removed) this.selection.scheduleRepair?.(); // the caret may have been in the removed blocks (P-108)
|
|
442
|
+
if (rootsDirty) this.updateRoots(retyped);
|
|
443
|
+
for (const parentId of parents) {
|
|
444
|
+
// A block retyped into a leaf (no children) in the same transaction has no updateChildren().
|
|
445
|
+
/** @type {{ updateChildren?: (retyped?: Set<string>) => void } | undefined} */ (this.blocks.get(parentId))?.updateChildren?.(retyped);
|
|
446
|
+
}
|
|
168
447
|
});
|
|
169
448
|
|
|
170
449
|
this.init();
|
|
171
450
|
}
|
|
172
451
|
|
|
452
|
+
/**
|
|
453
|
+
* What a hook or an `onBeforeInput` handler returns to stop the engine (and the hooks after it).
|
|
454
|
+
* @type {symbol}
|
|
455
|
+
* @public
|
|
456
|
+
*/
|
|
173
457
|
static BREAK = Symbol("BREAK");
|
|
458
|
+
/**
|
|
459
|
+
* What a hook returns to let the engine go on (same as returning nothing).
|
|
460
|
+
* @type {symbol}
|
|
461
|
+
* @public
|
|
462
|
+
*/
|
|
174
463
|
static CONTINUE = Symbol("CONTINUE");
|
|
464
|
+
/**
|
|
465
|
+
* `Nabu.BREAK`, reachable from the instance a hook receives.
|
|
466
|
+
* @type {symbol}
|
|
467
|
+
* @public
|
|
468
|
+
*/
|
|
175
469
|
BREAK = Nabu.BREAK;
|
|
470
|
+
/**
|
|
471
|
+
* `Nabu.CONTINUE`, reachable from the instance a hook receives.
|
|
472
|
+
* @type {symbol}
|
|
473
|
+
* @public
|
|
474
|
+
*/
|
|
176
475
|
CONTINUE = Nabu.CONTINUE;
|
|
177
476
|
|
|
178
|
-
/**
|
|
477
|
+
/**
|
|
478
|
+
* The Loro document behind the editor (public: connect it to a server with `doc.subscribeLocalUpdates` and `importRemote`).
|
|
479
|
+
* @type {LoroDoc}
|
|
480
|
+
* @public
|
|
481
|
+
*/
|
|
179
482
|
doc;
|
|
180
|
-
/**
|
|
483
|
+
/**
|
|
484
|
+
* The block classes registered by the loaded extensions, by block type.
|
|
485
|
+
* @type {SvelteMap<string, typeof Block>}
|
|
486
|
+
* @public
|
|
487
|
+
*/
|
|
181
488
|
registry = new SvelteMap();
|
|
182
|
-
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Type of the default text block (declared by an extension with `defaultBlock: true`): created by the
|
|
492
|
+
* engine when it needs an empty text block of its own, e.g. a caret after a trailing void block.
|
|
493
|
+
* @type {string | null}
|
|
494
|
+
* @public
|
|
495
|
+
*/
|
|
496
|
+
defaultBlockType = null;
|
|
497
|
+
/**
|
|
498
|
+
* The Svelte components registered by the loaded extensions, by block type.
|
|
499
|
+
* @type {SvelteMap<string, Component>}
|
|
500
|
+
* @public
|
|
501
|
+
*/
|
|
183
502
|
components = new SvelteMap();
|
|
184
|
-
/**
|
|
503
|
+
/**
|
|
504
|
+
* Every live block of the document, by tree id.
|
|
505
|
+
* @type {SvelteMap<string, Block>}
|
|
506
|
+
* @public
|
|
507
|
+
*/
|
|
185
508
|
blocks = new SvelteMap();
|
|
186
509
|
|
|
187
|
-
/**
|
|
510
|
+
/**
|
|
511
|
+
* The live blocks of each type (reactive sets, by block type).
|
|
512
|
+
* @type {SvelteMap<string, SvelteSet<Block>>}
|
|
513
|
+
* @public
|
|
514
|
+
*/
|
|
188
515
|
blocksByType = new SvelteMap();
|
|
189
516
|
|
|
190
|
-
/**
|
|
517
|
+
/**
|
|
518
|
+
* Registered subsystems. Each system should implement:
|
|
519
|
+
* - `start(): void` — called when the editor mounts
|
|
520
|
+
* - `stop(): void` — called when the editor unmounts
|
|
521
|
+
* @type {SvelteMap<string, { start?: () => void, stop?: () => void, [key: string]: any }>}
|
|
522
|
+
* @public
|
|
523
|
+
*/
|
|
191
524
|
systems = new SvelteMap();
|
|
192
525
|
|
|
526
|
+
/**
|
|
527
|
+
* Extension hooks by name, in registration order (see `ExtensionHooks`).
|
|
528
|
+
* @type {Map<string, Array<(nabu: Nabu, ...args: any[]) => any>>}
|
|
529
|
+
*/
|
|
193
530
|
hooks = new Map();
|
|
194
531
|
|
|
532
|
+
/**
|
|
533
|
+
* Hook function -> name of the extension that registered it. Lets `Block#ascend` run the hooks of the
|
|
534
|
+
* extension that OWNS the block type before the generic ones (type-specific handler wins).
|
|
535
|
+
* @type {WeakMap<Function, string>}
|
|
536
|
+
*/
|
|
537
|
+
hookOwners = new WeakMap();
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Declarative input rules collected from extensions, tested by TextBehavior
|
|
541
|
+
* against the text before the cursor on matching beforeinput events.
|
|
542
|
+
* @type {import('../utils/extensions.js').InputRule[]}
|
|
543
|
+
*/
|
|
544
|
+
inputRules = [];
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Slash-menu entries contributed by extensions (`Extension#slashCommands`); the slash menu lists ONLY these (plus the
|
|
548
|
+
* integrator's extras), sorted by `group` / `order`, keeping those whose `when(engine, block)` holds at the caret.
|
|
549
|
+
* @type {import('../ui/slash-menu.svelte.js').SlashCommand[]}
|
|
550
|
+
* @public
|
|
551
|
+
*/
|
|
552
|
+
slashCommands = [];
|
|
553
|
+
|
|
554
|
+
/** @type {import('../files/files.svelte.js').FilesConfig} */
|
|
555
|
+
fileConfig = {};
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Resolved `placeholders` option (see NabuInit). Reassign to change it at runtime.
|
|
559
|
+
* @type {import('../utils/placeholders.js').ResolvedPlaceholders}
|
|
560
|
+
* @public
|
|
561
|
+
*/
|
|
562
|
+
placeholders = $state.raw(normalizePlaceholders());
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Resolved `spellcheck` option (see NabuInit). Reactive: assign to change it at runtime.
|
|
566
|
+
* @type {boolean}
|
|
567
|
+
* @public
|
|
568
|
+
*/
|
|
569
|
+
spellcheck = $state.raw(true);
|
|
570
|
+
|
|
571
|
+
#readonly = $state.raw(false);
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Read-only mode (see the `readonly` option of NabuInit). Reactive: assign to switch it on or off at runtime. While `true`
|
|
575
|
+
* the user cannot change the document: input, paste, cut, drop, drag moves and commands (shortcuts, `commands.run`,
|
|
576
|
+
* `exec` of a command, undo / redo) are ignored by the engine, and the UI components hide themselves. Programmatic
|
|
577
|
+
* edits by the host (`insert`, `importJSON`...) are not blocked. View state that is not part of the document (a toggle
|
|
578
|
+
* opened to read it) stays possible and is never written to the document.
|
|
579
|
+
* @type {boolean}
|
|
580
|
+
* @public
|
|
581
|
+
*/
|
|
582
|
+
get readonly() { return this.#readonly; }
|
|
583
|
+
set readonly(value) {
|
|
584
|
+
this.#readonly = !!value;
|
|
585
|
+
if (this.#readonly) this.commandConfirm?.cancel('api'); // a hold / invite / chooser in progress is moot
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** @type {string | undefined} */
|
|
589
|
+
#lang = $state.raw(undefined);
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Resolved `lang` option (see NabuInit): a valid BCP 47 tag, or `undefined` (inherit the page language).
|
|
593
|
+
* Reactive: assign to change it at runtime; an invalid value is ignored (warning) and leaves it unchanged.
|
|
594
|
+
* @type {string | undefined}
|
|
595
|
+
* @public
|
|
596
|
+
*/
|
|
597
|
+
get lang() { return this.#lang; }
|
|
598
|
+
set lang(value) {
|
|
599
|
+
const { lang, valid } = normalizeLang(value);
|
|
600
|
+
if (!valid) { this.warn(`Ignoring invalid "lang" (not a BCP 47 tag): ${String(value)}`); return; }
|
|
601
|
+
this.#lang = lang;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** @type {import('../utils/tab.js').TabMode} */
|
|
605
|
+
#tabDefault = 'focus';
|
|
606
|
+
|
|
607
|
+
/** @type {import('../utils/tab.js').TabMode} */
|
|
608
|
+
#tab = $state.raw('focus');
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Resolved `tab` option (see NabuInit): what Tab / Shift+Tab do in a plain text block. Reactive: assign to change it at runtime;
|
|
612
|
+
* an unknown value warns and gives the default of the editor (its preset).
|
|
613
|
+
* @type {import('../utils/tab.js').TabMode}
|
|
614
|
+
* @public
|
|
615
|
+
*/
|
|
616
|
+
get tab() { return this.#tab; }
|
|
617
|
+
/** @param {unknown} value */
|
|
618
|
+
set tab(value) { this.#tab = resolveTabMode(value, this.#tabDefault, (message) => this.warn(message)); }
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Announcement of the Escape-then-Tab way out (option `tabHint`), `false` for none. Reactive.
|
|
622
|
+
* @type {string | false}
|
|
623
|
+
* @public
|
|
624
|
+
*/
|
|
625
|
+
tabHint = $state.raw(DEFAULT_TAB_HINT);
|
|
626
|
+
|
|
627
|
+
/** What the editor root exposes as `aria-description`: the hint, only while the mode keeps the focus in. */
|
|
628
|
+
get tabDescription() { return !this.#readonly && this.#tab !== 'focus' && this.tabHint ? this.tabHint : undefined; }
|
|
629
|
+
|
|
630
|
+
/** An Escape nobody consumed was the previous key: the next Tab / Shift+Tab leaves the editor (see `utils/tab.js`). */
|
|
631
|
+
#tabEscaped = false;
|
|
632
|
+
|
|
633
|
+
/** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
|
|
634
|
+
rearmTab() { this.#tabEscaped = false; }
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* Pending inline formatting for the next typed character (active marks at a
|
|
638
|
+
* collapsed cursor). null = inherit from the span at the cursor.
|
|
639
|
+
* @type {Record<string, boolean> | null}
|
|
640
|
+
*/
|
|
641
|
+
storedMarks = $state(null);
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* When true, `nabu.warn()` logs to the console (`[Nabu]`).
|
|
645
|
+
* @public
|
|
646
|
+
*/
|
|
195
647
|
debugging = $state(false);
|
|
196
648
|
|
|
197
649
|
/**
|
|
198
650
|
* Root-level serializers. Each function receives the Nabu instance and returns the serialized document.
|
|
199
651
|
* @type {Map<string, (nabu: Nabu) => any>}
|
|
652
|
+
* @public
|
|
200
653
|
*/
|
|
201
|
-
serializers = new Map([
|
|
654
|
+
serializers = new Map(/** @type {Array<[string, (nabu: Nabu) => any]>} */ ([
|
|
202
655
|
['markdown', (nabu) =>
|
|
203
656
|
nabu.children
|
|
204
657
|
.map(b => b.serialize('markdown'))
|
|
205
658
|
.filter(Boolean)
|
|
206
659
|
.join('\n\n')
|
|
207
660
|
],
|
|
208
|
-
['json', (nabu) =>
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
661
|
+
['json', (nabu) => {
|
|
662
|
+
const blocks = nabu.children.map(b => b.serialize('json')).filter(Boolean);
|
|
663
|
+
// The bytes of the `nabu-asset:` media travel with the document (same `assets` map as the clipboard format).
|
|
664
|
+
const assets = Files.get(nabu).embedAssets(blocks);
|
|
665
|
+
return { version: JSON_FORMAT_VERSION, blocks, ...(assets ? { assets } : {}) };
|
|
666
|
+
}]
|
|
667
|
+
]));
|
|
213
668
|
|
|
214
|
-
/**
|
|
669
|
+
/**
|
|
670
|
+
* The root blocks of the document, in order (reactive).
|
|
671
|
+
* @type {Block[]}
|
|
672
|
+
* @public
|
|
673
|
+
*/
|
|
215
674
|
children = $state([]);
|
|
216
675
|
|
|
676
|
+
/**
|
|
677
|
+
* Number of caret positions in the document (the sum of the root blocks').
|
|
678
|
+
* @public
|
|
679
|
+
*/
|
|
217
680
|
positions = $derived(this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
|
|
218
681
|
|
|
682
|
+
/**
|
|
683
|
+
* True when the document has no block.
|
|
684
|
+
* @public
|
|
685
|
+
*/
|
|
219
686
|
get isEmpty() {
|
|
220
687
|
return this.children.length === 0;
|
|
221
688
|
}
|
|
222
689
|
|
|
223
|
-
/**
|
|
690
|
+
/**
|
|
691
|
+
* Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, or one an extension
|
|
692
|
+
* adds with `serializers`); `null` (and a warning) for an unknown format.
|
|
693
|
+
* @param {string} format
|
|
694
|
+
* @returns {any}
|
|
695
|
+
* @public
|
|
696
|
+
*/
|
|
224
697
|
serialize(format) {
|
|
225
698
|
const fn = this.serializers.get(format);
|
|
226
699
|
if (!fn) {
|
|
@@ -234,21 +707,27 @@ export class Nabu {
|
|
|
234
707
|
this.hooks.get("onInit")?.forEach(hook => hook(this));
|
|
235
708
|
}
|
|
236
709
|
|
|
237
|
-
/**
|
|
238
|
-
|
|
710
|
+
/**
|
|
711
|
+
* Rafraîchit les blocs racines de l'éditeur. Les blocs déjà connus sont réutilisés tels quels : seul le type des nœuds
|
|
712
|
+
* listés dans `retyped` (ids dont le `type` vient de changer) est relu.
|
|
713
|
+
* @param {Set<string>} [retyped] without it, the type of every root is checked
|
|
714
|
+
*/
|
|
715
|
+
updateRoots(retyped) {
|
|
239
716
|
const roots = /** @type {NabuNode[]} */ (this.tree.roots());
|
|
240
717
|
this.children = roots.map((root, i) => {
|
|
241
718
|
const id = root.id.toString();
|
|
242
719
|
let block = this.blocks.get(id);
|
|
243
|
-
const currentType = root.data.get("type");
|
|
244
|
-
|
|
245
|
-
if (!block || block.type !== currentType) {
|
|
246
|
-
if (block) {
|
|
247
|
-
this.blocks.delete(id);
|
|
248
|
-
this.blocksByType.get(block.type)?.delete(block);
|
|
249
|
-
}
|
|
250
720
|
|
|
251
|
-
|
|
721
|
+
if (!block || !retyped || retyped.has(id)) {
|
|
722
|
+
const currentType = root.data.get("type");
|
|
723
|
+
if (!block || block.type !== currentType) {
|
|
724
|
+
if (block) {
|
|
725
|
+
this.blocks.delete(id);
|
|
726
|
+
this.blocksByType.get(block.type)?.delete(block);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
block = Block.load(this, root);
|
|
730
|
+
}
|
|
252
731
|
}
|
|
253
732
|
block.index = i;
|
|
254
733
|
block.parent = null;
|
|
@@ -258,14 +737,67 @@ export class Nabu {
|
|
|
258
737
|
|
|
259
738
|
/**
|
|
260
739
|
* Dispatch an action to all registered handlers for the given topic.
|
|
740
|
+
* Re-syncs the model selection from the DOM first: `selectionchange` is async, so right after a
|
|
741
|
+
* keyboard-only selection change (Shift+Arrow, Home/End, Ctrl+A) the model would be stale.
|
|
261
742
|
* @param {string} topic
|
|
262
743
|
* @param {any} [data]
|
|
263
744
|
* @returns {Promise<import('@aionbuilders/pulse').PulseEvent>}
|
|
745
|
+
* @public
|
|
264
746
|
*/
|
|
265
747
|
exec(topic, data) {
|
|
748
|
+
this.selection.sync();
|
|
266
749
|
return this.#pulse.emit(topic, data);
|
|
267
750
|
}
|
|
268
751
|
|
|
752
|
+
/**
|
|
753
|
+
* The command waiting for the user's confirmation (ADR 017 §3.4), reactive; `null` when none:
|
|
754
|
+
* `{ id, strategy: 'hold' | 'invite' | 'choose', label, display, message, target?, progress, options?, selectedIndex }`.
|
|
755
|
+
* `progress` (hold, 0 → 1) and `selectedIndex` (choose) are reactive fields of that object.
|
|
756
|
+
* @returns {import('../utils/command-confirm.svelte.js').PendingCommand | null}
|
|
757
|
+
* @public
|
|
758
|
+
*/
|
|
759
|
+
get pendingCommand() { return this.commandConfirm.pending; }
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Cancel the pending confirmation, if any: nothing runs.
|
|
763
|
+
* @public
|
|
764
|
+
*/
|
|
765
|
+
cancelPendingCommand() { this.commandConfirm.cancel('api'); }
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* The pending confirmation when it is ABOUT `target` (what `confirm.target(ctx)` returned: usually a block), else `null`.
|
|
769
|
+
* Reactive: a block that draws its own hold progress reads `nabu.pendingCommandOn(block)?.progress`.
|
|
770
|
+
* @param {any} target
|
|
771
|
+
* @returns {import('../utils/command-confirm.svelte.js').PendingCommand | null}
|
|
772
|
+
* @public
|
|
773
|
+
*/
|
|
774
|
+
pendingCommandOn(target) { return this.commandConfirm.pendingOn(target); }
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Text of the polite live region of the editor (prompts and outcomes of confirmations). Reactive.
|
|
778
|
+
* @returns {string}
|
|
779
|
+
* @public
|
|
780
|
+
*/
|
|
781
|
+
get commandAnnouncement() { return this.commandConfirm.announcement; }
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Register commands (ADR 017): the registry keeps them and resolves their keys; each one is also an action of the bus.
|
|
785
|
+
* @param {string} owner extension name
|
|
786
|
+
* @param {Record<string, import('../utils/commands.js').CommandDef>} commands
|
|
787
|
+
*/
|
|
788
|
+
#registerCommands(owner, commands) {
|
|
789
|
+
for (const [id, def] of Object.entries(commands)) {
|
|
790
|
+
const entry = this.commands.register(id, def, owner);
|
|
791
|
+
if (entry) this.#pulse.on(id, ({ event }) => (this.#readonly ? undefined : this.commands.invoke(entry, event.data)));
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Run the `hookName` hooks of every extension, in order, until one returns `BREAK`. Each is called as `hook(nabu, ...args)`.
|
|
797
|
+
* @param {string} hookName
|
|
798
|
+
* @param {...any} args
|
|
799
|
+
* @public
|
|
800
|
+
*/
|
|
269
801
|
trigger(hookName, ...args) {
|
|
270
802
|
const hooks = this.hooks.get(hookName) || [];
|
|
271
803
|
for (const hook of hooks) {
|
|
@@ -278,35 +810,349 @@ export class Nabu {
|
|
|
278
810
|
}
|
|
279
811
|
|
|
280
812
|
|
|
281
|
-
|
|
813
|
+
/**
|
|
814
|
+
* Commit the pending changes as one Loro transaction.
|
|
815
|
+
* @param {{ origin?: string }} [options] `origin` tags the transaction; an origin starting with `nabu:silent` is
|
|
816
|
+
* not recorded as an undo step (background completions that must not be undone on their own).
|
|
817
|
+
* @public
|
|
818
|
+
*/
|
|
819
|
+
async commit({ origin } = {}) {
|
|
820
|
+
this.#evictChildrenOfLeaves();
|
|
282
821
|
this.trigger("onBeforeTransaction", this);
|
|
283
|
-
|
|
822
|
+
// Structural operations (split, merge, delete/move of blocks, type change, list indent…)
|
|
823
|
+
// are their own undo step, and so is the typing that follows (see #hasPendingStructuralOps).
|
|
824
|
+
// Skipped when an isolation is already armed for this very commit (paste, cut).
|
|
825
|
+
let continuation = false;
|
|
826
|
+
const stepsBefore = this.#isolatedSteps;
|
|
827
|
+
if (!(this.#isolating && this.#isolatedSteps === 2) && this.#hasPendingStructuralOps()) {
|
|
828
|
+
if (this.#structuralBurst) {
|
|
829
|
+
// A second structural commit in the same synchronous turn is the same user
|
|
830
|
+
// operation (e.g. a list indent = create the sublist via nabu.insert(), which
|
|
831
|
+
// commits, then move the item): let it merge into the step just pushed.
|
|
832
|
+
continuation = true;
|
|
833
|
+
this.undoManager.setMergeInterval(this.#mergeInterval);
|
|
834
|
+
} else {
|
|
835
|
+
this.#structuralBurst = true;
|
|
836
|
+
queueMicrotask(() => { this.#structuralBurst = false; });
|
|
837
|
+
this.#isolateNextCommits();
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
this.#busy++; // until the render: the DOM lags the model, no selection capture meanwhile (see captureUndoSelection)
|
|
841
|
+
try {
|
|
842
|
+
this.doc.commit(typeof origin === 'string' ? { origin } : undefined);
|
|
843
|
+
} catch (err) {
|
|
844
|
+
this.#busy--;
|
|
845
|
+
throw err;
|
|
846
|
+
}
|
|
847
|
+
if (continuation && this.#isolating) {
|
|
848
|
+
// The merge above must not leak: the typing after the operation stays isolated
|
|
849
|
+
// (a merged commit may still call onPush, so don't count it as a pushed step).
|
|
850
|
+
this.#isolatedSteps = stepsBefore;
|
|
851
|
+
this.undoManager.setMergeInterval(0);
|
|
852
|
+
}
|
|
853
|
+
if (this.#isolating && this.#isolatedSteps === 0) {
|
|
854
|
+
this.#isolating = false;
|
|
855
|
+
this.undoManager.setMergeInterval(this.#mergeInterval);
|
|
856
|
+
}
|
|
284
857
|
await tick();
|
|
858
|
+
this.#busy--;
|
|
859
|
+
// Rendered: the selection is where the action left it (the caller may still move it, which is captured again).
|
|
860
|
+
this.captureUndoSelection('settle');
|
|
285
861
|
}
|
|
286
862
|
|
|
287
863
|
/**
|
|
288
|
-
*
|
|
864
|
+
* Generic schema rule: a block whose class cannot hold children (anything that is not a MegaBlock)
|
|
865
|
+
* never keeps child nodes. When the pending transaction retypes a node into such a block (transform,
|
|
866
|
+
* markdown shortcut, `data.set('type')`) or moves / creates a node under one, its children are moved
|
|
867
|
+
* out to right after it, in order, in the same transaction: nothing is lost, and the (type-specific)
|
|
868
|
+
* `onBeforeTransaction` normalizers then reshape the result. Knows no concrete block type.
|
|
289
869
|
*/
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
870
|
+
#evictChildrenOfLeaves() {
|
|
871
|
+
const pending = this.doc.getUncommittedOpsAsJson();
|
|
872
|
+
if (!pending) return;
|
|
873
|
+
const treeId = this.tree.id;
|
|
874
|
+
/** @type {Set<string>} */
|
|
875
|
+
const candidates = new Set();
|
|
876
|
+
for (const change of pending.changes) {
|
|
877
|
+
for (const op of change.ops) {
|
|
878
|
+
const content = /** @type {any} */ (op.content);
|
|
879
|
+
if (op.container === treeId) {
|
|
880
|
+
if ((content.type === 'move' || content.type === 'create') && content.parent) candidates.add(String(content.parent));
|
|
881
|
+
} else if (content.type === 'insert' && content.key === 'type' && op.container.endsWith(':Map')) {
|
|
882
|
+
candidates.add(op.container.slice(4, -4));
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
for (const id of candidates) {
|
|
887
|
+
if (!this.tree.has(/** @type {any} */ (id))) continue;
|
|
888
|
+
const node = /** @type {NabuNode | undefined} */ (this.tree.getNodeByID(/** @type {any} */ (id)));
|
|
889
|
+
if (!node || node.isDeleted()) continue;
|
|
890
|
+
const BlockClass = this.registry.get(/** @type {any} */ (node.data.get('type')));
|
|
891
|
+
if (!BlockClass || BlockClass === MegaBlock || BlockClass.prototype instanceof MegaBlock) continue;
|
|
892
|
+
/** @type {NabuNode} */
|
|
893
|
+
let anchor = node;
|
|
894
|
+
for (const child of /** @type {NabuNode[]} */ (node.children() ?? [])) {
|
|
895
|
+
child.moveAfter(anchor);
|
|
896
|
+
anchor = child;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Whether the pending (uncommitted) Loro transaction changes the document structure:
|
|
903
|
+
* a tree create / move / delete (every block creation, destruction, re-parenting or
|
|
904
|
+
* reordering — split, merge, multi-block deletion, list indent…) or a change of a
|
|
905
|
+
* block's `type` (transforms, markdown shortcuts).
|
|
906
|
+
*
|
|
907
|
+
* This is the one central choke point: whatever the call site (tree.createNode,
|
|
908
|
+
* node.move, destroy, adoptChildren, data.set('type')…), the ops end up in the
|
|
909
|
+
* pending transaction that commit() is about to flush, so nothing has to be marked
|
|
910
|
+
* at the ~46 mutation sites.
|
|
911
|
+
* @returns {boolean}
|
|
912
|
+
*/
|
|
913
|
+
#hasPendingStructuralOps() {
|
|
914
|
+
const pending = this.doc.getUncommittedOpsAsJson();
|
|
915
|
+
if (!pending) return false;
|
|
916
|
+
const treeId = this.tree.id;
|
|
917
|
+
for (const change of pending.changes) {
|
|
918
|
+
for (const op of change.ops) {
|
|
919
|
+
const content = /** @type {any} */ (op.content);
|
|
920
|
+
if (op.container === treeId) {
|
|
921
|
+
if (content.type === 'create' || content.type === 'move' || content.type === 'delete') return true;
|
|
922
|
+
} else if (content.type === 'insert' && content.key === 'type' && op.container.endsWith(':Map')) {
|
|
923
|
+
// `type` set on a block's data map ("cid:<nodeId>:Map"), not e.g. a file asset's MIME type.
|
|
924
|
+
if (this.blocks.has(op.container.slice(4, -4))) return true;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
293
927
|
}
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Make the next commit (a paste, a cut, a structural op) AND the one after it their own undo steps:
|
|
933
|
+
* merging is off until both pushed a step (empty commits don't count), then
|
|
934
|
+
* the configured interval is restored at the end of commit().
|
|
935
|
+
*/
|
|
936
|
+
#isolateNextCommits() {
|
|
937
|
+
this.undoManager.setMergeInterval(0);
|
|
938
|
+
this.#isolating = true;
|
|
939
|
+
this.#isolatedSteps = 2;
|
|
294
940
|
}
|
|
295
941
|
|
|
296
942
|
/**
|
|
297
|
-
*
|
|
943
|
+
* Make the NEXT commit its own undo step (and the typing right after it another one), even though it
|
|
944
|
+
* holds no structural op: for a non-structural change that must undo on its own, e.g. a flag toggled
|
|
945
|
+
* from the keyboard, which would otherwise merge with the typing around it. Call it just before commit().
|
|
946
|
+
* @public
|
|
947
|
+
*/
|
|
948
|
+
isolateUndoStep() {
|
|
949
|
+
this.#isolateNextCommits();
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Run Loro mutations as a single transaction, then optionally restore the cursor.
|
|
954
|
+
* Centralizes the "mutate → commit → setCursor" dance used by most actions.
|
|
955
|
+
* @param {() => void} mutateFn - Mutations Loro ici. Ne PAS appeler commit() dedans.
|
|
956
|
+
* @param {{ block: Block, offset: number } | null} [cursorIntent]
|
|
957
|
+
* @returns {Promise<void>}
|
|
958
|
+
* @public
|
|
959
|
+
*/
|
|
960
|
+
async transact(mutateFn, cursorIntent = null) {
|
|
961
|
+
mutateFn();
|
|
962
|
+
await this.commit();
|
|
963
|
+
if (cursorIntent) {
|
|
964
|
+
this.selection.setCursor(cursorIntent.block, cursorIntent.offset);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Apply a markdown BLOCK shortcut (`# `, `- `, `> `, `--- `…) so that undo gives back exactly what
|
|
970
|
+
* the user typed, trigger included: one Ctrl+Z after `# ` leaves a paragraph "# " with the caret
|
|
971
|
+
* after the space; a second one removes the typing as usual.
|
|
972
|
+
*
|
|
973
|
+
* 1. `trigger` (the swallowed space) is inserted at the caret and committed like normal typing;
|
|
974
|
+
* 2. `transform` runs (delete the prefix incl. the trigger, change/replace the block…) and is
|
|
975
|
+
* committed as its own structural undo step (see commit()), whose stored caret is right
|
|
976
|
+
* after the trigger.
|
|
977
|
+
* Both commits run in the same synchronous turn, so the intermediate "# " is never painted.
|
|
978
|
+
*
|
|
979
|
+
* For a trigger that is not text (``` + Enter), pass `trigger = ''`: nothing is inserted and
|
|
980
|
+
* undo restores the text typed before the key (the fence line, without the Enter).
|
|
981
|
+
* @param {Block} block the block the shortcut was typed in
|
|
982
|
+
* @param {string} trigger text of the trigger key, inserted before transforming ('' = none)
|
|
983
|
+
* @param {(behavior: any) => void} transform mutations only (it may commit itself, e.g. via transformTo)
|
|
984
|
+
* @returns {Promise<void>} resolves immediately, doing nothing, when `block.transformsEnabled === false`
|
|
985
|
+
* @public
|
|
986
|
+
*/
|
|
987
|
+
async shortcut(block, trigger, transform) {
|
|
988
|
+
// Defence in depth: a block that opts out of transforms (`transformsEnabled === false`) never
|
|
989
|
+
// converts. The primary guard is upstream (dispatchEventToSelection skips the extension hooks
|
|
990
|
+
// for typing in such a block, so the keystroke proceeds as plain text); this covers direct callers.
|
|
991
|
+
if (block.transformsEnabled === false) return;
|
|
992
|
+
const behavior = block.behaviors.get('text');
|
|
993
|
+
const sel = behavior?.selection;
|
|
994
|
+
if (!behavior || !sel) return;
|
|
995
|
+
const at = sel.from;
|
|
996
|
+
if (trigger) {
|
|
997
|
+
behavior.insert(at, trigger);
|
|
998
|
+
this.commit();
|
|
999
|
+
}
|
|
1000
|
+
this.#undoCursor = { block, offset: at + trigger.length };
|
|
1001
|
+
transform(behavior);
|
|
1002
|
+
const committed = this.commit(); // pushes the undo step synchronously (the await is only a tick)
|
|
1003
|
+
this.#undoCursor = null;
|
|
1004
|
+
await committed;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* True when every selected text run carries the given mark.
|
|
1009
|
+
* Reactive: reads block.selected and the behaviors' selections/deltas,
|
|
1010
|
+
* so it can be used directly in component templates (e.g. FloatingToolbar).
|
|
1011
|
+
* @param {string} markName
|
|
1012
|
+
* @returns {boolean}
|
|
1013
|
+
* @public
|
|
1014
|
+
*/
|
|
1015
|
+
isMarkActive(markName) {
|
|
1016
|
+
let found = false;
|
|
1017
|
+
for (const [, block] of this.blocks) {
|
|
1018
|
+
if (!block.selected) continue;
|
|
1019
|
+
const behavior = block.behaviors?.get('text');
|
|
1020
|
+
if (!behavior || typeof behavior.isMarkActive !== 'function') continue;
|
|
1021
|
+
const sel = behavior.selection;
|
|
1022
|
+
if (!sel || sel.isCollapsed) continue;
|
|
1023
|
+
found = true;
|
|
1024
|
+
if (!behavior.isMarkActive(markName, sel)) return false;
|
|
1025
|
+
}
|
|
1026
|
+
return found;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Import changes made ELSEWHERE (another tab, a peer, a stored copy of the document: ADR 010 multi-tab sync). They are the
|
|
1031
|
+
* document's own history, not the user's actions: Loro's UndoManager records local commits only, so an import is never an undo
|
|
1032
|
+
* step (undoing the user's own edits afterwards still works, Loro transforms them). The DOM follows through the normal Loro
|
|
1033
|
+
* events. The caret of the local user stays on the same CHARACTER: it is captured as Loro cursors before the import and put
|
|
1034
|
+
* back after the render (a text node rewritten by Svelte would otherwise send it to the start of the block); the page is
|
|
1035
|
+
* never scrolled for it. Idempotent (importing what the document already has changes nothing).
|
|
1036
|
+
* Called DURING an IME composition it is applied at once (not held): the model is safe, because the composition anchor is a Loro
|
|
1037
|
+
* cursor that follows the edit, and the caret restore is skipped meanwhile (the browser owns it). (`persistence/sync.js` still
|
|
1038
|
+
* holds the updates it receives while composing, which keeps the composing text node untouched by the render.)
|
|
1039
|
+
* @param {Uint8Array} bytes a Loro snapshot or update
|
|
1040
|
+
* @returns {import('loro-crdt').ImportStatus}
|
|
1041
|
+
* @public
|
|
1042
|
+
*/
|
|
1043
|
+
importRemote(bytes) {
|
|
1044
|
+
const keep = !this.#composing && this.#busy === 0 && this.doc.getPendingTxnLength() === 0 ? captureSelection(this) : null;
|
|
1045
|
+
const status = this.doc.import(bytes);
|
|
1046
|
+
if (keep) restoreSelection(this, keep, 0, false);
|
|
1047
|
+
return status;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Undo the last operation. The selection as it was before that operation comes back (see ADR 015).
|
|
1052
|
+
* @public
|
|
1053
|
+
*/
|
|
1054
|
+
undo() {
|
|
1055
|
+
if (this.undoManager.canUndo()) this.#whileRendering(() => this.undoManager.undo());
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* Redo the last undone operation. The selection comes back where that operation ended.
|
|
1060
|
+
* @public
|
|
298
1061
|
*/
|
|
299
1062
|
redo() {
|
|
300
|
-
if (this.undoManager.canRedo())
|
|
301
|
-
|
|
1063
|
+
if (this.undoManager.canRedo()) this.#whileRendering(() => this.undoManager.redo());
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* Run `fn` (an undo / redo, whose render is asynchronous) with the selection capture off until it is rendered.
|
|
1068
|
+
* @param {() => void} fn
|
|
1069
|
+
*/
|
|
1070
|
+
#whileRendering(fn) {
|
|
1071
|
+
this.#busy++;
|
|
1072
|
+
this.#undoing++;
|
|
1073
|
+
try { fn(); } finally { tick().then(() => { this.#busy--; this.#undoing--; }); }
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* The text of `block` just changed (a Loro event of its text container: local, programmatic or imported). When a selection end
|
|
1079
|
+
* is in that block and the change is NOT the user's own typing (the handlers place their caret themselves), the selection is
|
|
1080
|
+
* put back on the characters it was on once the render is done: Svelte rewrites the edited text node, which would send the end
|
|
1081
|
+
* of the DOM range to offset 0 of it (P-109). The ends are the Loro cursors of the last selection captured while the model and
|
|
1082
|
+
* the DOM agreed (`#undoSel`), so an insertion before them shifts them. O(1) when the block holds no selection end. Skipped
|
|
1083
|
+
* during a composition and an undo / redo (which restore the selection themselves), and when the editor has placed the selection
|
|
1084
|
+
* since that capture (an input handler puts its own caret after the render: it is the one that knows where the caret goes, and
|
|
1085
|
+
* what it placed is captured again, `captureUndoSelection('settle')`).
|
|
1086
|
+
* @param {Block} block
|
|
1087
|
+
*/
|
|
1088
|
+
noteTextChange(block) {
|
|
1089
|
+
const snap = this.#undoSel;
|
|
1090
|
+
if (!snap || this.#keepPending || this.#composing || this.#undoing > 0) return;
|
|
1091
|
+
if (snap.anchor.blockId !== block.id && snap.focus.blockId !== block.id) return;
|
|
1092
|
+
const placed = this.#undoSelPlacements;
|
|
1093
|
+
if (this.selection.placements !== placed) return;
|
|
1094
|
+
this.#keepPending = true;
|
|
1095
|
+
tick().then(() => {
|
|
1096
|
+
this.#keepPending = false;
|
|
1097
|
+
if (this.#composing || this.#undoing > 0 || this.selection.placements !== placed) return;
|
|
1098
|
+
keepSelection(this, snap);
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* Remember the live selection as the one an undo step pushed from now on gives back (ADR 015). Called wherever the selection
|
|
1104
|
+
* changes or an input starts (selection change, key down, programmatic caret placement), always while the model and the DOM
|
|
1105
|
+
* agree: it does nothing during a composition, while a commit / undo is rendering, and while a transaction is pending (the
|
|
1106
|
+
* Loro cursors have to bind to the text as it was BEFORE the change).
|
|
1107
|
+
* @param {'user' | 'settle'} [source] 'settle' = the editor itself placed the selection after an action: it is where that
|
|
1108
|
+
* action ended (what a redo gives back). 'user' = the user moved it.
|
|
1109
|
+
*/
|
|
1110
|
+
captureUndoSelection(source = 'user') {
|
|
1111
|
+
if (this.#composing || this.#busy > 0 || this.doc.getPendingTxnLength() > 0) return;
|
|
1112
|
+
const snap = captureSelection(this);
|
|
1113
|
+
if (!snap) return;
|
|
1114
|
+
this.#undoSel = snap;
|
|
1115
|
+
this.#undoSelPlacements = this.selection.placements ?? 0;
|
|
1116
|
+
if (source === 'settle' && this.#endKey !== null) {
|
|
1117
|
+
this.#actionEnds.set(this.#endKey, snap);
|
|
1118
|
+
if (this.#actionEnds.size > 200) this.#actionEnds.delete(/** @type {number} */ (this.#actionEnds.keys().next().value));
|
|
302
1119
|
}
|
|
303
1120
|
}
|
|
304
1121
|
|
|
1122
|
+
/** A pointer interaction starts: the selection that follows is the user's, no longer where the last action ended. */
|
|
1123
|
+
sealUndoEnd() { this.#endKey = null; }
|
|
1124
|
+
|
|
1125
|
+
/** Clear the pending stored marks. */
|
|
1126
|
+
clearStoredMarks() { this.storedMarks = null; }
|
|
305
1127
|
|
|
1128
|
+
/**
|
|
1129
|
+
* Toggle a stored mark for the next typed char (Ctrl+B etc. at a collapsed cursor).
|
|
1130
|
+
* @param {string} name
|
|
1131
|
+
*/
|
|
1132
|
+
toggleStoredMark(name) {
|
|
1133
|
+
const anchor = this.selection.anchorBlock;
|
|
1134
|
+
const beh = anchor?.behaviors?.get('text');
|
|
1135
|
+
const sel = beh?.selection;
|
|
1136
|
+
if (!beh || !sel) return;
|
|
1137
|
+
let active;
|
|
1138
|
+
if (this.storedMarks && name in this.storedMarks) active = this.storedMarks[name];
|
|
1139
|
+
else active = inheritedMarkAt(beh, sel.from, name);
|
|
1140
|
+
this.storedMarks = { ...(this.storedMarks || {}), [name]: !active };
|
|
1141
|
+
}
|
|
306
1142
|
|
|
307
|
-
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* Place the DOM + model selection. Asynchronous by nature: it waits for Svelte to flush pending state
|
|
1147
|
+
* (`tick()`), because the target blocks' DOM may not be rendered yet (e.g. right after a commit/insert).
|
|
1148
|
+
* The returned promise resolves once the selection has been set, i.e. once `nabu.selection` reflects it:
|
|
1149
|
+
* `await nabu.focus(...)` before `exec(...)` / typing. Fire-and-forget callers are unaffected.
|
|
1150
|
+
* @param {{from?: {offset?: number, block?: Block}, to?: {offset?: number, block?: Block}, offset?: number}} [options]
|
|
1151
|
+
* @returns {Promise<void>}
|
|
1152
|
+
* @public
|
|
1153
|
+
*/
|
|
308
1154
|
focus(options) {
|
|
309
|
-
tick().then(() => {
|
|
1155
|
+
return tick().then(() => {
|
|
310
1156
|
const sel = this.selection;
|
|
311
1157
|
|
|
312
1158
|
const {offset: fromOffset, block: fromBlock} = options?.from?.block ?
|
|
@@ -317,25 +1163,98 @@ export class Nabu {
|
|
|
317
1163
|
{offset: options?.to?.offset ?? sel.endOffset ?? 0, block: options?.to?.block} :
|
|
318
1164
|
this.resolveDocumentOffset(options?.offset ?? options?.to?.offset ?? sel.endOffset ?? 0) || {offset: sel.endOffset ?? 0, block: sel.focusBlock};
|
|
319
1165
|
|
|
320
|
-
|
|
1166
|
+
this.warn('Focusing from', fromBlock, 'offset', fromOffset, 'to', toBlock, 'offset', toOffset);
|
|
321
1167
|
|
|
322
1168
|
if (fromBlock && toBlock) {
|
|
323
1169
|
const fromPoint = fromBlock.getDOMPoint(fromOffset);
|
|
324
1170
|
const toPoint = toBlock.getDOMPoint(toOffset);
|
|
325
|
-
|
|
1171
|
+
this.warn('Resolved DOM points:', fromPoint, toPoint);
|
|
326
1172
|
if (fromPoint && toPoint) this.selection.setBaseAndExtent(fromPoint.node, fromPoint.offset, toPoint.node, toPoint.offset);
|
|
327
1173
|
}
|
|
328
|
-
})
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
329
1176
|
|
|
1177
|
+
/**
|
|
1178
|
+
* The deepest last block of the document that can hold a caret in the rendered document: follows
|
|
1179
|
+
* the last child at each level, but never enters a block that hides its children.
|
|
1180
|
+
* @returns {Block | null}
|
|
1181
|
+
* @public
|
|
1182
|
+
*/
|
|
1183
|
+
get lastVisibleBlock() {
|
|
1184
|
+
/** @type {any} */
|
|
1185
|
+
let block = this.children[this.children.length - 1] ?? null;
|
|
1186
|
+
while (block) {
|
|
1187
|
+
/** @type {Block[] | undefined} */
|
|
1188
|
+
const kids = block.children;
|
|
1189
|
+
if (!kids?.length || block.hidesChildren) break;
|
|
1190
|
+
block = kids[kids.length - 1];
|
|
1191
|
+
}
|
|
1192
|
+
return block;
|
|
330
1193
|
}
|
|
331
1194
|
|
|
1195
|
+
#openingTrailingCaret = false;
|
|
1196
|
+
|
|
332
1197
|
/**
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
1198
|
+
* The document must always offer a caret after its last block. Call it on user intent (ArrowDown /
|
|
1199
|
+
* ArrowRight leaving the document, a click below the last block): when the last block holds text, the
|
|
1200
|
+
* caret goes to its end; when it does not (a void block such as a divider / image, or a container
|
|
1201
|
+
* whose end is not a text position), an empty default text block is appended at the root, in one
|
|
1202
|
+
* undo step, and takes the caret. Never called eagerly on load.
|
|
1203
|
+
* @returns {Promise<Block | null>} The block now holding the caret
|
|
1204
|
+
* @public
|
|
1205
|
+
*/
|
|
1206
|
+
async openTrailingCaret() {
|
|
1207
|
+
if (this.#openingTrailingCaret) return null;
|
|
1208
|
+
const last = this.lastVisibleBlock;
|
|
1209
|
+
if (!last) return null;
|
|
1210
|
+
this.#openingTrailingCaret = true;
|
|
1211
|
+
try {
|
|
1212
|
+
/** @type {Block | null | undefined} */
|
|
1213
|
+
let target = last;
|
|
1214
|
+
let offset = last.behaviors?.get('text')?.text?.length ?? 0;
|
|
1215
|
+
if (!last.behaviors?.has('text')) {
|
|
1216
|
+
const type = this.defaultBlockType;
|
|
1217
|
+
if (!type || !this.registry.has(type)) return null;
|
|
1218
|
+
const created = this.insert(type, {}, null, this.children.length);
|
|
1219
|
+
await this.commit();
|
|
1220
|
+
target = this.blocks.get(created.id);
|
|
1221
|
+
offset = 0;
|
|
1222
|
+
}
|
|
1223
|
+
if (!target) return null;
|
|
1224
|
+
await tick();
|
|
1225
|
+
this.selection.setCursor(target, offset);
|
|
1226
|
+
return target;
|
|
1227
|
+
} finally {
|
|
1228
|
+
this.#openingTrailingCaret = false;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* Mouse down on the editor itself (not on a block): below the last block, that block is a void →
|
|
1234
|
+
* put a caret after it (see `openTrailingCaret`).
|
|
1235
|
+
* @param {MouseEvent} e
|
|
1236
|
+
*/
|
|
1237
|
+
handleMousedown(e) {
|
|
1238
|
+
this.rearmTab();
|
|
1239
|
+
if (this.#readonly) return;
|
|
1240
|
+
if (e.button !== 0 || e.defaultPrevented || e.target !== e.currentTarget) return;
|
|
1241
|
+
const last = this.lastVisibleBlock;
|
|
1242
|
+
const lastEl = /** @type {HTMLElement | null} */ (last?.element);
|
|
1243
|
+
if (!last || last.behaviors?.has('text') || !lastEl?.isConnected) return;
|
|
1244
|
+
if (e.clientY <= lastEl.getBoundingClientRect().bottom) return;
|
|
1245
|
+
this.openTrailingCaret(); // overrides the native caret the click leaves on the root
|
|
1246
|
+
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* Insert a new block of a registered type and commit (throws when the type is not registered).
|
|
1251
|
+
* @param {string} type - Block type (`'paragraph'`, or the name of an extension that declares a `block`)
|
|
1252
|
+
* @param {Record<string, any>} [props] - Initial props, read by the class's `static create` (`text`, `delta`...)
|
|
1253
|
+
* @param {string | null} [parentId] - Id of the parent block (`null`: the document root)
|
|
1254
|
+
* @param {number | null} [index] - Position among the siblings (`null`: last)
|
|
1255
|
+
* @returns {Block} The created block
|
|
1256
|
+
* @public
|
|
1257
|
+
*/
|
|
339
1258
|
insert(type, props = {}, parentId = null, index = null) {
|
|
340
1259
|
|
|
341
1260
|
const BlockClass = this.registry.get(type);
|
|
@@ -352,7 +1271,11 @@ export class Nabu {
|
|
|
352
1271
|
|
|
353
1272
|
|
|
354
1273
|
|
|
355
|
-
/**
|
|
1274
|
+
/**
|
|
1275
|
+
* Delete a block (and its children) from the tree. No commit: call `commit()` afterwards.
|
|
1276
|
+
* @param {Block} block
|
|
1277
|
+
* @public
|
|
1278
|
+
*/
|
|
356
1279
|
delete(block) {
|
|
357
1280
|
this.deleteNode(block.node.id);
|
|
358
1281
|
}
|
|
@@ -382,8 +1305,12 @@ export class Nabu {
|
|
|
382
1305
|
const sel = this.selection;
|
|
383
1306
|
if (!sel.anchorBlock || !sel.focusBlock) return;
|
|
384
1307
|
|
|
385
|
-
// 1. Essayer les hooks globaux d'extension d'abord
|
|
386
|
-
|
|
1308
|
+
// 1. Essayer les hooks globaux d'extension d'abord.
|
|
1309
|
+
// Un bloc `transformsEnabled === false` (code, callout, toggle…) ne se laisse pas transformer
|
|
1310
|
+
// par la frappe (raccourcis markdown `# `, `> `, ``` …) : on saute les hooks sur les insertions
|
|
1311
|
+
// (les hooks de suppression — sortie de bloc, garde-fous — tournent toujours) et la frappe
|
|
1312
|
+
// continue comme du texte normal. Même règle que TextBehavior.handleBeforeInput.
|
|
1313
|
+
if (hookName && !(hookName === 'onBeforeInput' && isTransformInput(e) && sel.anchorBlock.transformsEnabled === false)) {
|
|
387
1314
|
const hooks = this.hooks.get(hookName) || [];
|
|
388
1315
|
for (const hook of hooks) {
|
|
389
1316
|
const handled = hook(this, e, sel.anchorBlock);
|
|
@@ -415,27 +1342,265 @@ export class Nabu {
|
|
|
415
1342
|
|
|
416
1343
|
/** @param {InputEvent} e */
|
|
417
1344
|
handleBeforeinput(e) {
|
|
1345
|
+
if (this.#readonly) { e.preventDefault(); return; } // nothing is typed, deleted, pasted or dropped in a read-only editor
|
|
1346
|
+
this.selection.sync(); // selectionchange is async: don't act on a stale caret
|
|
1347
|
+
// Ne pas interférer avec la composition IME en cours : le navigateur
|
|
1348
|
+
// doit pouvoir muter librement le text node (insertCompositionText
|
|
1349
|
+
// n'est de toute façon pas annulable). Sync dans Loro à compositionend.
|
|
1350
|
+
if (this.#composing && (e.inputType === 'insertCompositionText' || e.inputType === 'deleteCompositionText')) {
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
// Any other input while a composition runs (a real Enter that the IME did not swallow, a paste, a delete…): the model
|
|
1354
|
+
// does not hold the composing text yet, so acting on it would use a stale offset (P-102). It is ignored; the composition
|
|
1355
|
+
// goes on and its commit (compositionend) follows. Never throws, `composing` is only ever reset by compositionend.
|
|
1356
|
+
if (this.#composing) {
|
|
1357
|
+
e.preventDefault();
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
this.selection.normalize(); // a caret on a dead position (void block, wrapper…) must not swallow the keystroke
|
|
418
1361
|
e.preventDefault(); // Toujours bloquer les mutations natives
|
|
419
1362
|
this.dispatchEventToSelection('beforeinput', e, 'onBeforeInput');
|
|
420
1363
|
}
|
|
421
1364
|
|
|
1365
|
+
// ── IME composition (issue #6) ───────────────────────────────────────────
|
|
1366
|
+
|
|
1367
|
+
/**
|
|
1368
|
+
* Capture the model position at the start of an IME composition and
|
|
1369
|
+
* switch to DOM-first mode for its duration.
|
|
1370
|
+
* @param {CompositionEvent} e
|
|
1371
|
+
*/
|
|
1372
|
+
handleCompositionStart(e) {
|
|
1373
|
+
if (this.#readonly) return;
|
|
1374
|
+
this.selection.sync();
|
|
1375
|
+
// A second compositionstart in the SAME block while one runs (Chrome silently restarts a composition when a script
|
|
1376
|
+
// rewrites its text node, e.g. a programmatic edit of the block: no compositionend in between): the first start is the
|
|
1377
|
+
// one that counts, its Loro-cursor anchor already follows the edit.
|
|
1378
|
+
if (this.#composing && this.#compositionStartBlock && this.#compositionStartBlock === this.selection.anchorBlock) return;
|
|
1379
|
+
// A composition over a selection replaces it (P-98 / P-99): the range is deleted through the MODEL first, rendered, and the
|
|
1380
|
+
// caret put at the junction, BEFORE the browser starts mutating the DOM (it would otherwise merge the blocks natively and
|
|
1381
|
+
// leave the model untouched). The deletion and the composed text are one undo step (see #compositionGroup).
|
|
1382
|
+
if (!this.selection.isCollapsed) this.#replaceSelectionForComposition();
|
|
1383
|
+
this.#composing = true;
|
|
1384
|
+
const anchor = this.selection.anchorBlock;
|
|
1385
|
+
if (!anchor) {
|
|
1386
|
+
this.#compositionStartBlock = null;
|
|
1387
|
+
this.#compositionStartOffset = null;
|
|
1388
|
+
this.#compositionAnchor = null;
|
|
1389
|
+
this.#endCompositionGroup();
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
const behavior = anchor.behaviors?.get('text');
|
|
1393
|
+
const sel = behavior?.selection;
|
|
1394
|
+
this.#compositionStartBlock = anchor;
|
|
1395
|
+
this.#compositionStartOffset = sel?.from ?? 0;
|
|
1396
|
+
this.#compositionAnchor = behavior ? makeEndpoint(anchor, sel?.from ?? 0, 'end') : null;
|
|
1397
|
+
this.#composingBlock = anchor;
|
|
1398
|
+
/** @type {any} */ (behavior)?.snapshotForComposition?.();
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/**
|
|
1402
|
+
* Delete the selected range (one block or several, isolated fields honoured: exactly what typing a character over it does,
|
|
1403
|
+
* see {@link deleteRange}) and leave a collapsed caret at the junction, with the DOM rendered synchronously.
|
|
1404
|
+
* Undo: the deletion opens an undo group that the end of the composition closes, so "replace the selection with the composed
|
|
1405
|
+
* text" is ONE step; a composition canceled right away leaves the deletion as its own step.
|
|
1406
|
+
*/
|
|
1407
|
+
#replaceSelectionForComposition() {
|
|
1408
|
+
const range = selectionRange(this);
|
|
1409
|
+
if (!range) return;
|
|
1410
|
+
try { this.undoManager.groupStart(); this.#compositionGroup = true; } catch { this.#compositionGroup = false; }
|
|
1411
|
+
const junction = deleteRange(this, range);
|
|
1412
|
+
if (!junction) { this.#endCompositionGroup(); return; }
|
|
1413
|
+
this.commit(); // the Loro transaction (and its undo step) is made synchronously; the await is only the render
|
|
1414
|
+
flushSync(); // the DOM matches the model before the browser starts the composition
|
|
1415
|
+
const block = this.blocks.get(junction.block.id) ?? junction.block;
|
|
1416
|
+
this.selection.setCursor(block, junction.offset);
|
|
1417
|
+
this.selection.sync();
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
#endCompositionGroup() {
|
|
1421
|
+
if (!this.#compositionGroup) return;
|
|
1422
|
+
this.#compositionGroup = false;
|
|
1423
|
+
try { this.undoManager.groupEnd(); } catch { /* the group already ended (remote import) */ }
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
/**
|
|
1427
|
+
* No-op: the browser manages the DOM freely during composition.
|
|
1428
|
+
* @param {CompositionEvent} e
|
|
1429
|
+
*/
|
|
1430
|
+
handleCompositionUpdate(e) {}
|
|
1431
|
+
|
|
1432
|
+
/**
|
|
1433
|
+
* Sync the composed text into Loro. The browser already inserted `e.data`
|
|
1434
|
+
* into the DOM; committing the same text to the model lets the next render
|
|
1435
|
+
* converge without duplication.
|
|
1436
|
+
* @param {CompositionEvent} e
|
|
1437
|
+
*/
|
|
1438
|
+
handleCompositionEnd(e) {
|
|
1439
|
+
if (this.#readonly && !this.#composing) return;
|
|
1440
|
+
this.#composing = false;
|
|
1441
|
+
const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
|
|
1442
|
+
const composedBlock = this.#compositionStartBlock;
|
|
1443
|
+
this.#composingBlock = null;
|
|
1444
|
+
/** @type {any} */ (composedIn)?.restoreAfterComposition?.(e.data || ''); // before the model catches up: no duplicate of the composed text
|
|
1445
|
+
try {
|
|
1446
|
+
this.#syncComposition(e);
|
|
1447
|
+
} finally {
|
|
1448
|
+
this.#endCompositionGroup();
|
|
1449
|
+
}
|
|
1450
|
+
this.selection.normalize(); // a dead caret must not survive the composition
|
|
1451
|
+
// A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
|
|
1452
|
+
if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
|
|
1453
|
+
this.selection.setCursor(composedBlock, 0);
|
|
1454
|
+
tick().then(() => { if (!this.#composing && composedBlock.element?.isConnected && !composedIn?.text) this.selection.setCursor(composedBlock, 0); });
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/** @param {CompositionEvent} e */
|
|
1459
|
+
#syncComposition(e) {
|
|
1460
|
+
const block = this.#compositionStartBlock;
|
|
1461
|
+
let startOffset = this.#compositionStartOffset;
|
|
1462
|
+
const anchor = this.#compositionAnchor;
|
|
1463
|
+
this.#compositionStartBlock = null;
|
|
1464
|
+
this.#compositionStartOffset = null;
|
|
1465
|
+
this.#compositionAnchor = null;
|
|
1466
|
+
if (!block || startOffset === null) return;
|
|
1467
|
+
|
|
1468
|
+
// The block may have been destroyed/replaced during the composition
|
|
1469
|
+
// (e.g. the user clicked elsewhere and a transform happened).
|
|
1470
|
+
const fresh = this.blocks.get(block.id);
|
|
1471
|
+
if (!fresh || fresh !== block) return;
|
|
1472
|
+
// nabu.blocks can still hold a deleted block — check the Loro tree too.
|
|
1473
|
+
if (block.node.isDeleted?.() || !this.tree.has(block.node.id)) return;
|
|
1474
|
+
|
|
1475
|
+
const behavior = block.behaviors?.get('text');
|
|
1476
|
+
if (!behavior) return;
|
|
1477
|
+
|
|
1478
|
+
// Canceled composition (Escape) fires compositionend with e.data === ''.
|
|
1479
|
+
const composedText = e.data || '';
|
|
1480
|
+
if (!composedText) return;
|
|
1481
|
+
|
|
1482
|
+
// Where the composition began NOW: the Loro cursors followed every edit of this text made meanwhile (P-101).
|
|
1483
|
+
if (anchor) {
|
|
1484
|
+
const moved = resolveOffset(this.doc, anchor, behavior.container.length);
|
|
1485
|
+
if (moved !== null) startOffset = moved;
|
|
1486
|
+
}
|
|
1487
|
+
startOffset = Math.max(0, Math.min(startOffset, behavior.container.length));
|
|
1488
|
+
|
|
1489
|
+
behavior.insert(startOffset, composedText);
|
|
1490
|
+
block.commit();
|
|
1491
|
+
const caret = startOffset + composedText.length;
|
|
1492
|
+
tick().then(() => {
|
|
1493
|
+
this.selection.setCursor(block, caret);
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
|
|
422
1497
|
/** @param {KeyboardEvent} e */
|
|
423
1498
|
handleKeydown(e) {
|
|
424
|
-
//
|
|
425
|
-
if (
|
|
1499
|
+
// Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
|
|
1500
|
+
if (this.#readonly) return;
|
|
1501
|
+
this.selection.sync(); // no-op when the document capture listener already synced
|
|
1502
|
+
this.selection.normalize();
|
|
1503
|
+
// The Escape-then-Tab way out of the `tab` option (utils/tab.js): any key but a lone modifier closes it, whoever handles the key.
|
|
1504
|
+
const escaped = this.#tabEscaped;
|
|
1505
|
+
if (!isModifierKey(e)) this.#tabEscaped = false;
|
|
1506
|
+
// Commands first (ADR 017): undo / redo and every declared shortcut. What no command handles falls through to the
|
|
1507
|
+
// legacy `onKeyDown` hooks and the block's own keydown, then to the native behavior.
|
|
1508
|
+
if (this.commands.handleKeydown(e)) return;
|
|
1509
|
+
if (this.#selectAll(e) || this.#landOnIsolated(e) || this.#jumpToEdge(e)) return;
|
|
1510
|
+
|
|
1511
|
+
this.dispatchEventToSelection('keydown', e, 'onKeyDown');
|
|
1512
|
+
// Tab / Shift+Tab that no command, hook or block took: the `tab` option decides (structural meanings come first).
|
|
1513
|
+
if (handleTabKey(this, e, escaped)) return;
|
|
1514
|
+
// An Escape that nothing consumed (slash menu, chooser, pending command, a block…) opens the way out for the next Tab.
|
|
1515
|
+
if (e.key === 'Escape' && !e.defaultPrevented && !e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey) this.#tabEscaped = true;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* Ctrl / Cmd + A when the document holds ISOLATED text fields (`Block#isolatesSelection`, e.g. region titles). Inside one it
|
|
1520
|
+
* selects exactly that field's text (like an input); elsewhere it selects the text of the document from the first to the last
|
|
1521
|
+
* block that is not isolated (the isolated fields are left out of the selection, as of any range). A document without
|
|
1522
|
+
* isolated block keeps the browser's own Select All.
|
|
1523
|
+
* @param {KeyboardEvent} e
|
|
1524
|
+
* @returns {boolean} Whether the key was handled
|
|
1525
|
+
*/
|
|
1526
|
+
#selectAll(e) {
|
|
1527
|
+
if (!(e.ctrlKey || e.metaKey) || e.shiftKey || e.altKey || typeof e.key !== 'string' || e.key.toLowerCase() !== 'a') return false;
|
|
1528
|
+
if (e.isComposing || this.#composing) return false;
|
|
1529
|
+
const sel = this.selection;
|
|
1530
|
+
const inside = sel.anchorBlock;
|
|
1531
|
+
if (inside?.isolatesSelection && sel.focusBlock === inside) {
|
|
426
1532
|
e.preventDefault();
|
|
427
|
-
|
|
428
|
-
return;
|
|
1533
|
+
sel.selectBlockText(inside);
|
|
1534
|
+
return true;
|
|
429
1535
|
}
|
|
1536
|
+
const texts = textBlocksInOrder(this, { visible: true });
|
|
1537
|
+
if (!texts.some((b) => b.isolatesSelection)) return false;
|
|
1538
|
+
e.preventDefault();
|
|
1539
|
+
const plain = texts.filter((b) => !b.isolatesSelection && b.element);
|
|
1540
|
+
const first = plain[0];
|
|
1541
|
+
const last = plain.at(-1);
|
|
1542
|
+
if (first && last) sel.selectBetween(first, last);
|
|
1543
|
+
return true;
|
|
1544
|
+
}
|
|
430
1545
|
|
|
431
|
-
|
|
432
|
-
|
|
1546
|
+
/**
|
|
1547
|
+
* Ctrl / Cmd + End and Ctrl / Cmd + Home (with Shift: extend the selection) in a LARGE document (`LARGE_DOC` blocks, whose
|
|
1548
|
+
* off-screen parts the browser skips, see `blocks/chunks.js`). The browser moves the caret to the end of what it has laid out, and
|
|
1549
|
+
* a skipped part has none: it would stop short of the real end. The caret goes to the end of the last text block (the start of
|
|
1550
|
+
* the first) of the model instead, and the page scrolls to it. A smaller document keeps the browser's own key.
|
|
1551
|
+
* @param {KeyboardEvent} e
|
|
1552
|
+
* @returns {boolean} Whether the key was handled
|
|
1553
|
+
*/
|
|
1554
|
+
#jumpToEdge(e) {
|
|
1555
|
+
if (!(e.ctrlKey || e.metaKey) || e.altKey || (e.key !== 'End' && e.key !== 'Home')) return false;
|
|
1556
|
+
if (e.isComposing || this.#composing || this.blocks.size < LARGE_DOC) return false;
|
|
1557
|
+
const texts = textBlocksInOrder(this, { visible: true });
|
|
1558
|
+
const toEnd = e.key === 'End';
|
|
1559
|
+
const target = toEnd ? texts[texts.length - 1] : texts[0];
|
|
1560
|
+
const point = target?.element ? /** @type {any} */ (target).getDOMPoint?.(toEnd ? (target.behaviors?.get('text')?.text.length ?? 0) : 0) : null;
|
|
1561
|
+
if (!target || !point) return false;
|
|
1562
|
+
e.preventDefault();
|
|
1563
|
+
const live = typeof window !== 'undefined' ? window.getSelection() : null;
|
|
1564
|
+
const anchor = e.shiftKey && live?.anchorNode && this.selection.owns(live.anchorNode) ? { node: live.anchorNode, offset: live.anchorOffset } : point;
|
|
1565
|
+
this.selection.setBaseAndExtent(anchor.node, anchor.offset, point.node, point.offset);
|
|
1566
|
+
// The skipped parts above take their real height as they are shown: reveal again once the layout has settled.
|
|
1567
|
+
revealFocus(target);
|
|
1568
|
+
requestAnimationFrame(() => requestAnimationFrame(() => { if (target.element?.isConnected) revealFocus(target); }));
|
|
1569
|
+
return true;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* Arrow keys at the edge of an ISOLATED text field (`Block#isolatesSelection`): a field is entered at its START going down /
|
|
1574
|
+
* right and at its END going up / left, whatever the column the caret had, and ArrowDown / ArrowRight at the end of a field
|
|
1575
|
+
* goes to the start of the next text. Only a collapsed caret at the very end (down / right) or start (up / left) of its
|
|
1576
|
+
* block is concerned; anywhere else the browser moves the caret as usual.
|
|
1577
|
+
* @param {KeyboardEvent} e
|
|
1578
|
+
* @returns {boolean} Whether the key was handled
|
|
1579
|
+
*/
|
|
1580
|
+
#landOnIsolated(e) {
|
|
1581
|
+
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.isComposing || this.#composing) return false;
|
|
1582
|
+
const down = e.key === 'ArrowDown' || e.key === 'ArrowRight';
|
|
1583
|
+
if (!down && e.key !== 'ArrowUp' && e.key !== 'ArrowLeft') return false;
|
|
1584
|
+
const sel = this.selection;
|
|
1585
|
+
const block = sel.anchorBlock;
|
|
1586
|
+
const text = block?.behaviors?.get('text');
|
|
1587
|
+
const caret = block?.selection;
|
|
1588
|
+
if (!block || !text || !sel.isCollapsed || !caret || caret.from !== caret.to) return false;
|
|
1589
|
+
const hasText = (/** @type {Block} */ b) => !!b.behaviors?.has('text');
|
|
1590
|
+
if (down) {
|
|
1591
|
+
if (caret.to !== text.text.length) return false;
|
|
1592
|
+
const next = block.findForward(hasText);
|
|
1593
|
+
if (!next || !(next.isolatesSelection || block.isolatesSelection)) return false;
|
|
433
1594
|
e.preventDefault();
|
|
434
|
-
|
|
435
|
-
|
|
1595
|
+
sel.setCursor(next, 0);
|
|
1596
|
+
} else {
|
|
1597
|
+
if (caret.from !== 0) return false;
|
|
1598
|
+
const previous = block.findBackward(hasText);
|
|
1599
|
+
if (!previous?.isolatesSelection) return false;
|
|
1600
|
+
e.preventDefault();
|
|
1601
|
+
sel.setCursor(previous, previous.behaviors.get('text').text.length);
|
|
436
1602
|
}
|
|
437
|
-
|
|
438
|
-
this.dispatchEventToSelection('keydown', e, 'onKeyDown');
|
|
1603
|
+
return true;
|
|
439
1604
|
}
|
|
440
1605
|
|
|
441
1606
|
/** @param {InputEvent} e */
|
|
@@ -451,12 +1616,24 @@ export class Nabu {
|
|
|
451
1616
|
|
|
452
1617
|
/** @param {ClipboardEvent} e */
|
|
453
1618
|
handleCopy(e) {
|
|
1619
|
+
this.selection.sync();
|
|
454
1620
|
if (this.selection.isCollapsed) return;
|
|
455
1621
|
e.preventDefault();
|
|
1622
|
+
if (!e.clipboardData) return;
|
|
1623
|
+
this.#writeSelection(e.clipboardData);
|
|
1624
|
+
}
|
|
456
1625
|
|
|
1626
|
+
/**
|
|
1627
|
+
* Serialize the current (non-collapsed) selection into `dt`: `application/x-nabu+json` (the fragment, with the bytes of
|
|
1628
|
+
* the stored media), `text/plain` (raw text for one text block, markdown otherwise) and `text/html`. Shared by copy / cut
|
|
1629
|
+
* (the clipboard) and by the drag of a text selection.
|
|
1630
|
+
* @param {DataTransfer} dt
|
|
1631
|
+
* @returns {boolean} False when there is nothing to serialize
|
|
1632
|
+
*/
|
|
1633
|
+
#writeSelection(dt) {
|
|
457
1634
|
const startBlock = this.selection.startBlock;
|
|
458
1635
|
const endBlock = this.selection.endBlock;
|
|
459
|
-
if (!startBlock || !endBlock
|
|
1636
|
+
if (!startBlock || !endBlock) return false;
|
|
460
1637
|
|
|
461
1638
|
const startFrom = this.selection.start?.from ?? 0;
|
|
462
1639
|
const endTo = this.selection.end?.to ?? null;
|
|
@@ -478,10 +1655,10 @@ export class Nabu {
|
|
|
478
1655
|
} else {
|
|
479
1656
|
const startRoot = findDirectChildOf(startBlock, this);
|
|
480
1657
|
const endRoot = findDirectChildOf(endBlock, this);
|
|
481
|
-
if (!startRoot || !endRoot) return;
|
|
1658
|
+
if (!startRoot || !endRoot) return false;
|
|
482
1659
|
const si = this.children.indexOf(startRoot);
|
|
483
1660
|
const ei = this.children.indexOf(endRoot);
|
|
484
|
-
if (si === -1 || ei === -1) return;
|
|
1661
|
+
if (si === -1 || ei === -1) return false;
|
|
485
1662
|
rootBlocks = this.children.slice(si, ei + 1);
|
|
486
1663
|
}
|
|
487
1664
|
}
|
|
@@ -500,6 +1677,7 @@ export class Nabu {
|
|
|
500
1677
|
startFrom: isFirst ? startFrom : 0,
|
|
501
1678
|
endBlock: isLast ? endBlock : null,
|
|
502
1679
|
endTo: isLast ? endTo : null,
|
|
1680
|
+
textOnly: true, // a text selection: isolated fields (region titles) and their containers are not copied
|
|
503
1681
|
});
|
|
504
1682
|
}
|
|
505
1683
|
|
|
@@ -509,20 +1687,30 @@ export class Nabu {
|
|
|
509
1687
|
to: isLast ? endTo : null,
|
|
510
1688
|
partial: isFirst && isLast ? 'both' : isFirst ? 'start' : isLast ? 'end' : false,
|
|
511
1689
|
});
|
|
512
|
-
}).filter(Boolean);
|
|
1690
|
+
}).flat().filter(Boolean); // an isolating container returns its selected children directly (an array)
|
|
513
1691
|
|
|
514
|
-
if (!pasteBlocks.length) return;
|
|
1692
|
+
if (!pasteBlocks.length) return false;
|
|
515
1693
|
|
|
516
|
-
|
|
517
|
-
|
|
1694
|
+
// Media stored in the document (`nabu-asset:` refs) is meaningless in another document: its bytes travel in the
|
|
1695
|
+
// fragment (`assets`), the blocks keep their ref. Outside Nabu (html / plain) such a ref is replaced, never leaked.
|
|
1696
|
+
const files = Files.get(this);
|
|
1697
|
+
const assets = files.embedAssets(pasteBlocks);
|
|
1698
|
+
const fragment = { version: CLIPBOARD_FORMAT_VERSION, blocks: pasteBlocks, ...(assets ? { assets } : {}) };
|
|
1699
|
+
dt.setData('application/x-nabu+json', JSON.stringify(fragment));
|
|
518
1700
|
|
|
519
1701
|
// Recursive serializers — dispatch to each BlockClass's static toMarkdown/toHtml.
|
|
520
|
-
// helpers.recurse lets blocks serialize
|
|
1702
|
+
// helpers.recurse lets blocks serialize a child without knowing its type; helpers.recurseAll serializes a list of
|
|
1703
|
+
// siblings in order, telling each one the siblings before it (`before`) and after it (`after`): a block may depend on
|
|
1704
|
+
// its neighbours (adjacent lists must not read back as one; a block that closes only when something follows it).
|
|
521
1705
|
/** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
|
|
522
1706
|
const pbToMarkdown = (pb, ctx = {}) => {
|
|
523
1707
|
const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
|
|
524
1708
|
if (BlockClass?.toMarkdown) {
|
|
525
|
-
return BlockClass.toMarkdown(pb, {
|
|
1709
|
+
return BlockClass.toMarkdown(pb, {
|
|
1710
|
+
...ctx,
|
|
1711
|
+
recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToMarkdown(child, { ...ctx, before: [], after: [], ...childCtx }),
|
|
1712
|
+
recurseAll: (/** @type {any[]} */ children, /** @type {any} */ childCtx) => children.map((child, k) => pbToMarkdown(child, { ...ctx, ...childCtx, before: children.slice(0, k), after: children.slice(k + 1) })),
|
|
1713
|
+
});
|
|
526
1714
|
}
|
|
527
1715
|
return (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
|
|
528
1716
|
};
|
|
@@ -534,18 +1722,27 @@ export class Nabu {
|
|
|
534
1722
|
return BlockClass.toHtml(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToHtml(child, { ...ctx, ...childCtx }) });
|
|
535
1723
|
}
|
|
536
1724
|
const text = (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
|
|
537
|
-
return text ? `<p>${text}</p>` : '';
|
|
1725
|
+
return text ? `<p>${escapeHtml(text)}</p>` : ''; // unknown block type: escaped, never raw
|
|
538
1726
|
};
|
|
539
1727
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
1728
|
+
// text/plain: a selection inside ONE text block is its raw selected text (no markdown syntax: no `**`, fences,
|
|
1729
|
+
// `# `, `- `); several blocks -> markdown.
|
|
1730
|
+
const single = pasteBlocks.length === 1 && startBlock === endBlock && !pasteBlocks[0].children?.length && Array.isArray(pasteBlocks[0].delta)
|
|
1731
|
+
? pasteBlocks[0] : null;
|
|
1732
|
+
const plain = single
|
|
1733
|
+
? /** @type {any[]} */ (single.delta).map(op => typeof op.insert === 'string' ? op.insert : '').join('')
|
|
1734
|
+
: files.externalize(pasteBlocks).map((pb, k, all) => pbToMarkdown(pb, { before: all.slice(0, k), after: all.slice(k + 1) })).join('\n\n');
|
|
1735
|
+
dt.setData('text/plain', plain);
|
|
1736
|
+
dt.setData('text/html', files.externalize(pasteBlocks, { inline: true }).map(pb => pbToHtml(pb)).join('\n'));
|
|
1737
|
+
return true;
|
|
543
1738
|
}
|
|
544
1739
|
|
|
545
1740
|
/** @param {ClipboardEvent} e */
|
|
546
1741
|
handleCut(e) {
|
|
1742
|
+
this.selection.sync();
|
|
547
1743
|
if (this.selection.isCollapsed) return;
|
|
548
1744
|
e.preventDefault();
|
|
1745
|
+
if (this.#readonly) { this.handleCopy(e); return; } // cutting a read-only text copies it and removes nothing
|
|
549
1746
|
|
|
550
1747
|
// 1. Copy selection to clipboard
|
|
551
1748
|
this.handleCopy(e);
|
|
@@ -554,25 +1751,58 @@ export class Nabu {
|
|
|
554
1751
|
const result = deleteSelectionContent(this, this);
|
|
555
1752
|
if (!result) return;
|
|
556
1753
|
|
|
557
|
-
// 3. Single Loro transaction + restore cursor
|
|
558
|
-
|
|
559
|
-
this
|
|
1754
|
+
// 3. Single Loro transaction (its own undo step, like a structural op) + restore cursor. The caret is placed
|
|
1755
|
+
// once the commit has re-rendered the text: set earlier, the DOM node it points into is replaced.
|
|
1756
|
+
this.#isolateNextCommits();
|
|
1757
|
+
this.commit().then(() => this.selection.setCursor(this.blocks.get(result.block.id) ?? result.block, result.offset));
|
|
560
1758
|
}
|
|
561
1759
|
|
|
562
1760
|
/** @param {ClipboardEvent} e */
|
|
563
1761
|
handlePaste(e) {
|
|
564
1762
|
e.preventDefault();
|
|
1763
|
+
if (this.#readonly) return;
|
|
1764
|
+
this.selection.sync();
|
|
565
1765
|
const clipboard = e.clipboardData;
|
|
566
1766
|
if (!clipboard) return;
|
|
1767
|
+
this.#insertTransfer(clipboard, null);
|
|
1768
|
+
}
|
|
567
1769
|
|
|
1770
|
+
/**
|
|
1771
|
+
* THE pipeline that turns a `DataTransfer` (the clipboard of a paste, the payload of a drop) into content: files become
|
|
1772
|
+
* the blocks their file handlers make of them, text goes to the verbatim buffer of a `pastesAsPlainText` block, else the
|
|
1773
|
+
* first paste interpreter (internal fragment, HTML, markdown, plain text) that reads the payload makes the fragment.
|
|
1774
|
+
* One undo step. `at` is where it lands: null = at the caret (a paste), else a drop position.
|
|
1775
|
+
* @param {DataTransfer} clipboard
|
|
1776
|
+
* @param {DropPosition | null} at
|
|
1777
|
+
*/
|
|
1778
|
+
#insertTransfer(clipboard, at) {
|
|
568
1779
|
const sorted = [...this.#pasteInterpreters].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
|
|
569
1780
|
|
|
1781
|
+
// Files on the clipboard (a screenshot, a file copied from the OS) win over its text payloads: each one becomes the
|
|
1782
|
+
// block their file handler makes of it. Except an internal copy (`application/x-nabu+json` already holds the blocks,
|
|
1783
|
+
// and their bytes), and a text payload that declares itself worth more (a spreadsheet range comes with an image of it).
|
|
1784
|
+
const planned = this.#planPastedFiles(clipboard, sorted);
|
|
1785
|
+
|
|
1786
|
+
// A block with `pastesAsPlainText` (code…) is a verbatim buffer: take the clipboard text as-is,
|
|
1787
|
+
// before any interpreter (markdown / HTML / nabu JSON) gets a chance to split it into blocks.
|
|
1788
|
+
const target = at ? (at.side === 'inside' ? at.block : null) : this.selection.anchorBlock;
|
|
1789
|
+
if (target && (at || target === this.selection.focusBlock) && target.pastesAsPlainText) {
|
|
1790
|
+
const text = clipboard.getData('text/plain');
|
|
1791
|
+
if (text) { this.#pasteVerbatim(target, text, at ? at.offset : undefined); return; }
|
|
1792
|
+
if (!planned.length) return;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
if (planned.length) {
|
|
1796
|
+
this.#pasteFiles(planned, at);
|
|
1797
|
+
return;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
570
1800
|
for (const interpreter of sorted) {
|
|
571
1801
|
const raw = clipboard.getData(interpreter.format);
|
|
572
1802
|
if (!raw) continue;
|
|
573
1803
|
const fragment = interpreter.interpret(raw, this);
|
|
574
1804
|
if (fragment) {
|
|
575
|
-
this.insertFragment(fragment);
|
|
1805
|
+
this.insertFragment(fragment, at ? { at } : undefined);
|
|
576
1806
|
return;
|
|
577
1807
|
}
|
|
578
1808
|
}
|
|
@@ -581,17 +1811,358 @@ export class Nabu {
|
|
|
581
1811
|
}
|
|
582
1812
|
|
|
583
1813
|
/**
|
|
584
|
-
*
|
|
1814
|
+
* The files of a paste event that an extension's `pasteFileHandlers` takes, with the block each one becomes. Empty when
|
|
1815
|
+
* the paste is not a file paste (no file, no handler accepting one, an internal copy, a text payload that outranks them).
|
|
1816
|
+
* @param {DataTransfer} clipboard
|
|
1817
|
+
* @param {import('../utils/extensions.js').PasteInterpreter[]} interpreters
|
|
1818
|
+
* @returns {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>}
|
|
1819
|
+
*/
|
|
1820
|
+
#planPastedFiles(clipboard, interpreters) {
|
|
1821
|
+
if (!this.#pasteFileHandlers.length) return [];
|
|
1822
|
+
/** @type {File[]} */
|
|
1823
|
+
let files = [...(clipboard.files ?? [])];
|
|
1824
|
+
if (!files.length) {
|
|
1825
|
+
files = [...(clipboard.items ?? [])].filter((item) => item.kind === 'file').map((item) => item.getAsFile()).filter((f) => !!f);
|
|
1826
|
+
}
|
|
1827
|
+
if (!files.length) return [];
|
|
1828
|
+
if (clipboard.getData('application/x-nabu+json')) return [];
|
|
1829
|
+
for (const interpreter of interpreters) {
|
|
1830
|
+
if (!interpreter.outranksFiles) continue;
|
|
1831
|
+
const raw = clipboard.getData(interpreter.format);
|
|
1832
|
+
if (raw && interpreter.outranksFiles(raw)) return [];
|
|
1833
|
+
}
|
|
1834
|
+
/** @type {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>} */
|
|
1835
|
+
const planned = [];
|
|
1836
|
+
for (const file of files) {
|
|
1837
|
+
for (const handler of this.#pasteFileHandlers) {
|
|
1838
|
+
let block = null;
|
|
1839
|
+
try { if (handler.accepts(file, this)) block = handler.block(file, this); } catch (error) { this.warn('paste: a file handler failed: ' + error); }
|
|
1840
|
+
if (block) { planned.push({ file, block }); break; }
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
return planned;
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
/**
|
|
1847
|
+
* Insert the blocks made of pasted files, at the caret, in order. The files are hashed and stored first (`Files#stage`),
|
|
1848
|
+
* then ONE `insertFragment` does the rest like any other paste: the blocks hold the hash refs (`pending` while a host's
|
|
1849
|
+
* `onBeforePersist` uploads the file, `rejected` for a file over `files.maxFileSize`); a single undo step.
|
|
1850
|
+
* @param {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>} planned
|
|
1851
|
+
* @param {DropPosition | null} [at] where the blocks land (a drop); null = at the caret (a paste)
|
|
1852
|
+
*/
|
|
1853
|
+
async #pasteFiles(planned, at = null) {
|
|
1854
|
+
const files = Files.get(this);
|
|
1855
|
+
// Staging is asynchronous: a drop position is followed through concurrent edits (Loro cursor), not re-read as an offset.
|
|
1856
|
+
const resolveAt = at ? this.#followPosition(at) : null;
|
|
1857
|
+
/** @type {import('../utils/extensions.js').PasteBlock[]} */
|
|
1858
|
+
const blocks = [];
|
|
1859
|
+
/** @type {Record<string, import('../files/files.svelte.js').EmbeddedAsset>} */
|
|
1860
|
+
const assets = {};
|
|
1861
|
+
for (const { file, block } of planned) {
|
|
1862
|
+
try {
|
|
1863
|
+
const staged = await files.stage(file);
|
|
1864
|
+
blocks.push({ ...block, props: { ...block.props, ref: staged.ref, ...staged.props }, partial: false });
|
|
1865
|
+
if (staged.asset) assets[staged.id] = staged.asset;
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
this.warn(`paste: could not read file "${file.name}": ${error}`);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
if (!blocks.length) return;
|
|
1871
|
+
const where = resolveAt ? resolveAt() : null;
|
|
1872
|
+
this.insertFragment({ blocks, assets }, where ? { at: where } : undefined);
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/**
|
|
1876
|
+
* Insert `text` verbatim at the caret of `block`, replacing its selection: no interpretation, no new
|
|
1877
|
+
* block. One undo step (isolated commit).
|
|
1878
|
+
* @param {Block} block
|
|
1879
|
+
* @param {string} text
|
|
1880
|
+
* @param {number} [offset] insert here instead of replacing the selection (a drop)
|
|
1881
|
+
*/
|
|
1882
|
+
#pasteVerbatim(block, text, offset) {
|
|
1883
|
+
const behavior = block.behaviors?.get('text');
|
|
1884
|
+
const sel = offset === undefined ? behavior?.selection : { from: offset, to: offset };
|
|
1885
|
+
if (!behavior || !sel) return;
|
|
1886
|
+
const from = Math.min(sel.from, sel.to);
|
|
1887
|
+
const to = Math.max(sel.from, sel.to);
|
|
1888
|
+
if (to > from) behavior.delete({ index: from, length: to - from });
|
|
1889
|
+
behavior.insert(from, text);
|
|
1890
|
+
this.#isolateNextCommits();
|
|
1891
|
+
this.commit();
|
|
1892
|
+
tick().then(() => this.selection.setCursor(this.blocks.get(block.id) || block, from + text.length));
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
// DRAG & DROP (ADR 014, lot 4)
|
|
1896
|
+
//
|
|
1897
|
+
// The browser never edits the document: every `dragover` / `drop` over the editor is taken here, whatever it carries.
|
|
1898
|
+
// What is dropped goes through the SAME pipeline as a paste (`#insertTransfer`: files → media blocks, then the paste
|
|
1899
|
+
// interpreters), at the model position under the pointer. The editor's own text selection can be dragged: it is a MOVE.
|
|
1900
|
+
// (The block drag handle — `ui/DragHandle.svelte` — uses pointer events, not HTML5 DnD: the two never meet.)
|
|
1901
|
+
|
|
1902
|
+
/**
|
|
1903
|
+
* Where the drop would land while something is dragged over the editor, `null` otherwise (left, dropped, cancelled, or
|
|
1904
|
+
* nothing the editor can take). Reactive state for a UI: Nabu itself draws nothing.
|
|
1905
|
+
* - `block` / `offset` / `side`: a caret position in the text of `block` (`side: 'inside'`, `offset` in its text), or
|
|
1906
|
+
* beside a block that holds no text (image, divider…: `side: 'before' | 'after'`, by the pointer's half).
|
|
1907
|
+
* - `kind`: `'files'` (OS files → media blocks), `'content'` (text / HTML / markdown / Nabu fragment from outside, or a
|
|
1908
|
+
* copy of the editor's own selection), `'move'` (the editor's own selection being moved). Decided from the drag's
|
|
1909
|
+
* declared types: a drag that mixes files and text resolves as it does for a paste (files win) at the drop.
|
|
1910
|
+
* @type {DropTarget | null}
|
|
1911
|
+
*/
|
|
1912
|
+
dropTarget = $state.raw(null);
|
|
1913
|
+
|
|
1914
|
+
/**
|
|
1915
|
+
* The text selection being dragged out of this editor (set by `handleDragStart`, until the drop / dragend).
|
|
1916
|
+
* @type {{ token: string, range: import('./container.utils.js').DeletionRange } | null}
|
|
1917
|
+
*/
|
|
1918
|
+
#dragSource = null;
|
|
1919
|
+
|
|
1920
|
+
/** @param {DropTarget | null} target */
|
|
1921
|
+
#setDropTarget(target) {
|
|
1922
|
+
if (!sameTarget(this.dropTarget, target)) this.dropTarget = target;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
/** What this editor can take from a drag: the formats its interpreters read, whether it takes files. */
|
|
1926
|
+
#dropCaps() {
|
|
1927
|
+
return { formats: this.#pasteInterpreters.map((interpreter) => interpreter.format), files: this.#pasteFileHandlers.length > 0 };
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/**
|
|
1931
|
+
* Whether a drag event is for this editor's own content: not for a nested editor, a UI island or a form control
|
|
1932
|
+
* inside it (those keep their native behavior), and not during an IME composition.
|
|
1933
|
+
* @param {DragEvent} e
|
|
1934
|
+
*/
|
|
1935
|
+
#ownsDrag(e) {
|
|
1936
|
+
const root = /** @type {HTMLElement | null} */ (e.currentTarget);
|
|
1937
|
+
const target = /** @type {Node | null} */ (e.target instanceof Node ? e.target : null);
|
|
1938
|
+
const el = target && (target.nodeType === Node.ELEMENT_NODE ? /** @type {Element} */ (target) : target.parentElement);
|
|
1939
|
+
if (!root || !el || this.#composing) return false;
|
|
1940
|
+
if (el.closest('[data-nabu-root]') !== root) return false;
|
|
1941
|
+
return !closestWithin(el, '[data-nabu-ui], input, textarea, select', root);
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
/**
|
|
1945
|
+
* Start of a drag inside the editor. A drag of the TEXT SELECTION is serialized like a copy (internal fragment, plain text,
|
|
1946
|
+
* HTML — so it can also be dropped in another editor or application) and remembered: dropped back in the editor it is a
|
|
1947
|
+
* MOVE (see `dropAt`). Any other drag (an image, a link, a draggable element) is cancelled: the browser would hand a drop
|
|
1948
|
+
* its own serialization of the DOM node.
|
|
1949
|
+
* @param {DragEvent} e
|
|
1950
|
+
*/
|
|
1951
|
+
handleDragStart(e) {
|
|
1952
|
+
this.#dragSource = null;
|
|
1953
|
+
this.#setDropTarget(null);
|
|
1954
|
+
if (!this.#ownsDrag(e) || !e.dataTransfer) return;
|
|
1955
|
+
const target = e.target;
|
|
1956
|
+
const draggedElement = target instanceof Element && !!target.closest('img, a[href], [draggable="true"]');
|
|
1957
|
+
this.selection.sync();
|
|
1958
|
+
const range = draggedElement || this.selection.isCollapsed ? null : selectionRange(this);
|
|
1959
|
+
const canMove = this.#pasteInterpreters.some((interpreter) => interpreter.format === NABU_FORMAT);
|
|
1960
|
+
if (!range || !canMove || !this.#writeSelection(e.dataTransfer)) {
|
|
1961
|
+
e.preventDefault();
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
const token = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
1965
|
+
e.dataTransfer.setData(DRAG_MARKER, token);
|
|
1966
|
+
e.dataTransfer.effectAllowed = this.#readonly ? 'copy' : 'copyMove'; // read-only: the text can be dragged out, never moved
|
|
1967
|
+
this.#dragSource = { token, range };
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
/**
|
|
1971
|
+
* `dragenter` / `dragover` over the editor: accept what it can take (cancelling the event is how a drop is allowed),
|
|
1972
|
+
* announce move vs copy, and publish the position in `dropTarget`.
|
|
1973
|
+
* @param {DragEvent} e
|
|
1974
|
+
*/
|
|
1975
|
+
handleDragOver(e) {
|
|
1976
|
+
const dt = e.dataTransfer;
|
|
1977
|
+
if (!dt) return;
|
|
1978
|
+
if (this.#readonly) { this.#setDropTarget(null); dt.dropEffect = 'none'; return; } // not cancelled: nothing can be dropped
|
|
1979
|
+
if (!this.#ownsDrag(e)) { this.#setDropTarget(null); return; }
|
|
1980
|
+
const own = !!this.#dragSource && Array.from(dt.types ?? []).includes(DRAG_MARKER);
|
|
1981
|
+
const copy = own && wantsCopy(e);
|
|
1982
|
+
/** @type {DropKind | null} */
|
|
1983
|
+
const kind = own ? (copy ? 'content' : 'move') : transferKind(dt.types, this.#dropCaps());
|
|
1984
|
+
if (!kind) { this.#setDropTarget(null); dt.dropEffect = 'none'; return; }
|
|
1985
|
+
const root = /** @type {HTMLElement} */ (e.currentTarget);
|
|
1986
|
+
const position = resolveDropPosition(this, root, e.clientX, e.clientY);
|
|
1987
|
+
e.preventDefault(); // allows the drop
|
|
1988
|
+
if (kind === 'move' && position && this.#dragSource && positionInRange(this.#dragSource.range, position)) {
|
|
1989
|
+
dt.dropEffect = 'none'; // onto the dragged text itself: nothing to do
|
|
1990
|
+
this.#setDropTarget(null);
|
|
1991
|
+
return;
|
|
1992
|
+
}
|
|
1993
|
+
dt.dropEffect = pickDropEffect(dt.effectAllowed, kind === 'move' ? 'move' : 'copy');
|
|
1994
|
+
this.#setDropTarget(position ? { ...position, kind } : null);
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/** @param {DragEvent} e */
|
|
1998
|
+
handleDragLeave(e) {
|
|
1999
|
+
if (!this.#ownsDrag(e)) return;
|
|
2000
|
+
const root = /** @type {HTMLElement} */ (e.currentTarget);
|
|
2001
|
+
if (e.relatedTarget instanceof Node && root.contains(e.relatedTarget)) return; // still inside the editor
|
|
2002
|
+
this.#setDropTarget(null);
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
/** The drag that started in this editor ended (dropped anywhere, or cancelled). @param {DragEvent} [e] */
|
|
2006
|
+
handleDragEnd(e) {
|
|
2007
|
+
this.#dragSource = null;
|
|
2008
|
+
this.#setDropTarget(null);
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/**
|
|
2012
|
+
* `drop` on the editor: the browser's default (inserting DOM nodes behind Loro's back, or navigating to a dropped
|
|
2013
|
+
* file) never happens. The position under the pointer is resolved, then {@link Nabu#dropAt} does the rest.
|
|
2014
|
+
* @param {DragEvent} e
|
|
2015
|
+
*/
|
|
2016
|
+
handleDrop(e) {
|
|
2017
|
+
const dt = e.dataTransfer;
|
|
2018
|
+
if (!dt || !this.#ownsDrag(e)) return;
|
|
2019
|
+
e.preventDefault(); // the browser never navigates to a dropped file, read-only or not
|
|
2020
|
+
if (this.#readonly) { this.#dragSource = null; this.#setDropTarget(null); return; }
|
|
2021
|
+
const source = this.#dragSource;
|
|
2022
|
+
this.#dragSource = null;
|
|
2023
|
+
this.#setDropTarget(null);
|
|
2024
|
+
const root = /** @type {HTMLElement} */ (e.currentTarget);
|
|
2025
|
+
const position = resolveDropPosition(this, root, e.clientX, e.clientY) ?? documentEnd(this);
|
|
2026
|
+
if (!position) return;
|
|
2027
|
+
// The editor takes the focus (undo, typing…) even when the drop leaves no text caret to put in it (a dropped image).
|
|
2028
|
+
if (document.activeElement !== root) root.focus({ preventScroll: true });
|
|
2029
|
+
const own = !!source && dt.getData(DRAG_MARKER) === source.token;
|
|
2030
|
+
this.dropAt(dt, position, { source: own && !wantsCopy(e) ? source : null });
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
/**
|
|
2034
|
+
* Drop `dt` at `position`, as ONE undo step, through the paste pipeline (files → media blocks, `pasteInterpreters`:
|
|
2035
|
+
* internal fragment, HTML, markdown, plain text; verbatim text into a `pastesAsPlainText` block).
|
|
2036
|
+
* With `opts.source` (the editor's own dragged selection) it is a MOVE: the source range is deleted and the content
|
|
2037
|
+
* inserted in the same transaction, the position corrected for the deletion; a position inside (or at the edge of) the
|
|
2038
|
+
* source range does nothing. Without it, content from outside — or a copy of the selection — is simply inserted.
|
|
2039
|
+
* @param {DataTransfer} dt
|
|
2040
|
+
* @param {DropPosition} position
|
|
2041
|
+
* @param {{ source?: { range: import('./container.utils.js').DeletionRange } | null }} [opts]
|
|
2042
|
+
*/
|
|
2043
|
+
dropAt(dt, position, opts = {}) {
|
|
2044
|
+
if (this.#readonly) return;
|
|
2045
|
+
const source = opts.source ?? null;
|
|
2046
|
+
if (source) {
|
|
2047
|
+
const { range } = source;
|
|
2048
|
+
const alive = (/** @type {Block} */ b) => !!b && !b.node?.isDeleted?.() && this.blocks.get(b.id) === b;
|
|
2049
|
+
if (!alive(range.startBlock) || !alive(range.endBlock) || !alive(position.block)) return;
|
|
2050
|
+
if (positionInRange(range, position)) return;
|
|
2051
|
+
// Check the payload reads back BEFORE deleting anything: a move that cannot insert must not lose text.
|
|
2052
|
+
const reader = this.#pasteInterpreters.find((interpreter) => interpreter.format === NABU_FORMAT);
|
|
2053
|
+
const raw = dt.getData(NABU_FORMAT);
|
|
2054
|
+
if (!reader || !raw || !reader.interpret(raw, this)) return;
|
|
2055
|
+
if (!deleteRange(this, range)) return;
|
|
2056
|
+
position = positionAfterRemoval(range, position, !!range.endBlock.node?.isDeleted?.());
|
|
2057
|
+
}
|
|
2058
|
+
this.#insertTransfer(dt, position);
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
/**
|
|
2062
|
+
* Degrades the pasted / imported blocks whose type is not registered in THIS editor to the default text
|
|
2063
|
+
* block (text kept, children kept as following siblings, nothing dropped). See `degradeUnknownBlocks`.
|
|
2064
|
+
* @param {import('../utils/extensions.js').PasteBlock[]} blocks
|
|
2065
|
+
* @returns {import('../utils/extensions.js').PasteBlock[]}
|
|
2066
|
+
*/
|
|
2067
|
+
#degradeUnknown(blocks) {
|
|
2068
|
+
const fallback = this.defaultBlockType && this.registry.has(this.defaultBlockType) ? this.defaultBlockType
|
|
2069
|
+
: this.registry.has('paragraph') ? 'paragraph' : null;
|
|
2070
|
+
if (!Array.isArray(blocks)) return blocks;
|
|
2071
|
+
/** @type {Set<string>} */
|
|
2072
|
+
const unknown = new Set();
|
|
2073
|
+
const degraded = degradeUnknownBlocks(blocks, (type) => {
|
|
2074
|
+
const known = this.registry.has(type);
|
|
2075
|
+
if (!known) unknown.add(type);
|
|
2076
|
+
return known;
|
|
2077
|
+
}, fallback);
|
|
2078
|
+
if (fallback && unknown.size) this.warn(`paste: unregistered block type(s) [${[...unknown].join(', ')}] degraded to "${fallback}"`);
|
|
2079
|
+
return degraded;
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
/**
|
|
2083
|
+
* What a block IS for the clipboard (its type and structural props), used to continue it after a paste.
|
|
2084
|
+
* @param {Block} block
|
|
2085
|
+
* @returns {{ type: string, props: Record<string, any> }}
|
|
2086
|
+
*/
|
|
2087
|
+
#blockSpec(block) {
|
|
2088
|
+
/** @type {any} */
|
|
2089
|
+
let serialized = null;
|
|
2090
|
+
try { serialized = block.serialize('application/x-nabu+json', { from: 0, to: 0, partial: false }); } catch { /* no serializer */ }
|
|
2091
|
+
return { type: block.type, props: { ...(serialized?.props ?? {}) } };
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
/**
|
|
2095
|
+
* The caret position a drop position stands for. Beside a block without text (before / after an image, a divider…) there
|
|
2096
|
+
* is no caret: an empty default text block is created there (same transaction as the insertion, so one undo step), and the
|
|
2097
|
+
* fragment lands in it like in any empty block (a text becomes its text, a media block replaces it).
|
|
2098
|
+
* @param {DropPosition} at
|
|
2099
|
+
* @returns {{ block: Block, offset: number } | null}
|
|
2100
|
+
*/
|
|
2101
|
+
#landingFor(at) {
|
|
2102
|
+
const { block, side } = at;
|
|
2103
|
+
if (!block || block.node?.isDeleted?.()) return null;
|
|
2104
|
+
if (side === 'inside') {
|
|
2105
|
+
const length = block.behaviors?.get('text')?.text?.length;
|
|
2106
|
+
if (length === undefined) return null;
|
|
2107
|
+
return { block, offset: Math.max(0, Math.min(at.offset, length)) };
|
|
2108
|
+
}
|
|
2109
|
+
const type = this.defaultBlockType;
|
|
2110
|
+
const Class = type && this.registry.get(type);
|
|
2111
|
+
if (!Class) return null;
|
|
2112
|
+
const created = Class.create(this, type, {});
|
|
2113
|
+
if (side === 'before') created.node.moveBefore(block.node);
|
|
2114
|
+
else created.node.moveAfter(block.node);
|
|
2115
|
+
wrapOrphan(this, created);
|
|
2116
|
+
return { block: created, offset: 0 };
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
/**
|
|
2120
|
+
* A function that re-reads a drop position later, after edits that happened meanwhile (the files of a drop are hashed
|
|
2121
|
+
* asynchronously): a text position follows the text through a Loro cursor; a block that vanished falls back to the end
|
|
2122
|
+
* of the document.
|
|
2123
|
+
* @param {DropPosition} at
|
|
2124
|
+
* @returns {() => DropPosition | null}
|
|
2125
|
+
*/
|
|
2126
|
+
#followPosition(at) {
|
|
2127
|
+
const text = at.side === 'inside' ? /** @type {any} */ (at.block.behaviors?.get('text')?.container) : null;
|
|
2128
|
+
/** @type {any} */
|
|
2129
|
+
let cursor = null;
|
|
2130
|
+
try { cursor = text?.getCursor?.(at.offset) ?? null; } catch { /* static fallback */ }
|
|
2131
|
+
return () => {
|
|
2132
|
+
if (at.block.node?.isDeleted?.()) return documentEnd(this);
|
|
2133
|
+
if (!cursor) return at;
|
|
2134
|
+
try {
|
|
2135
|
+
const pos = this.doc.getCursorPos(cursor);
|
|
2136
|
+
return pos ? { ...at, offset: pos.offset } : at;
|
|
2137
|
+
} catch { return at; }
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
/**
|
|
2142
|
+
* Insère un PasteFragment à la position du curseur courant — or at `opts.at` (a drop position: a caret position in a
|
|
2143
|
+
* text block, or beside a block without text, where an empty text block receives the fragment), whatever the DOM selection is.
|
|
585
2144
|
* @param {import('../utils/extensions.js').PasteFragment} fragment
|
|
2145
|
+
* @param {{ at?: DropPosition }} [opts]
|
|
586
2146
|
*/
|
|
587
|
-
insertFragment(fragment) {
|
|
588
|
-
|
|
2147
|
+
insertFragment(fragment, opts = {}) {
|
|
2148
|
+
this.selection.sync(); // public entry point: may be called outside an input event
|
|
2149
|
+
// Every fragment (HTML / markdown / nabu JSON / API) goes through here: unsafe link & media URLs are dropped.
|
|
2150
|
+
const files = Files.get(this);
|
|
2151
|
+
let adopted = files.adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets);
|
|
2152
|
+
// Content from outside (a web page): remote images are fetched and stored, when the host asked for it (`files.importRemote`).
|
|
2153
|
+
if (fragment.external) adopted = files.importRemote(adopted);
|
|
2154
|
+
const blocks = this.#degradeUnknown(adopted);
|
|
589
2155
|
if (!blocks?.length) return;
|
|
590
2156
|
|
|
591
2157
|
let anchorBlock;
|
|
592
2158
|
let offset;
|
|
593
2159
|
|
|
594
|
-
if (
|
|
2160
|
+
if (opts.at) {
|
|
2161
|
+
const landing = this.#landingFor(opts.at);
|
|
2162
|
+
if (!landing) return;
|
|
2163
|
+
anchorBlock = landing.block;
|
|
2164
|
+
offset = landing.offset;
|
|
2165
|
+
} else if (!this.selection.isCollapsed) {
|
|
595
2166
|
const result = deleteSelectionContent(this, this);
|
|
596
2167
|
if (!result) return;
|
|
597
2168
|
anchorBlock = result.block;
|
|
@@ -608,15 +2179,50 @@ export class Nabu {
|
|
|
608
2179
|
return;
|
|
609
2180
|
}
|
|
610
2181
|
|
|
2182
|
+
// The caret block may take over the insertion (a list item keeps pasted paragraphs in its list, and
|
|
2183
|
+
// splits the list around a block it cannot hold…). It declines with null: the default path runs.
|
|
2184
|
+
const landing = anchorBlock.acceptPaste(blocks, { offset });
|
|
2185
|
+
if (landing) {
|
|
2186
|
+
this.#isolateNextCommits();
|
|
2187
|
+
this.commit();
|
|
2188
|
+
tick().then(() => {
|
|
2189
|
+
if (!landing.block) return;
|
|
2190
|
+
const fb = this.blocks.get(landing.block.id) || landing.block;
|
|
2191
|
+
this.selection.setCursor(fb, landing.offset);
|
|
2192
|
+
});
|
|
2193
|
+
return;
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
// A whole pasted block landing in an EMPTY root-level block (e.g. `# Title` into an
|
|
2197
|
+
// empty paragraph) brings its type along. Pasting into existing text never coerces.
|
|
2198
|
+
// Blocks nested in a container (list item…) keep their type to preserve the structure, unless that
|
|
2199
|
+
// container holds free-form content (`Block#adoptsPastedTypes`, e.g. a toggle body).
|
|
2200
|
+
const anchorEmpty = textBehavior.container.length === 0 && (!anchorBlock.parent || anchorBlock.parent.adoptsPastedTypes);
|
|
2201
|
+
/** @param {import('../utils/extensions.js').PasteBlock} pb */
|
|
2202
|
+
const adoptType = (pb) => {
|
|
2203
|
+
if (!anchorEmpty || pb.partial !== false || pb.type === anchorBlock.type || !this.registry.has(pb.type)) return;
|
|
2204
|
+
const data = /** @type {any} */ (anchorBlock.node.data);
|
|
2205
|
+
data.set('type', pb.type);
|
|
2206
|
+
for (const [key, value] of Object.entries(pb.props || {})) data.set(key, value);
|
|
2207
|
+
};
|
|
2208
|
+
|
|
2209
|
+
// A pasted block is TEXT when it carries a delta; one without (image, divider…) cannot merge into the caret block's
|
|
2210
|
+
// text: it is inserted as a block (the caret block is split around it), or replaces an empty caret block (see adoptType).
|
|
2211
|
+
/** @param {import('../utils/extensions.js').PasteBlock} pb */
|
|
2212
|
+
const isText = (pb) => Array.isArray(pb.delta);
|
|
2213
|
+
|
|
611
2214
|
// ── Inline: single flat block ─────────────────────────────────────────
|
|
612
|
-
if (blocks.length === 1 && !blocks[0].children?.length) {
|
|
2215
|
+
if (blocks.length === 1 && !blocks[0].children?.length && (isText(blocks[0]) || anchorEmpty)) {
|
|
613
2216
|
const pb = blocks[0];
|
|
614
2217
|
const delta = pb.delta || [];
|
|
615
2218
|
const len = delta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
|
|
616
2219
|
|
|
2220
|
+
adoptType(pb);
|
|
617
2221
|
textBehavior.applyDelta([{ retain: offset }, ...delta]);
|
|
2222
|
+
this.#isolateNextCommits();
|
|
618
2223
|
this.commit();
|
|
619
|
-
|
|
2224
|
+
// A type change makes updateRoots() replace the block instance — re-fetch it.
|
|
2225
|
+
tick().then(() => this.selection.setCursor(this.blocks.get(anchorBlock.id) || anchorBlock, offset + len));
|
|
620
2226
|
return;
|
|
621
2227
|
}
|
|
622
2228
|
|
|
@@ -627,6 +2233,11 @@ export class Nabu {
|
|
|
627
2233
|
textBehavior.delete({ index: offset, length: textBehavior.container.length - offset });
|
|
628
2234
|
}
|
|
629
2235
|
|
|
2236
|
+
// What the caret block IS (type + props), captured before it may adopt a pasted type: the text that
|
|
2237
|
+
// follows the caret continues in a block of the same kind, like Enter would (`Ti|tle` heading stays a
|
|
2238
|
+
// heading on both sides of the pasted blocks).
|
|
2239
|
+
const tailSpec = rightDelta.length ? this.#blockSpec(anchorBlock) : null;
|
|
2240
|
+
|
|
630
2241
|
const firstPb = blocks[0];
|
|
631
2242
|
const lastPb = blocks[blocks.length - 1];
|
|
632
2243
|
const midPbs = blocks.slice(1, -1);
|
|
@@ -635,67 +2246,74 @@ export class Nabu {
|
|
|
635
2246
|
let focusOffset = offset;
|
|
636
2247
|
|
|
637
2248
|
// ── First block ───────────────────────────────────────────────────────
|
|
638
|
-
if (!firstPb.children?.length) {
|
|
639
|
-
// Leaf: merge content into anchor (anchor type survives)
|
|
2249
|
+
if (!firstPb.children?.length && (isText(firstPb) || anchorEmpty)) {
|
|
2250
|
+
// Leaf: merge content into anchor (anchor type survives, unless it was empty — see adoptType)
|
|
2251
|
+
adoptType(firstPb);
|
|
640
2252
|
const firstDelta = firstPb.delta || [];
|
|
641
2253
|
if (firstDelta.length) textBehavior.applyDelta([{ retain: offset }, ...firstDelta]);
|
|
642
2254
|
focusOffset = offset + firstDelta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
|
|
643
2255
|
} else {
|
|
644
|
-
// Container (e.g. List): insert it after anchor
|
|
645
|
-
prevNode = this
|
|
2256
|
+
// Container (e.g. List) or void block (image…): insert it after anchor
|
|
2257
|
+
prevNode = this.insertPasteBlock(firstPb, prevNode);
|
|
646
2258
|
}
|
|
2259
|
+
// The caret was at the very start of a text block and a block (not text) comes first: nothing precedes the pasted
|
|
2260
|
+
// block, the blank head left behind goes (the tail, created below, is the block that keeps the text).
|
|
2261
|
+
const dropHead = offset === 0 && !!rightDelta.length && !isText(firstPb) && !anchorEmpty && !/** @type {any} */ (anchorBlock).children?.length;
|
|
647
2262
|
|
|
648
2263
|
// ── Middle blocks ─────────────────────────────────────────────────────
|
|
649
2264
|
for (const pb of midPbs) {
|
|
650
|
-
prevNode = this
|
|
2265
|
+
prevNode = this.insertPasteBlock(pb, prevNode);
|
|
651
2266
|
}
|
|
652
2267
|
|
|
653
2268
|
// ── Last block (only when blocks.length > 1) ──────────────────────────
|
|
2269
|
+
// The text after the caret (`rightDelta`) merges with the last pasted block when that one is TEXT
|
|
2270
|
+
// (cut at the edge of a partial copy, or a default text block), in a block of the caret block's kind;
|
|
2271
|
+
// otherwise (heading, code, image, container…) the block is inserted as it is and the tail follows in
|
|
2272
|
+
// a block of the caret block's kind. Without a tail the last block is simply inserted as it is.
|
|
2273
|
+
/** @param {{type: string, props?: Record<string, any>}} spec @param {import('loro-crdt').Delta<string>[]} delta @param {any} after */
|
|
2274
|
+
const insertLeaf = (spec, delta, after) => {
|
|
2275
|
+
const Class = this.registry.get(spec.type) || this.registry.get('paragraph');
|
|
2276
|
+
if (!Class) return null;
|
|
2277
|
+
const created = Class.create(this, spec.type, spec.props || {});
|
|
2278
|
+
created.node.moveAfter(after);
|
|
2279
|
+
const wrapper = wrapOrphan(this, created);
|
|
2280
|
+
if (delta.length) created.behaviors?.get('text')?.applyDelta(delta);
|
|
2281
|
+
return { block: created, node: wrapper ? wrapper.node : created.node };
|
|
2282
|
+
};
|
|
2283
|
+
const deltaLen = (/** @type {any[]} */ d) => d.reduce((n, op) => n + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
|
|
2284
|
+
|
|
654
2285
|
if (blocks.length > 1) {
|
|
655
2286
|
if (!lastPb.children?.length) {
|
|
656
|
-
|
|
657
|
-
const
|
|
658
|
-
if (
|
|
659
|
-
const
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
const
|
|
663
|
-
if (
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
}
|
|
668
|
-
focusBlock = newLast;
|
|
669
|
-
prevNode = wrapper ? wrapper.node : newLast.node;
|
|
2287
|
+
const lastDelta = lastPb.delta || [];
|
|
2288
|
+
const lastIsText = lastPb.partial === 'end' || lastPb.partial === 'both' || lastPb.type === this.defaultBlockType;
|
|
2289
|
+
if (!tailSpec) {
|
|
2290
|
+
const done = insertLeaf({ type: lastPb.type, props: lastPb.props }, lastDelta, prevNode);
|
|
2291
|
+
if (done) { focusBlock = done.block; focusOffset = deltaLen(lastDelta); prevNode = done.node; }
|
|
2292
|
+
} else if (lastIsText) {
|
|
2293
|
+
const done = insertLeaf(tailSpec, [...lastDelta, ...rightDelta], prevNode);
|
|
2294
|
+
if (done) { focusBlock = done.block; focusOffset = deltaLen(lastDelta); prevNode = done.node; }
|
|
2295
|
+
} else {
|
|
2296
|
+
prevNode = this.insertPasteBlock(lastPb, prevNode);
|
|
2297
|
+
const done = insertLeaf(tailSpec, rightDelta, prevNode);
|
|
2298
|
+
if (done) { focusBlock = done.block; focusOffset = 0; prevNode = done.node; }
|
|
670
2299
|
}
|
|
671
2300
|
} else {
|
|
672
|
-
// Container last block: insert it,
|
|
673
|
-
prevNode = this
|
|
674
|
-
if (
|
|
675
|
-
const
|
|
676
|
-
if (
|
|
677
|
-
const p = PClass.create(this, 'paragraph', {});
|
|
678
|
-
p.node.moveAfter(prevNode);
|
|
679
|
-
p.behaviors?.get('text')?.applyDelta(rightDelta);
|
|
680
|
-
focusBlock = p;
|
|
681
|
-
focusOffset = 0;
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
} else {
|
|
686
|
-
// Single container block: rightDelta goes in a new paragraph after it
|
|
687
|
-
if (rightDelta.length) {
|
|
688
|
-
const PClass = this.registry.get('paragraph');
|
|
689
|
-
if (PClass) {
|
|
690
|
-
const p = PClass.create(this, 'paragraph', {});
|
|
691
|
-
p.node.moveAfter(prevNode);
|
|
692
|
-
p.behaviors?.get('text')?.applyDelta(rightDelta);
|
|
693
|
-
focusBlock = p;
|
|
694
|
-
focusOffset = 0;
|
|
2301
|
+
// Container last block: insert it, the tail goes in a new block after it
|
|
2302
|
+
prevNode = this.insertPasteBlock(lastPb, prevNode);
|
|
2303
|
+
if (tailSpec) {
|
|
2304
|
+
const done = insertLeaf(tailSpec, rightDelta, prevNode);
|
|
2305
|
+
if (done) { focusBlock = done.block; focusOffset = 0; }
|
|
695
2306
|
}
|
|
696
2307
|
}
|
|
2308
|
+
} else if (tailSpec) {
|
|
2309
|
+
// Single container block: the tail goes in a new block after it
|
|
2310
|
+
const done = insertLeaf(tailSpec, rightDelta, prevNode);
|
|
2311
|
+
if (done) { focusBlock = done.block; focusOffset = 0; }
|
|
697
2312
|
}
|
|
698
2313
|
|
|
2314
|
+
if (dropHead && focusBlock !== anchorBlock) this.tree.delete(anchorBlock.node.id);
|
|
2315
|
+
|
|
2316
|
+
this.#isolateNextCommits();
|
|
699
2317
|
this.commit();
|
|
700
2318
|
tick().then(() => {
|
|
701
2319
|
const fb = this.blocks.get(focusBlock.id) || focusBlock;
|
|
@@ -706,21 +2324,35 @@ export class Nabu {
|
|
|
706
2324
|
/**
|
|
707
2325
|
* Inserts a PasteBlock after `afterNode`. Handles both leaf blocks (wrapOrphan)
|
|
708
2326
|
* and container blocks (creates container, recurses into children).
|
|
709
|
-
* Returns the outer node to use as the next prevNode.
|
|
2327
|
+
* Returns the outer node to use as the next prevNode. Public: part of the paste toolbox a block's
|
|
2328
|
+
* `acceptPaste` hook builds on. No commit.
|
|
710
2329
|
* @param {import('../utils/extensions.js').PasteBlock} pb
|
|
711
2330
|
* @param {any} afterNode
|
|
712
2331
|
* @returns {any}
|
|
2332
|
+
* @public
|
|
713
2333
|
*/
|
|
714
|
-
|
|
2334
|
+
insertPasteBlock(pb, afterNode) {
|
|
2335
|
+
if (!this.registry.has(pb.type)) {
|
|
2336
|
+
// Unknown type: degraded to the default text block, its children follow it (nothing is dropped).
|
|
2337
|
+
const degraded = this.#degradeUnknown([pb]);
|
|
2338
|
+
if (degraded.length === 1 && !this.registry.has(degraded[0].type)) return afterNode; // no default block to degrade to
|
|
2339
|
+
let previous = afterNode;
|
|
2340
|
+
for (const d of degraded) previous = this.insertPasteBlock(d, previous);
|
|
2341
|
+
return previous;
|
|
2342
|
+
}
|
|
715
2343
|
if (pb.children?.length) {
|
|
716
2344
|
const ContainerClass = this.registry.get(pb.type);
|
|
717
2345
|
if (!ContainerClass) return afterNode;
|
|
718
2346
|
const container = ContainerClass.create(this, pb.type, pb.props || {});
|
|
719
2347
|
container.node.moveAfter(afterNode);
|
|
2348
|
+
// A container with its own text (list item, toggle…) keeps it.
|
|
2349
|
+
const ctb = container.behaviors?.get('text');
|
|
2350
|
+
if (ctb && pb.delta?.length) ctb.applyDelta(pb.delta);
|
|
720
2351
|
for (const child of pb.children) {
|
|
721
|
-
this
|
|
2352
|
+
this.createPasteBlock(child, container.node.id.toString());
|
|
722
2353
|
}
|
|
723
|
-
|
|
2354
|
+
const wrapper = wrapOrphan(this, container);
|
|
2355
|
+
return wrapper ? wrapper.node : container.node;
|
|
724
2356
|
}
|
|
725
2357
|
|
|
726
2358
|
const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
|
|
@@ -735,22 +2367,119 @@ export class Nabu {
|
|
|
735
2367
|
}
|
|
736
2368
|
|
|
737
2369
|
/**
|
|
738
|
-
* Creates a block inside a container, recursively handling nested children.
|
|
2370
|
+
* Creates a block inside a container, recursively handling nested children. Public: part of the paste
|
|
2371
|
+
* toolbox a block's `acceptPaste` hook builds on. No commit.
|
|
739
2372
|
* @param {import('../utils/extensions.js').PasteBlock} pb
|
|
740
2373
|
* @param {string} parentId
|
|
2374
|
+
* @returns {Block | null} the created block
|
|
2375
|
+
* @public
|
|
741
2376
|
*/
|
|
742
|
-
|
|
2377
|
+
createPasteBlock(pb, parentId) {
|
|
2378
|
+
if (!this.registry.has(pb.type)) {
|
|
2379
|
+
// Unknown type: the default text block, then its children as ITS following siblings (not inside it).
|
|
2380
|
+
const [head, ...rest] = this.#degradeUnknown([pb]);
|
|
2381
|
+
if (!head || !this.registry.has(head.type)) return null;
|
|
2382
|
+
const created = this.createPasteBlock(head, parentId);
|
|
2383
|
+
for (const sibling of rest) this.createPasteBlock(sibling, parentId);
|
|
2384
|
+
return created;
|
|
2385
|
+
}
|
|
743
2386
|
const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
|
|
744
|
-
if (!BlockClass) return;
|
|
2387
|
+
if (!BlockClass) return null;
|
|
745
2388
|
const block = BlockClass.create(this, pb.type, pb.props || {}, parentId);
|
|
746
2389
|
const tb = block.behaviors?.get('text');
|
|
747
2390
|
if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
|
|
748
2391
|
for (const child of pb.children || []) {
|
|
749
|
-
this
|
|
2392
|
+
this.createPasteBlock(child, block.node.id.toString());
|
|
750
2393
|
}
|
|
2394
|
+
return block;
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
// DOCUMENT IMPORT
|
|
2398
|
+
|
|
2399
|
+
/**
|
|
2400
|
+
* Replace the entire document with the given PasteFragment.
|
|
2401
|
+
* Unlike insertFragment(), this does not depend on a live DOM selection:
|
|
2402
|
+
* blocks are created at the root through the same registry pipeline as paste.
|
|
2403
|
+
* @param {import('../utils/extensions.js').PasteFragment} fragment
|
|
2404
|
+
* @returns {Promise<void>}
|
|
2405
|
+
* @public
|
|
2406
|
+
*/
|
|
2407
|
+
async importFragment(fragment) {
|
|
2408
|
+
const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets));
|
|
2409
|
+
if (!blocks?.length) return;
|
|
2410
|
+
|
|
2411
|
+
[...this.tree.roots()].forEach(root => this.tree.delete(root.id));
|
|
2412
|
+
|
|
2413
|
+
for (const pb of blocks) {
|
|
2414
|
+
const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
|
|
2415
|
+
if (!BlockClass) continue;
|
|
2416
|
+
const block = BlockClass.create(this, pb.type, pb.props || {});
|
|
2417
|
+
const tb = block.behaviors?.get('text');
|
|
2418
|
+
if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
|
|
2419
|
+
for (const child of pb.children || []) {
|
|
2420
|
+
this.createPasteBlock(child, block.node.id.toString());
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
await this.commit();
|
|
2425
|
+
// The files of the import are verified and stored in the background: the import is complete once they are (a host upload is not waited for).
|
|
2426
|
+
await Files.get(this).whenIdle();
|
|
751
2427
|
}
|
|
752
2428
|
|
|
753
|
-
/**
|
|
2429
|
+
/**
|
|
2430
|
+
* Replace the entire document with content parsed from a Markdown string.
|
|
2431
|
+
* Requires MarkdownPasteExtension (or any text/plain interpreter) to be loaded.
|
|
2432
|
+
* @param {string} markdown
|
|
2433
|
+
* @returns {Promise<void>}
|
|
2434
|
+
* @public
|
|
2435
|
+
*/
|
|
2436
|
+
async importMarkdown(markdown) {
|
|
2437
|
+
const interpreter = [...this.#pasteInterpreters]
|
|
2438
|
+
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
|
2439
|
+
.find(i => i.format === 'text/plain');
|
|
2440
|
+
if (!interpreter) {
|
|
2441
|
+
this.warn('importMarkdown: MarkdownPasteExtension not loaded');
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
// CommonMark semantics: consecutive lines join into one paragraph (paste splits per line).
|
|
2446
|
+
const fragment = interpreter.interpret(markdown, this, { joinLines: true });
|
|
2447
|
+
if (!fragment) {
|
|
2448
|
+
this.warn('importMarkdown: nothing to import');
|
|
2449
|
+
return;
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
await this.importFragment(fragment);
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
/**
|
|
2456
|
+
* Replace the entire document with a `serialize('json')` export. An export of a version this editor does not know
|
|
2457
|
+
* is refused with a warning (the document is left untouched), like the clipboard does; a block type that is not
|
|
2458
|
+
* registered is degraded to the default text block (`degradeUnknownBlocks`), nothing is dropped.
|
|
2459
|
+
* @param {{version?: string | number, blocks: Parameters<typeof import('../utils/extensions.js').jsonToPasteBlocks>[0], assets?: Record<string, import('../files/files.svelte.js').EmbeddedAsset>} | string} json
|
|
2460
|
+
* @returns {Promise<void>}
|
|
2461
|
+
* @public
|
|
2462
|
+
*/
|
|
2463
|
+
async importJSON(json) {
|
|
2464
|
+
const doc = typeof json === 'string' ? JSON.parse(json) : json;
|
|
2465
|
+
if (!isSupportedJsonVersion(doc?.version)) {
|
|
2466
|
+
this.warn(`importJSON: unsupported export version ${JSON.stringify(doc.version)} (this editor reads version ${JSON_FORMAT_VERSION}): nothing imported`);
|
|
2467
|
+
return;
|
|
2468
|
+
}
|
|
2469
|
+
const blocks = jsonToPasteBlocks(doc?.blocks || []);
|
|
2470
|
+
if (!blocks.length) {
|
|
2471
|
+
this.warn('importJSON: nothing to import');
|
|
2472
|
+
return;
|
|
2473
|
+
}
|
|
2474
|
+
await this.importFragment({ blocks, ...(doc.assets && typeof doc.assets === 'object' ? { assets: doc.assets } : {}) });
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/**
|
|
2478
|
+
* The block and local offset that hold a document-wide caret offset (`positions` counted from the start of the document).
|
|
2479
|
+
* @param {number} globalOffset
|
|
2480
|
+
* @returns {{ block: Block, offset: number } | null}
|
|
2481
|
+
* @public
|
|
2482
|
+
*/
|
|
754
2483
|
resolveDocumentOffset(globalOffset) {
|
|
755
2484
|
let remaining = globalOffset;
|
|
756
2485
|
for (const block of this.children) {
|
|
@@ -763,7 +2492,86 @@ export class Nabu {
|
|
|
763
2492
|
return last ? last.resolveOffset(Math.max(0, (last.positions ?? 1) - 1)) : null;
|
|
764
2493
|
}
|
|
765
2494
|
|
|
766
|
-
/** @
|
|
2495
|
+
/** @type {NabuInternals | null} */
|
|
2496
|
+
#internals = null;
|
|
2497
|
+
|
|
2498
|
+
/**
|
|
2499
|
+
* The door to everything the engine uses internally that the stable contract (the members tagged `public` in their JSDoc) does not cover: the
|
|
2500
|
+
* command-confirm controller, the action bus, the hook and rule registries, the clipboard / drop / event pipelines, undo
|
|
2501
|
+
* capture, stored marks, the selection's repair machinery. They are the same references the engine runs on, not copies.
|
|
2502
|
+
*
|
|
2503
|
+
* The door itself is part of the stable contract; **@unstable** is everything behind it: nothing reached through `internals` is a
|
|
2504
|
+
* promise, it may change, move or disappear in ANY minor version.
|
|
2505
|
+
* Prefer the stable members; use this when you must, and pin the version of the package. The set of keys is frozen by a
|
|
2506
|
+
* test, so a change shows up in the changelog.
|
|
2507
|
+
* @returns {NabuInternals}
|
|
2508
|
+
* @public
|
|
2509
|
+
* @unstable
|
|
2510
|
+
*/
|
|
2511
|
+
get internals() {
|
|
2512
|
+
if (this.#internals) return this.#internals;
|
|
2513
|
+
const nabu = this;
|
|
2514
|
+
const selection = nabu.selection;
|
|
2515
|
+
return this.#internals = Object.freeze({
|
|
2516
|
+
pulse: this.#pulse,
|
|
2517
|
+
commandConfirm: this.commandConfirm,
|
|
2518
|
+
hooks: this.hooks,
|
|
2519
|
+
hookOwners: this.hookOwners,
|
|
2520
|
+
inputRules: this.inputRules,
|
|
2521
|
+
pasteInterpreters: this.#pasteInterpreters,
|
|
2522
|
+
pasteFileHandlers: this.#pasteFileHandlers,
|
|
2523
|
+
undoManager: this.undoManager,
|
|
2524
|
+
content: this.content,
|
|
2525
|
+
fileConfig: this.fileConfig,
|
|
2526
|
+
get storedMarks() { return nabu.storedMarks; },
|
|
2527
|
+
set storedMarks(value) { nabu.storedMarks = value; },
|
|
2528
|
+
toggleStoredMark: this.toggleStoredMark.bind(this),
|
|
2529
|
+
clearStoredMarks: this.clearStoredMarks.bind(this),
|
|
2530
|
+
noteTextChange: this.noteTextChange.bind(this),
|
|
2531
|
+
captureUndoSelection: this.captureUndoSelection.bind(this),
|
|
2532
|
+
sealUndoEnd: this.sealUndoEnd.bind(this),
|
|
2533
|
+
updateRoots: this.updateRoots.bind(this),
|
|
2534
|
+
deleteNode: this.deleteNode.bind(this),
|
|
2535
|
+
rearmTab: this.rearmTab.bind(this),
|
|
2536
|
+
get tabDescription() { return nabu.tabDescription; },
|
|
2537
|
+
dispatchEventToSelection: this.dispatchEventToSelection.bind(this),
|
|
2538
|
+
handleKeydown: this.handleKeydown.bind(this),
|
|
2539
|
+
handleBeforeinput: this.handleBeforeinput.bind(this),
|
|
2540
|
+
beforeinput: this.beforeinput.bind(this),
|
|
2541
|
+
handleCompositionStart: this.handleCompositionStart.bind(this),
|
|
2542
|
+
handleCompositionUpdate: this.handleCompositionUpdate.bind(this),
|
|
2543
|
+
handleCompositionEnd: this.handleCompositionEnd.bind(this),
|
|
2544
|
+
handleMousedown: this.handleMousedown.bind(this),
|
|
2545
|
+
handleCopy: this.handleCopy.bind(this),
|
|
2546
|
+
handleCut: this.handleCut.bind(this),
|
|
2547
|
+
handlePaste: this.handlePaste.bind(this),
|
|
2548
|
+
insertFragment: this.insertFragment.bind(this),
|
|
2549
|
+
handleDragStart: this.handleDragStart.bind(this),
|
|
2550
|
+
handleDragOver: this.handleDragOver.bind(this),
|
|
2551
|
+
handleDragLeave: this.handleDragLeave.bind(this),
|
|
2552
|
+
handleDragEnd: this.handleDragEnd.bind(this),
|
|
2553
|
+
handleDrop: this.handleDrop.bind(this),
|
|
2554
|
+
dropAt: this.dropAt.bind(this),
|
|
2555
|
+
get dropTarget() { return nabu.dropTarget; },
|
|
2556
|
+
selection: Object.freeze({
|
|
2557
|
+
normalize: selection.normalize.bind(selection),
|
|
2558
|
+
scheduleRepair: selection.scheduleRepair.bind(selection),
|
|
2559
|
+
repairAfterRemoval: selection.repairAfterRemoval.bind(selection),
|
|
2560
|
+
get placements() { return selection.placements; },
|
|
2561
|
+
attachRoot: selection.attachRoot.bind(selection),
|
|
2562
|
+
owns: selection.owns.bind(selection),
|
|
2563
|
+
scope: selection.scope.bind(selection),
|
|
2564
|
+
get root() { return selection.root; },
|
|
2565
|
+
}),
|
|
2566
|
+
});
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
/**
|
|
2570
|
+
* Log a diagnostic to the console when `debugging` is on. Silent otherwise.
|
|
2571
|
+
* @param {...any} args
|
|
2572
|
+
* @returns {void}
|
|
2573
|
+
* @public
|
|
2574
|
+
*/
|
|
767
2575
|
warn(...args) {
|
|
768
2576
|
if (this.debugging) console.warn("[Nabu]", ...args);
|
|
769
2577
|
}
|