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