@aionbuilders/nabu 0.1.0-beta.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +523 -0
- package/LICENSE +21 -0
- package/README.md +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 +199 -48
- package/dist/behaviors/text/text.behavior.svelte.js +549 -83
- 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 +31 -17
- 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 +1746 -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 +34 -13
- 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 +54 -7
- 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/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 +47 -19
- package/dist/utils/selection.svelte.js +60 -10
- package/dist/utils/spellcheck.d.ts +9 -0
- package/dist/utils/spellcheck.js +17 -0
- package/dist/utils/tab.d.ts +31 -0
- package/dist/utils/tab.js +117 -0
- package/dist/utils/words.d.ts +7 -0
- package/dist/utils/words.js +62 -0
- package/dist/vite.d.ts +9 -3
- package/dist/vite.js +19 -8
- package/package.json +54 -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
|
@@ -4,18 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
import { LoroText } from "loro-crdt";
|
|
6
6
|
import { tick } from "svelte";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
* @param {string} text
|
|
11
|
-
* @returns {string}
|
|
12
|
-
*/
|
|
13
|
-
function escapeHtml(text) {
|
|
14
|
-
return text
|
|
15
|
-
.replace(/&/g, '&')
|
|
16
|
-
.replace(/</g, '<')
|
|
17
|
-
.replace(/>/g, '>');
|
|
18
|
-
}
|
|
7
|
+
import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
|
|
8
|
+
import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
|
|
9
|
+
import { countWords } from "../../utils/words.js";
|
|
19
10
|
|
|
20
11
|
/**
|
|
21
12
|
* Converts a Loro text delta to inline HTML.
|
|
@@ -33,62 +24,202 @@ export function deltaToHtml(delta) {
|
|
|
33
24
|
if (attrs.italic) text = `<em>${text}</em>`;
|
|
34
25
|
if (attrs.underline) text = `<u>${text}</u>`;
|
|
35
26
|
if (attrs.strikethrough) text = `<s>${text}</s>`;
|
|
36
|
-
if (attrs.link)
|
|
27
|
+
if (attrs.link) {
|
|
28
|
+
// An unsafe href (javascript:, data:…) never becomes a live link: the label survives, the <a> does not.
|
|
29
|
+
const href = sanitizeUrl(attrs.link, { kind: 'link' });
|
|
30
|
+
if (href !== null) text = `<a href="${escapeAttr(href)}">${text}</a>`;
|
|
31
|
+
}
|
|
37
32
|
return text;
|
|
38
33
|
}).join('');
|
|
39
34
|
}
|
|
40
35
|
|
|
41
36
|
/**
|
|
42
37
|
* Converts a Loro text delta to inline Markdown.
|
|
38
|
+
* A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
|
|
39
|
+
* (a block that re-reads its own lines, like a callout body, keeps the plain newline).
|
|
43
40
|
* @param {import('loro-crdt').Delta<string>[]} delta
|
|
41
|
+
* @param {{ rawBreaks?: boolean }} [options]
|
|
44
42
|
* @returns {string}
|
|
45
43
|
*/
|
|
46
|
-
export function deltaToMarkdown(delta) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
44
|
+
export function deltaToMarkdown(delta, { rawBreaks = false } = {}) {
|
|
45
|
+
const ops = delta.filter((op) => typeof op.insert === 'string' && op.insert);
|
|
46
|
+
let out = '';
|
|
47
|
+
for (let i = 0; i < ops.length;) {
|
|
48
|
+
const link = ops[i].attributes?.link;
|
|
49
|
+
let j = i + 1;
|
|
50
|
+
while (j < ops.length && ops[j].attributes?.link === link) j++;
|
|
51
|
+
const run = markdownRuns(ops.slice(i, j), rawBreaks); // same href (or none): ONE `[…](href)`, marks inside
|
|
52
|
+
out += link ? `[${run}](${markdownDestination(String(link))})` : run;
|
|
53
|
+
i = j;
|
|
54
|
+
}
|
|
55
|
+
return escapeBlockStart(out);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Mark delimiters, outermost first (nesting order). Code is not here: a code span takes no other mark. */
|
|
59
|
+
const MARK_DELIMITERS = /** @type {const} */ ([
|
|
60
|
+
['underline', '<u>', '</u>'],
|
|
61
|
+
['strikethrough', '~~', '~~'],
|
|
62
|
+
['bold', '**', '**'],
|
|
63
|
+
['italic', '*', '*'],
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Runs of text (no link boundary inside) as markdown. A mark spanning several runs is ONE delimiter pair
|
|
68
|
+
* (`**a *b* c**`); whitespace at the edge of a span moves outside the delimiters (`**a **` would not parse).
|
|
69
|
+
* @param {any[]} ops
|
|
70
|
+
* @param {boolean} rawBreaks
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
function markdownRuns(ops, rawBreaks) {
|
|
74
|
+
/** @type {Array<{ text?: string, raw?: boolean, open?: string, close?: string }>} */
|
|
75
|
+
let tokens = [];
|
|
76
|
+
/** @type {number[]} */
|
|
77
|
+
let active = [];
|
|
78
|
+
const closeFrom = (/** @type {number} */ k) => {
|
|
79
|
+
for (let j = active.length - 1; j >= k; j--) tokens.push({ close: MARK_DELIMITERS[active[j]][2] });
|
|
80
|
+
active = active.slice(0, k);
|
|
81
|
+
};
|
|
82
|
+
for (const op of ops) {
|
|
50
83
|
const attrs = op.attributes || {};
|
|
51
|
-
if (attrs.code)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
84
|
+
if (attrs.code) { closeFrom(0); tokens.push({ text: markdownCodeSpan(op.insert), raw: true }); continue; }
|
|
85
|
+
const want = MARK_DELIMITERS.map((m, idx) => (attrs[m[0]] ? idx : -1)).filter((idx) => idx >= 0);
|
|
86
|
+
let k = 0;
|
|
87
|
+
while (k < active.length && k < want.length && active[k] === want[k]) k++;
|
|
88
|
+
closeFrom(k);
|
|
89
|
+
for (let j = k; j < want.length; j++) tokens.push({ open: MARK_DELIMITERS[want[j]][1] });
|
|
90
|
+
active = want;
|
|
91
|
+
tokens.push({ text: op.insert });
|
|
92
|
+
}
|
|
93
|
+
closeFrom(0);
|
|
94
|
+
|
|
95
|
+
// Whitespace at the inner edge of a delimiter run moves outside it.
|
|
96
|
+
for (let t = 0; t < tokens.length; t++) {
|
|
97
|
+
if (tokens[t].open !== undefined && tokens[t - 1]?.open === undefined) {
|
|
98
|
+
let j = t;
|
|
99
|
+
while (tokens[j + 1]?.open !== undefined) j++;
|
|
100
|
+
const next = tokens[j + 1];
|
|
101
|
+
const m = next && next.text !== undefined && !next.raw ? /^\s+/.exec(next.text) : null;
|
|
102
|
+
if (next && m) { next.text = /** @type {string} */ (next.text).slice(m[0].length); tokens.splice(t, 0, { text: m[0] }); t += 1; }
|
|
103
|
+
} else if (tokens[t].close !== undefined && tokens[t - 1]?.close === undefined) {
|
|
104
|
+
let j = t;
|
|
105
|
+
while (tokens[j + 1]?.close !== undefined) j++;
|
|
106
|
+
const prev = tokens[t - 1];
|
|
107
|
+
const m = prev && prev.text !== undefined && !prev.raw ? /\s+$/.exec(prev.text) : null;
|
|
108
|
+
if (prev && m) { prev.text = /** @type {string} */ (prev.text).slice(0, -m[0].length); tokens.splice(j + 1, 0, { text: m[0] }); }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// Drop the delimiter pairs left empty.
|
|
112
|
+
tokens = tokens.filter((tk) => tk.text !== '');
|
|
113
|
+
for (let t = 0; t < tokens.length - 1;) {
|
|
114
|
+
if (tokens[t].open !== undefined && tokens[t + 1].close !== undefined) { tokens.splice(t, 2); t = Math.max(0, t - 1); } else t++;
|
|
115
|
+
}
|
|
116
|
+
return tokens.map((tk) => tk.open ?? tk.close ?? (tk.raw ? tk.text : escapeMarkdownText(/** @type {string} */ (tk.text)).replace(/\n/g, rawBreaks ? '\n' : '\\\n'))).join('');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A code span: a backtick fence longer than any run inside, padded when the text touches a backtick or is space-wrapped. */
|
|
120
|
+
function markdownCodeSpan(/** @type {string} */ text) {
|
|
121
|
+
const runs = new Set((text.match(/`+/g) || []).map((r) => r.length));
|
|
122
|
+
let n = 1;
|
|
123
|
+
while (runs.has(n)) n++;
|
|
124
|
+
const fence = '`'.repeat(n);
|
|
125
|
+
const pad = /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : '';
|
|
126
|
+
return fence + pad + text + pad + fence;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
|
|
130
|
+
export function markdownDestination(/** @type {string} */ href) {
|
|
131
|
+
let depth = 0;
|
|
132
|
+
let balanced = true;
|
|
133
|
+
for (const ch of href) {
|
|
134
|
+
if (ch === '(') depth++;
|
|
135
|
+
else if (ch === ')' && --depth < 0) balanced = false;
|
|
136
|
+
}
|
|
137
|
+
if (!href || depth !== 0 || !balanced || /[\s<>\u0000-\u001f]/.test(href)) return '<' + href.replace(/[<>\\]/g, (m) => '\\' + m) + '>';
|
|
138
|
+
return href.replace(/\\/g, '\\\\');
|
|
60
139
|
}
|
|
61
140
|
|
|
62
141
|
/**
|
|
63
142
|
* @typedef {NabuNode<{type: "paragraph", text: LoroText}>} TextNode
|
|
64
143
|
*/
|
|
65
144
|
|
|
145
|
+
/** @type {Intl.Segmenter | null} */
|
|
146
|
+
const graphemeSegmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Length (UTF-16 units) of the user-perceived character starting at `index` — the unit one Delete press removes.
|
|
150
|
+
* `Intl.Segmenter` handles ZWJ sequences, flags and combining marks; without it a surrogate pair is kept whole.
|
|
151
|
+
* A caret inside a cluster deletes up to the end of that cluster. 0 at the end of the text.
|
|
152
|
+
* @param {string} text @param {number} index
|
|
153
|
+
*/
|
|
154
|
+
export function nextGraphemeLength(text, index) {
|
|
155
|
+
if (index < 0 || index >= text.length) return 0;
|
|
156
|
+
if (graphemeSegmenter) {
|
|
157
|
+
const seg = graphemeSegmenter.segment(text).containing(index);
|
|
158
|
+
if (seg) return seg.index + seg.segment.length - index;
|
|
159
|
+
}
|
|
160
|
+
const code = text.charCodeAt(index);
|
|
161
|
+
const low = text.charCodeAt(index + 1);
|
|
162
|
+
return code >= 0xD800 && code <= 0xDBFF && low >= 0xDC00 && low <= 0xDFFF ? 2 : 1;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Length (UTF-16 units) of the user-perceived character ENDING at `index` — the unit one Backspace press removes.
|
|
167
|
+
* Mirror of {@link nextGraphemeLength}: `Intl.Segmenter` handles ZWJ sequences, flags and combining marks; without it a
|
|
168
|
+
* surrogate pair is kept whole. A caret inside a cluster deletes back to the start of that cluster. 0 at the start.
|
|
169
|
+
* @param {string} text @param {number} index
|
|
170
|
+
*/
|
|
171
|
+
export function prevGraphemeLength(text, index) {
|
|
172
|
+
if (index <= 0 || index > text.length) return 0;
|
|
173
|
+
if (graphemeSegmenter) {
|
|
174
|
+
const seg = graphemeSegmenter.segment(text).containing(index - 1);
|
|
175
|
+
if (seg) return index - seg.index;
|
|
176
|
+
}
|
|
177
|
+
const low = text.charCodeAt(index - 1);
|
|
178
|
+
const high = text.charCodeAt(index - 2);
|
|
179
|
+
return low >= 0xDC00 && low <= 0xDFFF && high >= 0xD800 && high <= 0xDBFF ? 2 : 1;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The editing of a block's rich text: wraps a Loro text and offers the reactive `text` and `delta`, the selection in that text, and insertion, deletion, splitting, marks and links. Text blocks use it through `TextBlock`; a container with a header (list item, toggle) owns one.
|
|
184
|
+
*/
|
|
66
185
|
export class TextBehavior {
|
|
67
186
|
/** @param {Block} block @param {LoroText} [container] */
|
|
68
187
|
constructor(block, container) {
|
|
188
|
+
/** @public */
|
|
69
189
|
this.block = block;
|
|
70
190
|
this.nabu = block.nabu;
|
|
71
191
|
const node = /** @type {TextNode} */ (block.node);
|
|
72
|
-
/**
|
|
192
|
+
/**
|
|
193
|
+
* @type {LoroText}
|
|
194
|
+
* @public
|
|
195
|
+
*/
|
|
73
196
|
this.container = container ?? node.data.get("text") ?? node.data.setContainer("text", new LoroText());
|
|
197
|
+
/** @public */
|
|
74
198
|
this.text = $state(this.container.toString());
|
|
199
|
+
/** @public */
|
|
75
200
|
this.delta = $state(this.container.toDelta());
|
|
76
201
|
this.container.subscribe(() => {
|
|
77
202
|
this.text = this.container.toString();
|
|
78
203
|
this.delta = this.container.toDelta();
|
|
204
|
+
this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
|
|
79
205
|
});
|
|
80
206
|
}
|
|
81
207
|
|
|
208
|
+
/** @public */
|
|
82
209
|
selection = $derived(this.block.element && this.block.nabu.selection && this.getSelection(this.block.element, this.block.nabu.selection));
|
|
83
210
|
|
|
211
|
+
/** @public */
|
|
84
212
|
positions = $derived(this.text.length + 1);
|
|
85
213
|
|
|
86
214
|
/**
|
|
87
|
-
* Number of
|
|
215
|
+
* Number of words in this text: segmented with `Intl.Segmenter` in the language of the editor (`nabu.lang`) when the platform
|
|
216
|
+
* has it, so Chinese or Japanese text counts its words rather than one per sentence; whitespace-separated otherwise. See
|
|
217
|
+
* `utils/words.js`. Reactive in the text and in `nabu.lang`.
|
|
88
218
|
* @returns {number}
|
|
219
|
+
* @public
|
|
89
220
|
*/
|
|
90
221
|
get wordCount() {
|
|
91
|
-
return this.text.
|
|
222
|
+
return countWords(this.text, this.nabu?.lang);
|
|
92
223
|
}
|
|
93
224
|
|
|
94
225
|
/**
|
|
@@ -108,11 +239,11 @@ export class TextBehavior {
|
|
|
108
239
|
let to = this.text.length;
|
|
109
240
|
|
|
110
241
|
if (containsStart) {
|
|
111
|
-
from = this.
|
|
242
|
+
from = this.modelOffset(globalRange.startContainer, globalRange.startOffset);
|
|
112
243
|
}
|
|
113
244
|
|
|
114
245
|
if (containsEnd) {
|
|
115
|
-
to = this.
|
|
246
|
+
to = this.modelOffset(globalRange.endContainer, globalRange.endOffset);
|
|
116
247
|
}
|
|
117
248
|
|
|
118
249
|
return {
|
|
@@ -137,11 +268,86 @@ export class TextBehavior {
|
|
|
137
268
|
return range.toString().length;
|
|
138
269
|
}
|
|
139
270
|
|
|
140
|
-
/**
|
|
271
|
+
/**
|
|
272
|
+
* {@link TextBehavior#calculateOffset} bounded by the MODEL text: an empty text renders a lone "\n" placeholder, and a caret
|
|
273
|
+
* after it is still offset 0, not 1 (P-108). (Not during an IME composition: the browser's text is ahead of the model then.)
|
|
274
|
+
* @param {Node} node @param {number} offset @param {HTMLElement?} [element]
|
|
275
|
+
*/
|
|
276
|
+
modelOffset(node, offset, element = this.block.element) {
|
|
277
|
+
const at = this.calculateOffset(node, offset, element);
|
|
278
|
+
return this.nabu.composing ? at : Math.min(at, this.text.length);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** The render of an EMPTY block when an IME composition started (Svelte's own child nodes and their text), to put back if it is canceled. @type {{ nodes: Node[], data: string[] } | null} */
|
|
282
|
+
#emptySnapshot = null;
|
|
283
|
+
|
|
284
|
+
/** Svelte's own nodes around a trailing render filler when an IME composition started: its text nodes and the filler with its place. @type {{ texts: Set<Node>, filler: Element, parent: Node, next: Node | null } | null} */
|
|
285
|
+
#compositionSnapshot = null;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* IME composition starts. With a trailing render filler (`<br data-nabu-filler>`, the empty last line after a "\n")
|
|
289
|
+
* the browser puts the composed text in a NEW text node before the filler (and may swap the filler for a `<br>` of
|
|
290
|
+
* its own) — nodes Svelte does not know, which would stay next to the ones it updates once the model catches up
|
|
291
|
+
* (text shown twice). Remember Svelte's nodes so {@link TextBehavior#restoreAfterComposition} can undo the browser's
|
|
292
|
+
* additions at the end. No filler: nothing to do.
|
|
293
|
+
*/
|
|
294
|
+
snapshotForComposition() {
|
|
295
|
+
const element = this.block.element;
|
|
296
|
+
this.#compositionSnapshot = null;
|
|
297
|
+
this.#emptySnapshot = null;
|
|
298
|
+
// An EMPTY block renders a lone "\n" text node: a canceled composition makes the browser swap it for a <br> (caret lost).
|
|
299
|
+
if (element && !this.text) {
|
|
300
|
+
const nodes = [...element.childNodes];
|
|
301
|
+
this.#emptySnapshot = { nodes, data: nodes.map((n) => n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n).data : '') };
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const filler = element?.querySelector('[data-nabu-filler]');
|
|
305
|
+
if (!element || !filler?.parentNode) return;
|
|
306
|
+
const texts = new Set();
|
|
307
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
|
308
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) texts.add(n);
|
|
309
|
+
this.#compositionSnapshot = { texts, filler, parent: filler.parentNode, next: filler.nextSibling };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* End of a composition begun next to a filler, BEFORE the composed text reaches the model: remove the text nodes and
|
|
314
|
+
* `<br>` the browser created meanwhile (the composed text is committed to the model, which the next render shows
|
|
315
|
+
* through Svelte's own nodes); a canceled composition (`composedText` empty) gets its filler back.
|
|
316
|
+
* @param {string} composedText
|
|
317
|
+
*/
|
|
318
|
+
restoreAfterComposition(composedText) {
|
|
319
|
+
const snap = this.#compositionSnapshot;
|
|
320
|
+
this.#compositionSnapshot = null;
|
|
321
|
+
const element = this.block.element;
|
|
322
|
+
const empty = this.#emptySnapshot;
|
|
323
|
+
this.#emptySnapshot = null;
|
|
324
|
+
if (empty && element && !composedText) {
|
|
325
|
+
// Canceled in an empty block: the render text node (not a browser <br>) with its text, as Svelte left it.
|
|
326
|
+
element.replaceChildren(...empty.nodes);
|
|
327
|
+
empty.nodes.forEach((n, i) => { if (n.nodeType === Node.TEXT_NODE && /** @type {Text} */ (n).data !== empty.data[i]) /** @type {Text} */ (n).data = empty.data[i]; });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (!snap || !element) return;
|
|
331
|
+
/** @type {Node[]} */
|
|
332
|
+
const stray = [];
|
|
333
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
|
334
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) if (!snap.texts.has(n)) stray.push(n);
|
|
335
|
+
for (const br of element.querySelectorAll('br')) if (br !== snap.filler) stray.push(br);
|
|
336
|
+
for (const n of stray) n.parentNode?.removeChild(n);
|
|
337
|
+
if (!composedText && !snap.filler.isConnected) {
|
|
338
|
+
snap.parent.insertBefore(snap.filler, snap.next?.parentNode === snap.parent ? snap.next : null);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* @param {InputEvent} event
|
|
344
|
+
* @param {ReturnType<TextBehavior["getSelection"]>} [selection]
|
|
345
|
+
* @public
|
|
346
|
+
*/
|
|
141
347
|
handleBeforeInput(event, selection = this.selection) {
|
|
142
348
|
// Hook system (Markdown shortcuts, de-transformation, structural guards…).
|
|
143
349
|
// `transformsEnabled: false` (e.g. code blocks) only suppresses transforms,
|
|
144
|
-
// which fire on insertions — deletion hooks (block exit,
|
|
350
|
+
// which fire on insertions — deletion hooks (block exit, structural guards) still run.
|
|
145
351
|
const isInsertion = event.inputType === "insertText"
|
|
146
352
|
|| event.inputType === "insertParagraph"
|
|
147
353
|
|| event.inputType === "insertLineBreak"
|
|
@@ -174,7 +380,32 @@ export class TextBehavior {
|
|
|
174
380
|
case "deleteWordForward":
|
|
175
381
|
return this.handleDeleteWordForward(event, selection);
|
|
176
382
|
case "deleteSoftLineBackward":
|
|
383
|
+
case "deleteHardLineBackward":
|
|
177
384
|
return this.handleDeleteSoftLineBackward(event, selection);
|
|
385
|
+
case "deleteSoftLineForward":
|
|
386
|
+
case "deleteHardLineForward":
|
|
387
|
+
return this.handleDeleteSoftLineForward(event, selection);
|
|
388
|
+
case "deleteEntireSoftLine":
|
|
389
|
+
case "deleteEntireHardLine":
|
|
390
|
+
return this.handleDeleteEntireLine(event, selection);
|
|
391
|
+
case "deleteContent":
|
|
392
|
+
return this.handleDeleteContent(event, selection);
|
|
393
|
+
case "insertReplacementText":
|
|
394
|
+
return this.handleInsertReplacementText(event, selection);
|
|
395
|
+
case "insertFromYank":
|
|
396
|
+
return this.handleInsertFromYank(event, selection);
|
|
397
|
+
case "insertTranspose":
|
|
398
|
+
return this.handleInsertTranspose(event, selection);
|
|
399
|
+
case "formatBold":
|
|
400
|
+
case "formatItalic":
|
|
401
|
+
case "formatUnderline":
|
|
402
|
+
case "formatStrikeThrough":
|
|
403
|
+
case "formatSubscript":
|
|
404
|
+
case "formatSuperscript":
|
|
405
|
+
case "formatRemove":
|
|
406
|
+
// Formatting is the rich-text extension's business (its `onBeforeInput` hook already ran); without it: nothing.
|
|
407
|
+
event.preventDefault();
|
|
408
|
+
return true;
|
|
178
409
|
case "insertParagraph":
|
|
179
410
|
return this.handleInsertParagraph(event, selection);
|
|
180
411
|
case "historyUndo":
|
|
@@ -241,6 +472,19 @@ export class TextBehavior {
|
|
|
241
472
|
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from + 1));
|
|
242
473
|
}
|
|
243
474
|
|
|
475
|
+
/**
|
|
476
|
+
* Whether an extension vetoes the merge of two text blocks that Backspace / Delete at a block boundary is about to do
|
|
477
|
+
* (the `onBeforeMerge(nabu, survivor, victim)` hook; returning `nabu.BREAK` refuses: nothing is merged, nothing is
|
|
478
|
+
* deleted). The engine names no reason: an extension may protect a structural boundary between the two blocks.
|
|
479
|
+
* @param {Block} survivor @param {Block} victim
|
|
480
|
+
*/
|
|
481
|
+
#mergeRefused(survivor, victim) {
|
|
482
|
+
const hooks = this.nabu.hooks.get("onBeforeMerge");
|
|
483
|
+
if (!hooks) return false;
|
|
484
|
+
for (const hook of hooks) if (hook(this.nabu, survivor, victim) === this.nabu.BREAK) return true;
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
|
|
244
488
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
|
|
245
489
|
handleDeleteContentBackward(event, sel = this.selection) {
|
|
246
490
|
if (!sel) return;
|
|
@@ -250,6 +494,7 @@ export class TextBehavior {
|
|
|
250
494
|
const previousBehavior = previousBlock?.behaviors.get("text");
|
|
251
495
|
if (previousBehavior && previousBehavior instanceof TextBehavior) {
|
|
252
496
|
event.preventDefault();
|
|
497
|
+
if (this.#mergeRefused(previousBlock, this.block)) return true;
|
|
253
498
|
const previousLength = previousBehavior.text.length;
|
|
254
499
|
// previousBehavior.delta([
|
|
255
500
|
// { retain: previousLength },
|
|
@@ -263,8 +508,11 @@ export class TextBehavior {
|
|
|
263
508
|
}
|
|
264
509
|
} else {
|
|
265
510
|
event.preventDefault();
|
|
266
|
-
|
|
267
|
-
|
|
511
|
+
// A collapsed caret deletes the PREVIOUS grapheme cluster (a ZWJ emoji, a flag, a letter + combining accent,
|
|
512
|
+
// a surrogate pair — never half of one); a selection inside the block is deleted whole.
|
|
513
|
+
const length = sel.isCollapsed ? prevGraphemeLength(this.text, sel.from) : sel.to - sel.from;
|
|
514
|
+
const index = sel.isCollapsed ? sel.from - length : sel.from;
|
|
515
|
+
if (length <= 0) return true;
|
|
268
516
|
this.delete({index, length});
|
|
269
517
|
this.block.commit();
|
|
270
518
|
|
|
@@ -282,6 +530,7 @@ export class TextBehavior {
|
|
|
282
530
|
const nextBehavior = nextBlock?.behaviors.get("text");
|
|
283
531
|
if (nextBehavior && nextBehavior instanceof TextBehavior) {
|
|
284
532
|
event.preventDefault();
|
|
533
|
+
if (this.#mergeRefused(this.block, nextBlock)) return true;
|
|
285
534
|
// this.delta([
|
|
286
535
|
// { retain: this.container.length },
|
|
287
536
|
// ...nextBehavior.container.toDelta()
|
|
@@ -294,13 +543,31 @@ export class TextBehavior {
|
|
|
294
543
|
|
|
295
544
|
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
|
|
296
545
|
}
|
|
546
|
+
return;
|
|
297
547
|
}
|
|
548
|
+
// Everywhere else the native mutation is prevented, so the key must be handled here or it is swallowed:
|
|
549
|
+
// a selection inside the block is deleted whole, a collapsed caret deletes the NEXT grapheme cluster
|
|
550
|
+
// (a ZWJ emoji, a flag, a letter + combining accent, a surrogate pair — never half of one).
|
|
551
|
+
event.preventDefault();
|
|
552
|
+
const index = sel.from;
|
|
553
|
+
const length = sel.isCollapsed ? nextGraphemeLength(this.text, sel.from) : sel.to - sel.from;
|
|
554
|
+
if (length <= 0) return true;
|
|
555
|
+
this.delete({ index, length });
|
|
556
|
+
this.block.commit();
|
|
557
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, index));
|
|
558
|
+
return true;
|
|
298
559
|
}
|
|
299
560
|
|
|
300
561
|
/**
|
|
301
562
|
* Deletes the word before the cursor (Ctrl+Backspace on Win/Linux,
|
|
302
563
|
* Option+Delete on Mac), including the whitespace that precedes it
|
|
303
564
|
* so no orphan space is left behind (issue #4).
|
|
565
|
+
*
|
|
566
|
+
* For a collapsed selection the range is always computed from the model
|
|
567
|
+
* text, never from `event.getTargetRanges()`: browsers disagree on it
|
|
568
|
+
* (Chromium stops right after the previous space, leaving "one two " from
|
|
569
|
+
* "one two three"), so the behavior would differ per engine.
|
|
570
|
+
* Rule: remove `\s* \S+ \s*` ending at the cursor ("one two three|" -> "one two").
|
|
304
571
|
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
305
572
|
*/
|
|
306
573
|
handleDeleteWordBackward(event, sel = this.selection) {
|
|
@@ -311,19 +578,10 @@ export class TextBehavior {
|
|
|
311
578
|
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
|
|
312
579
|
return true;
|
|
313
580
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const r = ranges[0];
|
|
319
|
-
deleteFrom = this.calculateOffset(r.startContainer, r.startOffset);
|
|
320
|
-
} else {
|
|
321
|
-
// FIX issue #4 : inclure le whitespace AVANT le mot dans la suppression
|
|
322
|
-
const textBefore = this.text.slice(0, sel.from);
|
|
323
|
-
// \s* leading : l'espace qui précède le mot est supprimé aussi (comportement Mac)
|
|
324
|
-
const wordMatch = textBefore.match(/(\s*\S+\s*)$/);
|
|
325
|
-
deleteFrom = wordMatch ? sel.from - wordMatch[0].length : 0;
|
|
326
|
-
}
|
|
581
|
+
const textBefore = this.text.slice(0, sel.from);
|
|
582
|
+
// \s* leading : l'espace qui précède le mot est supprimé aussi (comportement Mac)
|
|
583
|
+
const wordMatch = textBefore.match(/(\s*\S+\s*)$/);
|
|
584
|
+
const deleteFrom = wordMatch ? sel.from - wordMatch[0].length : 0;
|
|
327
585
|
const len = sel.from - deleteFrom;
|
|
328
586
|
if (len > 0) this.delete({ index: deleteFrom, length: len });
|
|
329
587
|
this.block.commit();
|
|
@@ -332,8 +590,19 @@ export class TextBehavior {
|
|
|
332
590
|
}
|
|
333
591
|
|
|
334
592
|
/**
|
|
335
|
-
* Deletes the word after the cursor (Ctrl+Delete / Option+Fn+Delete)
|
|
336
|
-
*
|
|
593
|
+
* Deletes the word after the cursor (Ctrl+Delete / Option+Fn+Delete).
|
|
594
|
+
*
|
|
595
|
+
* Like backward deletion, a collapsed selection is resolved from the model
|
|
596
|
+
* text only (`getTargetRanges()` is ignored: it is engine-dependent).
|
|
597
|
+
* Rule, so that the result never has a double space nor glued words:
|
|
598
|
+
* - the cursor is right before the word ("one |two three") -> remove the
|
|
599
|
+
* word and its trailing whitespace -> "one three";
|
|
600
|
+
* - whitespace sits between the cursor and the word ("one| two three")
|
|
601
|
+
* -> remove that leading whitespace and the word, keep the trailing
|
|
602
|
+
* whitespace -> "one three";
|
|
603
|
+
* - last word of the text -> remove it with its leading whitespace
|
|
604
|
+
* ("one two| three" -> "one two").
|
|
605
|
+
* If only whitespace remains after the cursor, it is all removed.
|
|
337
606
|
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
338
607
|
*/
|
|
339
608
|
handleDeleteWordForward(event, sel = this.selection) {
|
|
@@ -344,18 +613,15 @@ export class TextBehavior {
|
|
|
344
613
|
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
|
|
345
614
|
return true;
|
|
346
615
|
}
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const wordMatch = textAfter.match(/^(\s*\S+\s*)/);
|
|
356
|
-
deleteTo = sel.from + (wordMatch ? wordMatch[0].length : textAfter.length);
|
|
616
|
+
const textAfter = this.text.slice(sel.from);
|
|
617
|
+
const wordMatch = textAfter.match(/^(\s*)(\S+)(\s*)/);
|
|
618
|
+
let len;
|
|
619
|
+
if (!wordMatch) len = textAfter.length;
|
|
620
|
+
else {
|
|
621
|
+
const [, leading, word, trailing] = wordMatch;
|
|
622
|
+
// Leading whitespace present: keep the trailing one as the separator.
|
|
623
|
+
len = leading ? leading.length + word.length : word.length + trailing.length;
|
|
357
624
|
}
|
|
358
|
-
const len = deleteTo - sel.from;
|
|
359
625
|
if (len > 0) this.delete({ index: sel.from, length: len });
|
|
360
626
|
this.block.commit();
|
|
361
627
|
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
|
|
@@ -363,19 +629,175 @@ export class TextBehavior {
|
|
|
363
629
|
}
|
|
364
630
|
|
|
365
631
|
/**
|
|
366
|
-
*
|
|
367
|
-
* (
|
|
632
|
+
* Start of the line holding `index` (after the previous "\n", or 0). A model line is a "\n"-delimited run: soft and
|
|
633
|
+
* hard lines are the same thing here (the model knows no visual wrapping).
|
|
634
|
+
* @param {number} index
|
|
635
|
+
*/
|
|
636
|
+
#lineStart(index) {
|
|
637
|
+
return index <= 0 ? 0 : this.text.lastIndexOf('\n', index - 1) + 1;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** End of the line holding `index` (the next "\n", or the end of the text). @param {number} index */
|
|
641
|
+
#lineEnd(index) {
|
|
642
|
+
const nl = this.text.indexOf('\n', index);
|
|
643
|
+
return nl === -1 ? this.text.length : nl;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Deletes `[from, to)` as ONE edit (one commit), caret at `from`. Always returns true (the event is handled).
|
|
648
|
+
* @param {number} from @param {number} to
|
|
649
|
+
*/
|
|
650
|
+
#deleteSpan(from, to) {
|
|
651
|
+
if (to > from) {
|
|
652
|
+
this.delete({ index: from, length: to - from });
|
|
653
|
+
this.block.commit();
|
|
654
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, from));
|
|
655
|
+
}
|
|
656
|
+
return true;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Deletes from the start of the current line to the cursor (Cmd+Backspace on Mac; `deleteHardLineBackward`).
|
|
661
|
+
* A selection inside the block is deleted whole.
|
|
368
662
|
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
369
663
|
*/
|
|
370
664
|
handleDeleteSoftLineBackward(event, sel = this.selection) {
|
|
371
665
|
if (!sel) return;
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
666
|
+
if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
|
|
667
|
+
return this.#deleteSpan(this.#lineStart(sel.from), sel.from);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Deletes from the cursor to the end of the current line (Cmd+Fn+Delete, Ctrl+K style; `deleteHardLineForward`).
|
|
672
|
+
* At the end of a line (before a "\n") or of the block nothing is deleted. A selection is deleted whole.
|
|
673
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
674
|
+
*/
|
|
675
|
+
handleDeleteSoftLineForward(event, sel = this.selection) {
|
|
676
|
+
if (!sel) return;
|
|
677
|
+
if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
|
|
678
|
+
return this.#deleteSpan(sel.from, this.#lineEnd(sel.from));
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Deletes the whole line(s) touched by the selection (`deleteEntireSoftLine`): the text between the surrounding "\n"
|
|
683
|
+
* (or block edges), the line breaks themselves are kept. Caret at the start of the emptied line.
|
|
684
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
685
|
+
*/
|
|
686
|
+
handleDeleteEntireLine(event, sel = this.selection) {
|
|
687
|
+
if (!sel) return;
|
|
688
|
+
return this.#deleteSpan(this.#lineStart(sel.from), this.#lineEnd(sel.to));
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* `deleteContent`: delete the selection (no direction). A collapsed caret deletes nothing.
|
|
693
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
694
|
+
*/
|
|
695
|
+
handleDeleteContent(event, sel = this.selection) {
|
|
696
|
+
if (!sel) return;
|
|
697
|
+
return this.#deleteSpan(sel.from, sel.to);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* The attributes (marks) of the run holding the character at `index`, or null.
|
|
702
|
+
* @param {number} index
|
|
703
|
+
* @returns {Record<string, any> | null}
|
|
704
|
+
*/
|
|
705
|
+
#marksAt(index) {
|
|
706
|
+
let offset = 0;
|
|
707
|
+
for (const op of this.container.toDelta()) {
|
|
708
|
+
if (typeof op.insert !== 'string') continue;
|
|
709
|
+
const end = offset + op.insert.length;
|
|
710
|
+
if (index >= offset && index < end) return op.attributes ? { ...op.attributes } : null;
|
|
711
|
+
offset = end;
|
|
712
|
+
}
|
|
713
|
+
return null;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* Inserts `text` at `index` carrying `marks` (the inserted run only; marks are exact, they never leak to neighbours).
|
|
718
|
+
* @param {number} index @param {string} text @param {Record<string, any> | null} marks
|
|
719
|
+
*/
|
|
720
|
+
#insertWithMarks(index, text, marks) {
|
|
721
|
+
if (!text) return;
|
|
722
|
+
this.insert(index, text);
|
|
723
|
+
if (!marks) return;
|
|
724
|
+
const range = { from: index, to: index + text.length, isCollapsed: false, direction: /** @type {const} */ ('none') };
|
|
725
|
+
for (const [name, value] of Object.entries(marks)) if (value) this.applyMark(name, value, range);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* `insertReplacementText`: a spellcheck / autocorrect replacement. The replacement text comes in
|
|
730
|
+
* `dataTransfer` (`text/plain`) or `data`; the range to replace in `getTargetRanges()` (mapped to model offsets), else
|
|
731
|
+
* the selection. The replaced run's marks are kept on the new text. One edit (one undo step), caret after it.
|
|
732
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
733
|
+
*/
|
|
734
|
+
handleInsertReplacementText(event, sel = this.selection) {
|
|
735
|
+
const text = event.dataTransfer?.getData?.('text/plain') || event.data || '';
|
|
736
|
+
const element = this.block.element;
|
|
737
|
+
const target = typeof event.getTargetRanges === 'function' ? event.getTargetRanges()[0] : null;
|
|
738
|
+
let from;
|
|
739
|
+
let to;
|
|
740
|
+
if (target && element && element.contains(target.startContainer) && element.contains(target.endContainer)) {
|
|
741
|
+
from = this.calculateOffset(target.startContainer, target.startOffset);
|
|
742
|
+
to = this.calculateOffset(target.endContainer, target.endOffset);
|
|
743
|
+
} else if (sel) {
|
|
744
|
+
from = sel.from;
|
|
745
|
+
to = sel.to;
|
|
746
|
+
} else {
|
|
747
|
+
return true;
|
|
378
748
|
}
|
|
749
|
+
if (to < from) [from, to] = [to, from];
|
|
750
|
+
from = Math.max(0, Math.min(from, this.text.length));
|
|
751
|
+
to = Math.max(from, Math.min(to, this.text.length));
|
|
752
|
+
if (from === to && !text) return true;
|
|
753
|
+
const marks = from < to ? this.#marksAt(from) : null;
|
|
754
|
+
if (to > from) this.delete({ index: from, length: to - from });
|
|
755
|
+
this.#insertWithMarks(from, text, marks);
|
|
756
|
+
this.nabu.storedMarks = null;
|
|
757
|
+
this.block.commit();
|
|
758
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, from + text.length));
|
|
759
|
+
return true;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* `insertFromYank` (Emacs-style yank on macOS): the text is inserted as plain text at the caret, replacing the selection.
|
|
764
|
+
* No input rule runs (it is a paste, not typing).
|
|
765
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
766
|
+
*/
|
|
767
|
+
handleInsertFromYank(event, sel = this.selection) {
|
|
768
|
+
if (!sel) return;
|
|
769
|
+
const text = event.data || event.dataTransfer?.getData?.('text/plain') || '';
|
|
770
|
+
if (!text) return true;
|
|
771
|
+
if (!sel.isCollapsed) this.delete({ index: sel.from, length: sel.to - sel.from });
|
|
772
|
+
this.insert(sel.from, text);
|
|
773
|
+
this.nabu.storedMarks = null;
|
|
774
|
+
this.block.commit();
|
|
775
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, sel.from + text.length));
|
|
776
|
+
return true;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* `insertTranspose` (macOS Ctrl+T): swaps the two graphemes around the caret; at the end of the text, the last two.
|
|
781
|
+
* Marks travel with their character. No-op with a selection, at the start, with a single character or across a line break.
|
|
782
|
+
* @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
|
|
783
|
+
*/
|
|
784
|
+
handleInsertTranspose(event, sel = this.selection) {
|
|
785
|
+
if (!sel || !sel.isCollapsed) return true;
|
|
786
|
+
const text = this.text;
|
|
787
|
+
const end = sel.from >= text.length ? text.length : sel.from + nextGraphemeLength(text, sel.from);
|
|
788
|
+
const middle = end - prevGraphemeLength(text, end); // boundary between the two graphemes
|
|
789
|
+
const start = middle - prevGraphemeLength(text, middle);
|
|
790
|
+
if (middle <= start || end <= middle) return true;
|
|
791
|
+
const left = text.slice(start, middle);
|
|
792
|
+
const right = text.slice(middle, end);
|
|
793
|
+
if (left === '\n' || right === '\n') return true;
|
|
794
|
+
const leftMarks = this.#marksAt(start);
|
|
795
|
+
const rightMarks = this.#marksAt(middle);
|
|
796
|
+
this.delete({ index: start, length: end - start });
|
|
797
|
+
this.#insertWithMarks(start, right, rightMarks);
|
|
798
|
+
this.#insertWithMarks(start + right.length, left, leftMarks);
|
|
799
|
+
this.block.commit();
|
|
800
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, end));
|
|
379
801
|
return true;
|
|
380
802
|
}
|
|
381
803
|
|
|
@@ -400,6 +822,7 @@ export class TextBehavior {
|
|
|
400
822
|
* Retrouve le nœud texte et l'offset DOM pour un offset Modèle donné
|
|
401
823
|
* @param {number} targetOffset
|
|
402
824
|
* @param {HTMLElement?} [element]
|
|
825
|
+
* @public
|
|
403
826
|
*/
|
|
404
827
|
getDOMPoint(targetOffset, element = this.block.element) {
|
|
405
828
|
if (!element) return null;
|
|
@@ -421,12 +844,21 @@ export class TextBehavior {
|
|
|
421
844
|
return { node: element, offset: element.childNodes.length };
|
|
422
845
|
}
|
|
423
846
|
|
|
424
|
-
/**
|
|
847
|
+
/**
|
|
848
|
+
* @param {number} index
|
|
849
|
+
* @param {string} text
|
|
850
|
+
* @public
|
|
851
|
+
*/
|
|
425
852
|
insert(index, text) {
|
|
426
|
-
|
|
853
|
+
// Never past the end of the text, whatever the caller computed (a stale DOM offset would panic Loro).
|
|
854
|
+
this.container.insert(Math.max(0, Math.min(index, this.container.length)), text);
|
|
427
855
|
}
|
|
428
856
|
|
|
429
|
-
/**
|
|
857
|
+
/**
|
|
858
|
+
* @param {Parameters<Block["delete"]>[0]} [deletion]
|
|
859
|
+
* @param {ReturnType<TextBehavior["getSelection"]>} [selection]
|
|
860
|
+
* @public
|
|
861
|
+
*/
|
|
430
862
|
delete(deletion, selection = this.selection) {
|
|
431
863
|
const l = this.container.length;
|
|
432
864
|
let from = deletion?.from ?? selection?.from ?? 0;
|
|
@@ -438,7 +870,10 @@ export class TextBehavior {
|
|
|
438
870
|
this.container.delete(index, length);
|
|
439
871
|
}
|
|
440
872
|
|
|
441
|
-
/**
|
|
873
|
+
/**
|
|
874
|
+
* @param {import('loro-crdt').Delta<string>[]} data
|
|
875
|
+
* @public
|
|
876
|
+
*/
|
|
442
877
|
applyDelta(data = []) {
|
|
443
878
|
this.container.applyDelta(data);
|
|
444
879
|
}
|
|
@@ -447,6 +882,7 @@ export class TextBehavior {
|
|
|
447
882
|
* @param {Parameters<Block["split"]>[0]} [options]
|
|
448
883
|
* @param {ReturnType<TextBehavior["getSelection"]>} [selection]
|
|
449
884
|
* @returns {ReturnType<Block["split"]>}
|
|
885
|
+
* @public
|
|
450
886
|
*/
|
|
451
887
|
split(options, selection = this.selection) {
|
|
452
888
|
const sel = selection;
|
|
@@ -457,19 +893,37 @@ export class TextBehavior {
|
|
|
457
893
|
return this.block.ascend("onSplit", null, { offset: from, delta: this.container.sliceDelta(from, to)});
|
|
458
894
|
}
|
|
459
895
|
|
|
460
|
-
/**
|
|
896
|
+
/**
|
|
897
|
+
* @param {string} markName
|
|
898
|
+
* @param {any} value
|
|
899
|
+
* @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
|
|
900
|
+
* @public
|
|
901
|
+
*/
|
|
461
902
|
applyMark(markName, value, sel) {
|
|
462
903
|
if (!sel || sel.isCollapsed) return;
|
|
904
|
+
// Model guard: an unsafe link (javascript:…) never enters the document through any mark API.
|
|
905
|
+
if (markName === 'link' && sanitizeUrl(value, { kind: 'link' }) === null) {
|
|
906
|
+
this.nabu.warn('applyMark: refused unsafe link href', value);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
463
909
|
this.container.mark({ start: sel.from, end: sel.to }, markName, value);
|
|
464
910
|
}
|
|
465
911
|
|
|
466
|
-
/**
|
|
912
|
+
/**
|
|
913
|
+
* @param {string} markName
|
|
914
|
+
* @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
|
|
915
|
+
* @public
|
|
916
|
+
*/
|
|
467
917
|
removeMark(markName, sel) {
|
|
468
918
|
if (!sel || sel.isCollapsed) return;
|
|
469
919
|
this.container.unmark({ start: sel.from, end: sel.to }, markName);
|
|
470
920
|
}
|
|
471
921
|
|
|
472
|
-
/**
|
|
922
|
+
/**
|
|
923
|
+
* @param {string} markName
|
|
924
|
+
* @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
|
|
925
|
+
* @public
|
|
926
|
+
*/
|
|
473
927
|
isMarkActive(markName, sel) {
|
|
474
928
|
if (!sel || sel.isCollapsed) return false;
|
|
475
929
|
const delta = this.container.toDelta();
|
|
@@ -485,7 +939,12 @@ export class TextBehavior {
|
|
|
485
939
|
return true;
|
|
486
940
|
}
|
|
487
941
|
|
|
488
|
-
/**
|
|
942
|
+
/**
|
|
943
|
+
* @param {string} markName
|
|
944
|
+
* @param {any} value
|
|
945
|
+
* @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
|
|
946
|
+
* @public
|
|
947
|
+
*/
|
|
489
948
|
toggleMark(markName, value, sel) {
|
|
490
949
|
if (!sel || sel.isCollapsed) return;
|
|
491
950
|
if (this.isMarkActive(markName, sel)) {
|
|
@@ -495,14 +954,17 @@ export class TextBehavior {
|
|
|
495
954
|
}
|
|
496
955
|
}
|
|
497
956
|
|
|
498
|
-
/** @
|
|
499
|
-
|
|
500
|
-
|
|
957
|
+
/** @param {{ rawBreaks?: boolean }} [options] see {@link deltaToMarkdown}
|
|
958
|
+
* @public
|
|
959
|
+
* @returns {string} */
|
|
960
|
+
toMarkdown(options) {
|
|
961
|
+
return deltaToMarkdown(this.delta, options);
|
|
501
962
|
}
|
|
502
963
|
|
|
503
964
|
/**
|
|
504
965
|
* Converts the text delta to a Slate-like JSON format.
|
|
505
966
|
* @returns {{text: string, [mark: string]: any}[]}
|
|
967
|
+
* @public
|
|
506
968
|
*/
|
|
507
969
|
toJSON() {
|
|
508
970
|
return this.delta
|
|
@@ -516,8 +978,9 @@ export class TextBehavior {
|
|
|
516
978
|
|
|
517
979
|
/**
|
|
518
980
|
* Serializes a (partial) range of this block's text as a PasteBlock.
|
|
519
|
-
* @param {{ from?: number, to?: number, partial?: 'start'|'end'|'both'|false, props?: Record<string,any> }} [context]
|
|
520
|
-
* @returns {import('
|
|
981
|
+
* @param {{ from?: number, to?: number | null, partial?: 'start'|'end'|'both'|false, props?: Record<string,any> }} [context]
|
|
982
|
+
* @returns {import('../../utils/extensions.js').PasteBlock}
|
|
983
|
+
* @public
|
|
521
984
|
*/
|
|
522
985
|
toClipboardBlock({ from = 0, to = null, partial = false, props = {} } = {}) {
|
|
523
986
|
const end = to ?? this.container.length;
|
|
@@ -529,7 +992,10 @@ export class TextBehavior {
|
|
|
529
992
|
};
|
|
530
993
|
}
|
|
531
994
|
|
|
532
|
-
/**
|
|
995
|
+
/**
|
|
996
|
+
* @param {Block} other
|
|
997
|
+
* @public
|
|
998
|
+
*/
|
|
533
999
|
absorbs(other) {
|
|
534
1000
|
const otherBehavior = other.behaviors.get("text");
|
|
535
1001
|
if (!otherBehavior || !(otherBehavior instanceof TextBehavior)) return false;
|