docblocks-react-ui 0.9.0 → 0.9.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.
@@ -3004,97 +3004,424 @@ function editableOfNode$1(node) {
3004
3004
  return (node === null ? null : node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[contenteditable=\"true\"]") ?? null;
3005
3005
  }
3006
3006
  //#endregion
3007
- //#region src/editing/block-commands/utils/focus.ts
3008
- /** Run `fn` in the next animation frame (setTimeout where frames do not exist). */
3009
- function afterFrame(fn) {
3010
- if (typeof requestAnimationFrame === "function") requestAnimationFrame(fn);
3011
- else setTimeout(fn, 0);
3007
+ //#region src/editing/selection-mapping.ts
3008
+ let writerAnchorHint = null;
3009
+ /** The degenerate seat's intended anchor's record (the mapping's reverse's stand). */
3010
+ function setWriterAnchorHint(root, anchorNode, anchorOffset, startNode, startOffset, endNode, endOffset) {
3011
+ writerAnchorHint = {
3012
+ root,
3013
+ anchorNode,
3014
+ anchorOffset,
3015
+ startNode,
3016
+ startOffset,
3017
+ endNode,
3018
+ endOffset
3019
+ };
3020
+ }
3021
+ /** The root's live hint over the exact-match seat (the staleness's no-stand). */
3022
+ function writerAnchorHintFor(root, range) {
3023
+ const hint = writerAnchorHint;
3024
+ if (hint === null || hint.root !== root) return null;
3025
+ if (hint.startNode !== range.startContainer || hint.startOffset !== range.startOffset) return null;
3026
+ if (hint.endNode !== range.endContainer || hint.endOffset !== range.endOffset) return null;
3027
+ if (hint.anchorNode !== range.endContainer || hint.anchorOffset !== range.endOffset) return null;
3028
+ return hint;
3012
3029
  }
3013
3030
  /**
3014
- * The live scope of a caret/selection seat. The captured editor root may
3015
- * have been replaced by the very gesture that scheduled the seat (a
3016
- * structural move remounts the subtree, and the captured element detaches):
3017
- * a detached scope finds nothing, so the document is the fallback (the
3018
- * caller's uniqueness / connectedness guards still apply).
3031
+ * Map the DOM selection to a core Selection for one editor root.
3032
+ *
3033
+ * Contract:
3034
+ * - a selection with both endpoints in one text block maps to the per-block
3035
+ * text range (a caret when collapsed);
3036
+ * - a selection with endpoints in (possibly different) text blocks maps to
3037
+ * the text range over the resolved points;
3038
+ * - an endpoint in a non-text region (image, divider, table, …) resolves to
3039
+ * the nearest text boundary in reading order: the document-order-first
3040
+ * endpoint to the END of the nearest preceding text block (or the START
3041
+ * of the nearest following one when there is no preceding one), the
3042
+ * document-order-last endpoint the other way around; a range that reaches
3043
+ * into a non-text region only through its endpoints (the range itself
3044
+ * spans a text block) is resolved the same way;
3045
+ * - a selection touching no text block maps to a `blocks` selection over
3046
+ * the blocks the range touches (no per-block text range);
3047
+ * - a selection inside a nested editor (a sync-embed) or outside the
3048
+ * editor root maps to `none` (the nested editor owns the selection);
3049
+ * - a selection whose endpoint stands in the empty-cell activation layer
3050
+ * maps to `none` (the layer holds a view-local caret — the cell holds no
3051
+ * doc blocks while the layer stands);
3052
+ * - `reverse` comes from the anchor/focus order (a right-to-left drag).
3053
+ *
3054
+ * The engine fills the cross-block `blocks` chain on `set` — the mapping
3055
+ * never computes it. Offsets of boundary endpoints come from the doc
3056
+ * (getTextLength), not a DOM text walk.
3019
3057
  */
3020
- function liveScope(scope) {
3021
- return scope instanceof Element && !scope.isConnected ? document : scope;
3058
+ function mapDomSelection(root, domSelection, doc) {
3059
+ if (domSelection === null || domSelection.rangeCount === 0) return { kind: "none" };
3060
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = domSelection;
3061
+ if (anchorNode === null || focusNode === null) return { kind: "none" };
3062
+ if (!root.contains(anchorNode) || !root.contains(focusNode)) return { kind: "none" };
3063
+ if (!ownScopeOf(anchorNode, root) || !ownScopeOf(focusNode, root)) return { kind: "none" };
3064
+ if (inActivationLayer(anchorNode) || inActivationLayer(focusNode)) return { kind: "none" };
3065
+ if (inDatabaseBlock(anchorNode) || inDatabaseBlock(focusNode)) return { kind: "none" };
3066
+ const range = domSelection.getRangeAt(0);
3067
+ const anchorBlock = textBlockOf(anchorNode, root);
3068
+ const focusBlock = textBlockOf(focusNode, root);
3069
+ if ((anchorNode instanceof Element ? anchorNode : anchorNode.parentElement ?? null)?.closest("[data-slot=\"docblocks/canvas-view\"]") !== null && anchorBlock === null && editableOfNode(anchorNode) === null) return { kind: "none" };
3070
+ const startEditable = editableOfNode(range.startContainer);
3071
+ const endEditable = range.startContainer === range.endContainer ? startEditable : editableOfNode(range.endContainer);
3072
+ if (startEditable !== null && endEditable !== null && startEditable !== endEditable) {
3073
+ const first = {
3074
+ node: range.startContainer,
3075
+ offset: range.startOffset,
3076
+ textBlock: textBlockOf(range.startContainer, root)
3077
+ };
3078
+ const last = {
3079
+ node: range.endContainer,
3080
+ offset: range.endOffset,
3081
+ textBlock: textBlockOf(range.endContainer, root)
3082
+ };
3083
+ if (first.textBlock === null && last.textBlock === null && !rangeTouchesTextBlock(root, range)) return mapBlocksSelection(root, domSelection, anchorBlock);
3084
+ const from = resolveEndpoint(doc, root, first, "first");
3085
+ const to = resolveEndpoint(doc, root, last, "last");
3086
+ if (from === null || to === null) return mapBlocksSelection(root, domSelection, anchorBlock);
3087
+ if (from.blockId === to.blockId && from.offset === to.offset) return {
3088
+ kind: "text",
3089
+ from,
3090
+ to: null
3091
+ };
3092
+ let anchorIsFirst = range.startContainer === anchorNode && range.startOffset === anchorOffset;
3093
+ if (anchorIsFirst && writerAnchorHintFor(root, range) !== null) anchorIsFirst = false;
3094
+ return {
3095
+ kind: "text",
3096
+ from,
3097
+ to,
3098
+ ...!anchorIsFirst ? { reverse: true } : {}
3099
+ };
3100
+ }
3101
+ if (anchorBlock !== null && focusBlock === anchorBlock) return mapTextSelection(anchorBlock, anchorNode, anchorOffset, focusNode, focusOffset);
3102
+ let anchorIsFirst = range.startContainer === anchorNode && range.startOffset === anchorOffset;
3103
+ if (anchorIsFirst && writerAnchorHintFor(root, range) !== null) anchorIsFirst = false;
3104
+ const first = {
3105
+ node: anchorIsFirst ? anchorNode : focusNode,
3106
+ offset: anchorIsFirst ? anchorOffset : focusOffset,
3107
+ textBlock: anchorIsFirst ? anchorBlock : focusBlock
3108
+ };
3109
+ const last = {
3110
+ node: anchorIsFirst ? focusNode : anchorNode,
3111
+ offset: anchorIsFirst ? focusOffset : anchorOffset,
3112
+ textBlock: anchorIsFirst ? focusBlock : anchorBlock
3113
+ };
3114
+ if (first.textBlock === null && last.textBlock === null && !rangeTouchesTextBlock(root, range)) return mapBlocksSelection(root, domSelection, anchorBlock);
3115
+ const from = resolveEndpoint(doc, root, first, "first");
3116
+ const to = resolveEndpoint(doc, root, last, "last");
3117
+ if (from === null || to === null) return mapBlocksSelection(root, domSelection, anchorBlock);
3118
+ if (from.blockId === to.blockId && from.offset === to.offset) return {
3119
+ kind: "text",
3120
+ from,
3121
+ to: null
3122
+ };
3123
+ return {
3124
+ kind: "text",
3125
+ from,
3126
+ to,
3127
+ ...!anchorIsFirst ? { reverse: true } : {}
3128
+ };
3022
3129
  }
3023
3130
  /**
3024
- * Move the browser caret into a block's inner editable at the flat offset
3025
- * (DOM-only: the doc is untouched). Schedule it for the frame after a
3026
- * structural gesture (the element must be rendered); `scope` confines the
3027
- * lookup to one editor root (a page can render the same doc in several).
3131
+ * Whether the endpoint stands inside the empty-cell activation layer: the
3132
+ * endpoint is the layer itself or a node it contains (the layer's text is
3133
+ * local, never doc-derived).
3028
3134
  */
3029
- function focusCaretIn(blockId, offset, scope = document, guard) {
3030
- afterFrame(() => {
3031
- if (guard !== void 0 && !guard()) return;
3032
- const el = Array.from(liveScope(scope).querySelectorAll(`[data-block-id="${CSS.escape(blockId)}"][data-slot="docblocks/block-content"]`)).find((candidate) => !candidate.closest("[data-slot=\"docblocks/frame-window-content\"]")) ?? null;
3033
- if (el === null || !el.isConnected) return;
3034
- el.focus();
3035
- restoreSelection(el, offset, null);
3036
- });
3135
+ function inActivationLayer(node) {
3136
+ return (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/cell-activation\"]") !== null;
3037
3137
  }
3038
3138
  /**
3039
- * The caret's seat into the EXACT editable element at the flat offset
3040
- * (the focusCaretIn's parity — the frame waits the caller's re-render's
3041
- * commit). The exact element's stand over the id's query: the canvas's
3042
- * frame windows render the block's inert copies over the same id (the
3043
- * query stands the copy — the frame's view-back order stands it first in
3044
- * the DOM), so the caller passes the hit's element (the elementFromPoint's
3045
- * resolution — the pointer-events-none's copy stands no hit).
3139
+ * Whether the endpoint sits inside a database block (the interactive
3140
+ * surface with its own cell selection; the cells AND the chrome — the
3141
+ * toolbar and the Add row / Add column buttons live outside the
3142
+ * `database-grid` scroller but inside the block, so the guard stands the
3143
+ * whole block). A DOM caret there carries no doc selection — the block's
3144
+ * own keys / gestures own the stand.
3046
3145
  */
3047
- function focusCaretInElement(el, offset) {
3048
- afterFrame(() => {
3049
- if (!el.isConnected) return;
3050
- el.focus();
3051
- restoreSelection(el, offset, null);
3052
- });
3146
+ function inDatabaseBlock(node) {
3147
+ return (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/database\"]") !== null;
3148
+ }
3149
+ /** A selection with both endpoints in one text block. */
3150
+ function mapTextSelection(block, anchorNode, anchorOffset, focusNode, focusOffset) {
3151
+ const anchor = caretOffsetIn(block, anchorNode, anchorOffset);
3152
+ const focus = caretOffsetIn(block, focusNode, focusOffset);
3153
+ const reverse = focus < anchor;
3154
+ const start = reverse ? focus : anchor;
3155
+ const end = reverse ? anchor : focus;
3156
+ const blockId = block.dataset.blockId;
3157
+ return {
3158
+ kind: "text",
3159
+ from: {
3160
+ blockId,
3161
+ offset: start
3162
+ },
3163
+ to: start === end ? null : {
3164
+ blockId,
3165
+ offset: end
3166
+ },
3167
+ ...reverse ? { reverse: true } : {}
3168
+ };
3053
3169
  }
3054
3170
  /**
3055
- * Focus the empty-cell activation layer of a table cell: the local
3056
- * editable that holds the caret while the cell holds no blocks (the first
3057
- * input materializes the paragraph). The layer is not a doc block, so the
3058
- * seat is a plain focus of the element (the caret lands at the start of
3059
- * the empty layer). Like focusCaretIn the query is scoped to one editor
3060
- * root.
3171
+ * Resolve one endpoint to a text point. An endpoint inside a text block is
3172
+ * its caret offset there. An endpoint in a non-text region takes the
3173
+ * nearest text boundary in reading order per the endpoint's role (see the
3174
+ * module header). Null when no boundary exists in either fallback direction.
3061
3175
  */
3062
- function focusCellActivation(cellId, scope = document) {
3063
- afterFrame(() => {
3064
- const activation = liveScope(scope).querySelector(`[data-slot="docblocks/table-cell"][data-block-id="${CSS.escape(cellId)}"]`)?.querySelector("[data-slot=\"docblocks/cell-activation\"]");
3065
- if (activation == null || !activation.isConnected) return;
3066
- activation.focus();
3067
- });
3176
+ function resolveEndpoint(doc, root, endpoint, role) {
3177
+ if (endpoint.textBlock !== null) return {
3178
+ blockId: endpoint.textBlock.dataset.blockId,
3179
+ offset: caretOffsetIn(endpoint.textBlock, endpoint.node, endpoint.offset)
3180
+ };
3181
+ const blocks = textBlockElementsIn(root);
3182
+ if (role === "first") {
3183
+ const preceding = nearestBefore(endpoint.node, blocks);
3184
+ if (preceding !== null) return {
3185
+ blockId: blockIdOf(preceding),
3186
+ offset: doc.getTextLength(blockIdOf(preceding))
3187
+ };
3188
+ const following = nearestAfter(endpoint.node, blocks);
3189
+ return following === null ? null : {
3190
+ blockId: blockIdOf(following),
3191
+ offset: 0
3192
+ };
3193
+ }
3194
+ const following = nearestAfter(endpoint.node, blocks);
3195
+ if (following !== null) return {
3196
+ blockId: blockIdOf(following),
3197
+ offset: 0
3198
+ };
3199
+ const preceding = nearestBefore(endpoint.node, blocks);
3200
+ return preceding === null ? null : {
3201
+ blockId: blockIdOf(preceding),
3202
+ offset: doc.getTextLength(blockIdOf(preceding))
3203
+ };
3068
3204
  }
3069
- /** The parent block id per the DOM: the wrapper above the block's own wrapper; null at the doc root. */
3070
- function domParentBlockIdOf(el) {
3071
- return (el.parentElement?.closest("[data-block-id]"))?.parentElement?.closest("[data-block-id]")?.dataset.blockId ?? null;
3205
+ /** The block id of a text-editable element. */
3206
+ function blockIdOf(element) {
3207
+ return element.dataset.blockId;
3072
3208
  }
3073
- /**
3074
- * Whether the candidate inner is the SURVIVOR of the remount, not a framer
3075
- * exit clone. On a wrapper-tag swap (list-item in/out) the exit clone
3076
- * renders the block's NEW type at the OLD position — a wrong wrapper tag
3077
- * for the new type in one shape of the view, or a twin candidate (the
3078
- * count check's ambiguity stand) in the other. The survivor stands in a
3079
- * wrapper that matches the new type: a list-item in its li (the motion
3080
- * view's li stands directly under the row — the nesting is the indent
3081
- * data, no list wrapper — and the base view's li in the list run), any
3082
- * other type in a div.
3083
- */
3084
- function isSurvivorInner(el, blockType) {
3085
- const wrapper = el.parentElement;
3086
- if (blockType === "list-item") return wrapper?.tagName === "LI";
3087
- return wrapper?.tagName === "DIV";
3209
+ /** A selection spanning blocks: the touched block ids in document order. */
3210
+ function mapBlocksSelection(root, domSelection, anchorBlock) {
3211
+ const range = domSelection.getRangeAt(0);
3212
+ const ids = [];
3213
+ for (const element of Array.from(root.querySelectorAll("[data-block-id]"))) {
3214
+ const blockId = element.dataset.blockId;
3215
+ if (ids.includes(blockId)) continue;
3216
+ if (range.intersectsNode(element)) ids.push(blockId);
3217
+ }
3218
+ if (ids.length === 0) return { kind: "none" };
3219
+ const anchorId = anchorBlock !== null ? anchorBlock.dataset.blockId : ids[0];
3220
+ return {
3221
+ kind: "blocks",
3222
+ ids,
3223
+ anchorId: ids.includes(anchorId) ? anchorId : ids[0]
3224
+ };
3088
3225
  }
3089
- /** Whether the DOM selection's endpoints sit in (or on) the element. */
3090
- function seatedIn(el) {
3091
- const sel = window.getSelection();
3092
- if (sel === null || sel.rangeCount === 0) return false;
3093
- const inOrOn = (node) => node !== null && (node === el || el.contains(node));
3094
- return inOrOn(sel.anchorNode) && inOrOn(sel.focusNode);
3226
+ /** Whether the range intersects a text-editable block of the editor. */
3227
+ function rangeTouchesTextBlock(root, range) {
3228
+ for (const element of textBlockElementsIn(root)) if (range.intersectsNode(element)) return true;
3229
+ return false;
3095
3230
  }
3096
3231
  /**
3097
- * Whether the DOM selection sits in the element AT the requested flat
3232
+ * The text-editable blocks of the editor's OWN scope (contenteditable
3233
+ * [data-block-id], in DOM order). Blocks of a nested editor (a sync-embed
3234
+ * rendering another doc) are excluded: a boundary resolved to a foreign
3235
+ * block id would not exist in this doc's `doc`, so the mapping must never
3236
+ * consider them (compare the `ownScopeOf` endpoint guard in
3237
+ * `mapDomSelection`).
3238
+ */
3239
+ function textBlockElementsIn(root) {
3240
+ return Array.from(root.querySelectorAll("[data-block-id]")).filter((element) => isTextBlockElement(element) && ownScopeOf(element, root));
3241
+ }
3242
+ /**
3243
+ * Whether the element is a text-editable block (the inner contenteditable
3244
+ * [data-block-id] element).
3245
+ */
3246
+ function isTextBlockElement(element) {
3247
+ return element.dataset.blockId !== void 0 && element.getAttribute("contenteditable") === "true";
3248
+ }
3249
+ /** The nearest text-editable block strictly before the node in reading order. */
3250
+ function nearestBefore(node, blocks) {
3251
+ for (let i = blocks.length - 1; i >= 0; i--) {
3252
+ const element = blocks[i];
3253
+ if (node.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING) return element;
3254
+ }
3255
+ return null;
3256
+ }
3257
+ /** The nearest text-editable block strictly after the node in reading order. */
3258
+ function nearestAfter(node, blocks) {
3259
+ for (const element of blocks) if (node.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING) return element;
3260
+ return null;
3261
+ }
3262
+ /**
3263
+ * Whether the node sits in the editor root's own scope: inside a deeper
3264
+ * nested editor root (a sync-embed rendering another doc) the node
3265
+ * belongs to that editor, not this one.
3266
+ */
3267
+ function ownScopeOf(node, root) {
3268
+ return ((node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/editor\"]") ?? null) === root;
3269
+ }
3270
+ /**
3271
+ * The closest text block (a contenteditable [data-block-id] element) that
3272
+ * contains the node; null when the node is in a non-text block or outside
3273
+ * the editor root.
3274
+ */
3275
+ function textBlockOf(node, root) {
3276
+ let current = node;
3277
+ while (current !== null && current !== root) {
3278
+ if (current instanceof HTMLElement && isTextBlockElement(current)) return current;
3279
+ current = current.parentNode;
3280
+ }
3281
+ return null;
3282
+ }
3283
+ /**
3284
+ * Structural equality over the fields a DOM mapping produces. The
3285
+ * engine-maintained `blocks` chain of a text selection is derived from
3286
+ * from/to, so it is not compared.
3287
+ */
3288
+ function selectionsEqual(a, b) {
3289
+ if (a.kind !== b.kind) return false;
3290
+ if (a.kind === "none") return true;
3291
+ if (a.kind === "blocks" && b.kind === "blocks") return a.anchorId === b.anchorId && a.ids.length === b.ids.length && a.ids.every((id, i) => id === b.ids[i]);
3292
+ if (a.kind === "text" && b.kind === "text") {
3293
+ if (a.from.blockId !== b.from.blockId || a.from.offset !== b.from.offset) return false;
3294
+ if (a.to === null !== (b.to === null)) return false;
3295
+ if (a.to !== null && b.to !== null && (a.to.blockId !== b.to.blockId || a.to.offset !== b.to.offset)) return false;
3296
+ return a.reverse === b.reverse;
3297
+ }
3298
+ return false;
3299
+ }
3300
+ /**
3301
+ * Map the DOM selection to the view at gesture time. The browser does not
3302
+ * reliably dispatch `selectionchange` for a cross-boundary selection (and
3303
+ * headless dispatch is flaky in general), so every gesture that re-bases
3304
+ * the DOM selection pushes the mapping to the view itself; the event-based
3305
+ * path then stands as the idempotent backstop.
3306
+ */
3307
+ function syncDomSelection(root, doc, view) {
3308
+ const next = mapDomSelection(root, window.getSelection(), doc);
3309
+ if (!selectionsEqual(next, view.get())) view.set(next);
3310
+ }
3311
+ /**
3312
+ * Whether the DOM selection's endpoints stand inside a block's editable
3313
+ * (of any editor root): the caret is live in an editable, so the
3314
+ * selection's mapping expresses a real edit position. A selection
3315
+ * collapsed outside the editables (the chrome, the stale residue) does
3316
+ * not — the mapping must not clobber a `blocks` view there. Neither does
3317
+ * a caret parked at a pure page-container position (the page's single
3318
+ * editable container is an editable, but the caret stands in no block —
3319
+ * the reseat's transient, the gutter's focus park).
3320
+ */
3321
+ function domSelectionInEditable(domSelection) {
3322
+ const inText = (node) => {
3323
+ const editable = editableOfNode(node);
3324
+ if (editable === null) return false;
3325
+ return editable.getAttribute("data-slot") !== "docblocks/page";
3326
+ };
3327
+ return inText(domSelection?.anchorNode ?? null) && inText(domSelection?.focusNode ?? null);
3328
+ }
3329
+ /** The contenteditable that owns a node (the node's element or its parent's), or null. */
3330
+ function editableOfNode(node) {
3331
+ return (node === null ? null : node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[contenteditable=\"true\"]") ?? null;
3332
+ }
3333
+ //#endregion
3334
+ //#region src/editing/block-commands/utils/focus.ts
3335
+ /** Run `fn` in the next animation frame (setTimeout where frames do not exist). */
3336
+ function afterFrame(fn) {
3337
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(fn);
3338
+ else setTimeout(fn, 0);
3339
+ }
3340
+ /**
3341
+ * The live scope of a caret/selection seat. The captured editor root may
3342
+ * have been replaced by the very gesture that scheduled the seat (a
3343
+ * structural move remounts the subtree, and the captured element detaches):
3344
+ * a detached scope finds nothing, so the document is the fallback (the
3345
+ * caller's uniqueness / connectedness guards still apply).
3346
+ */
3347
+ function liveScope(scope) {
3348
+ return scope instanceof Element && !scope.isConnected ? document : scope;
3349
+ }
3350
+ /**
3351
+ * Move the browser caret into a block's inner editable at the flat offset
3352
+ * (DOM-only: the doc is untouched). Schedule it for the frame after a
3353
+ * structural gesture (the element must be rendered); `scope` confines the
3354
+ * lookup to one editor root (a page can render the same doc in several).
3355
+ */
3356
+ function focusCaretIn(blockId, offset, scope = document, guard) {
3357
+ afterFrame(() => {
3358
+ if (guard !== void 0 && !guard()) return;
3359
+ const el = Array.from(liveScope(scope).querySelectorAll(`[data-block-id="${CSS.escape(blockId)}"][data-slot="docblocks/block-content"]`)).find((candidate) => !candidate.closest("[data-slot=\"docblocks/frame-window-content\"]")) ?? null;
3360
+ if (el === null || !el.isConnected) return;
3361
+ el.focus();
3362
+ restoreSelection(el, offset, null);
3363
+ });
3364
+ }
3365
+ /**
3366
+ * The caret's seat into the EXACT editable element at the flat offset
3367
+ * (the focusCaretIn's parity — the frame waits the caller's re-render's
3368
+ * commit). The exact element's stand over the id's query: the canvas's
3369
+ * frame windows render the block's inert copies over the same id (the
3370
+ * query stands the copy — the frame's view-back order stands it first in
3371
+ * the DOM), so the caller passes the hit's element (the elementFromPoint's
3372
+ * resolution — the pointer-events-none's copy stands no hit).
3373
+ */
3374
+ function focusCaretInElement(el, offset) {
3375
+ afterFrame(() => {
3376
+ if (!el.isConnected) return;
3377
+ el.focus();
3378
+ restoreSelection(el, offset, null);
3379
+ });
3380
+ }
3381
+ /**
3382
+ * Focus the empty-cell activation layer of a table cell: the local
3383
+ * editable that holds the caret while the cell holds no blocks (the first
3384
+ * input materializes the paragraph). The layer is not a doc block, so the
3385
+ * seat is a plain focus of the element (the caret lands at the start of
3386
+ * the empty layer). Like focusCaretIn the query is scoped to one editor
3387
+ * root.
3388
+ */
3389
+ function focusCellActivation(cellId, scope = document) {
3390
+ afterFrame(() => {
3391
+ const activation = liveScope(scope).querySelector(`[data-slot="docblocks/table-cell"][data-block-id="${CSS.escape(cellId)}"]`)?.querySelector("[data-slot=\"docblocks/cell-activation\"]");
3392
+ if (activation == null || !activation.isConnected) return;
3393
+ activation.focus();
3394
+ });
3395
+ }
3396
+ /** The parent block id per the DOM: the wrapper above the block's own wrapper; null at the doc root. */
3397
+ function domParentBlockIdOf(el) {
3398
+ return (el.parentElement?.closest("[data-block-id]"))?.parentElement?.closest("[data-block-id]")?.dataset.blockId ?? null;
3399
+ }
3400
+ /**
3401
+ * Whether the candidate inner is the SURVIVOR of the remount, not a framer
3402
+ * exit clone. On a wrapper-tag swap (list-item in/out) the exit clone
3403
+ * renders the block's NEW type at the OLD position — a wrong wrapper tag
3404
+ * for the new type in one shape of the view, or a twin candidate (the
3405
+ * count check's ambiguity stand) in the other. The survivor stands in a
3406
+ * wrapper that matches the new type: a list-item in its li (the motion
3407
+ * view's li stands directly under the row — the nesting is the indent
3408
+ * data, no list wrapper — and the base view's li in the list run), any
3409
+ * other type in a div.
3410
+ */
3411
+ function isSurvivorInner(el, blockType) {
3412
+ const wrapper = el.parentElement;
3413
+ if (blockType === "list-item") return wrapper?.tagName === "LI";
3414
+ return wrapper?.tagName === "DIV";
3415
+ }
3416
+ /** Whether the DOM selection's endpoints sit in (or on) the element. */
3417
+ function seatedIn(el) {
3418
+ const sel = window.getSelection();
3419
+ if (sel === null || sel.rangeCount === 0) return false;
3420
+ const inOrOn = (node) => node !== null && (node === el || el.contains(node));
3421
+ return inOrOn(sel.anchorNode) && inOrOn(sel.focusNode);
3422
+ }
3423
+ /**
3424
+ * Whether the DOM selection sits in the element AT the requested flat
3098
3425
  * offsets (a collapsed caret at `from`, a span over [from, to)). A
3099
3426
  * selection inside the element at a different seat (a competing re-seat's
3100
3427
  * transient — the container's re-seat lands at the block's edge while
@@ -3213,7 +3540,13 @@ function reseatHistorySelection(doc, view, scope = document) {
3213
3540
  * (`selection-mapping`'s cross-editable branch) reads the range there.
3214
3541
  * The direction's read-back stands the range's (the anchor reads as the
3215
3542
  * range's start): the core model is document-ordered, so the direction
3216
- * carries no behavior.
3543
+ * carries no behavior — except the writer's anchor's hint (the backward
3544
+ * cross seat's stand): the base stands the selection's anchor (the
3545
+ * gesture's fixed end), and the addRange's read-back flips the anchor to
3546
+ * the range's start (the far end), so the intended anchor (the base, the
3547
+ * range's end's stand) is recorded over the seat's endpoints for the
3548
+ * mapping's reverse's stand (the extension's chain reads the anchor from
3549
+ * the view's direction then, not the DOM's read-back).
3217
3550
  */
3218
3551
  function applyDomSelection(baseNode, baseOffset, focusNode, focusOffset) {
3219
3552
  const selection = window.getSelection();
@@ -3235,6 +3568,10 @@ function applyDomSelection(baseNode, baseOffset, focusNode, focusOffset) {
3235
3568
  }
3236
3569
  selection.removeAllRanges();
3237
3570
  selection.addRange(range);
3571
+ if (!baseFirst) {
3572
+ const root = editorRootOf(baseNode) ?? editorRootOf(focusNode);
3573
+ if (root !== null) setWriterAnchorHint(root, baseNode, baseOffset, focusNode, focusOffset, baseNode, baseOffset);
3574
+ }
3238
3575
  }
3239
3576
  /**
3240
3577
  * Re-base the browser's selection anchor at (anchorNode, anchorOffset) and
@@ -15968,498 +16305,365 @@ function htmlToBlocks(html) {
15968
16305
  cells.push(runsOf(cell, {}, false));
15969
16306
  }
15970
16307
  if (cells.length > 0) rows.push(cells);
15971
- }
15972
- if (rows.length === 0) return;
15973
- const cols = Math.max(...rows.map((row) => row.length));
15974
- for (const row of rows) while (row.length < cols) row.push([]);
15975
- blocks.push({
15976
- type: "table",
15977
- indent,
15978
- attrs: { cols },
15979
- runs: [],
15980
- rows
15981
- });
15982
- return;
15983
- }
15984
- case "P":
15985
- pushBlock("paragraph", indent, {}, blockRunsOf(element, tag));
15986
- return;
15987
- case "ADDRESS":
15988
- case "ARTICLE":
15989
- case "ASIDE":
15990
- case "DD":
15991
- case "DIV":
15992
- case "DL":
15993
- case "DT":
15994
- case "FIELDSET":
15995
- case "FIGCAPTION":
15996
- case "FIGURE":
15997
- case "FOOTER":
15998
- case "HEADER":
15999
- case "MAIN":
16000
- case "NAV":
16001
- case "SECTION": {
16002
- let inline = [];
16003
- const flushInline = () => {
16004
- const runs = dropEdgeWhitespaceRuns(inline);
16005
- inline = [];
16006
- if (runs.length > 0) pushBlock("paragraph", indent, {}, runs);
16007
- };
16008
- for (const child of Array.from(element.childNodes)) if (child.nodeType === Node.ELEMENT_NODE) {
16009
- const childElement = child;
16010
- const childTag = childElement.nodeName.toUpperCase();
16011
- if (isLineAnchor(childElement)) continue;
16012
- if (childTag === "SCRIPT" || childTag === "STYLE") continue;
16013
- if (BLOCK_LEVEL_TAGS.has(childTag)) {
16014
- flushInline();
16015
- visitBlock(childElement, indent);
16016
- continue;
16017
- }
16018
- for (const run of runsOf(childElement, {}, false)) pushRun(inline, run.text, run.marks);
16019
- } else if (child.nodeType === Node.TEXT_NODE) {
16020
- const text = inlineTextOf(child.nodeValue ?? "", false);
16021
- if (text !== "") pushRun(inline, text, {});
16022
- }
16023
- flushInline();
16024
- return;
16025
- }
16026
- }
16027
- const runs = blockRunsOf(element, tag);
16028
- if (runs.length > 0) pushBlock("paragraph", indent, {}, runs);
16029
- };
16030
- for (const node of Array.from(parsed.body.childNodes)) {
16031
- if (node.nodeType === Node.TEXT_NODE) {
16032
- const text = inlineTextOf(node.nodeValue ?? "", false);
16033
- if (text !== "") pushRun(pending, text, {});
16034
- continue;
16035
- }
16036
- if (node.nodeType !== Node.ELEMENT_NODE) continue;
16037
- const element = node;
16038
- if (isLineAnchor(element)) continue;
16039
- const tag = element.nodeName.toUpperCase();
16040
- if (tag === "SCRIPT" || tag === "STYLE") continue;
16041
- if (BLOCK_LEVEL_TAGS.has(tag)) {
16042
- flushPending();
16043
- visitBlock(element, 0);
16044
- } else {
16045
- const runs = runsOf(element, {}, false);
16046
- for (const run of runs) pushRun(pending, run.text, run.marks);
16047
- }
16048
- }
16049
- flushPending();
16050
- return blocks;
16051
- }
16052
- /**
16053
- * The text content of a rich payload (the cell paste stands the plain text
16054
- * even for an HTML-only clipboard — the cell's data is plain text and the
16055
- * marks are dropped).
16056
- */
16057
- function plainTextOfHtml(html) {
16058
- return new DOMParser().parseFromString(html, "text/html").body?.textContent ?? "";
16059
- }
16060
- /**
16061
- * Apply a rich paste: the code target takes the raw text (no parsing, no
16062
- * marks); the page targets materialize the parsed blocks through the
16063
- * shared multi-block pipeline (the caret block split; the merge; the
16064
- * demotion; the re-based indents) — one transaction, one undo step.
16065
- * Returns the caret landing, or `null` when nothing was pasted.
16066
- */
16067
- function applyRichPaste(doc, blockId, from, to, html, opts) {
16068
- const block = doc.getBlock(blockId);
16069
- if (block === null) return null;
16070
- if (block.type === "code") {
16071
- const raw = rawTextOfHtml(html).replace(/\r\n?/g, "\n");
16072
- if (raw === "") return null;
16073
- doc.transact(() => {
16074
- if (to > from) doc.deleteText(blockId, from, to);
16075
- doc.insertText(blockId, from, raw);
16076
- });
16077
- return {
16078
- blockId,
16079
- offset: from + raw.length
16080
- };
16081
- }
16082
- return materializePaste(doc, blockId, from, to, htmlToBlocks(html), opts);
16083
- }
16084
- //#endregion
16085
- //#region src/editing/range-extend.ts
16086
- /**
16087
- * The keyboard extension of a cross-block text range: move the selection's
16088
- * focus end with the arrow / home / end keys.
16089
- *
16090
- * The browser cannot extend a DOM selection across a contenteditable
16091
- * boundary (a drag or a native shift+arrow stays inside the starting
16092
- * editable), so the editor owns the movement for a cross range: the focus
16093
- * end steps by one character (arrows) or to the block's edge (home / end),
16094
- * and steps across the edge into the adjacent chain block. The move
16095
- * re-bases the DOM selection with the anchor end standing; the
16096
- * selectionchange mapping then updates the view. A move with nothing left
16097
- * to extend (the range's edge) stands as a no-op. Returns whether the
16098
- * focus end moved (the caller suppresses the browser default then: the
16099
- * native extension would race the re-base).
16100
- */
16101
- function extendRangeFocusEnd(doc, selection, key) {
16102
- if (selection.kind !== "text" || selection.to === null) return false;
16103
- const domSelection = window.getSelection();
16104
- if (domSelection === null || domSelection.rangeCount === 0) return false;
16105
- const { anchorNode, anchorOffset } = domSelection;
16106
- if (anchorNode === null) return false;
16107
- const effective = effectiveFocusEnd(domSelection);
16108
- if (effective === null) return false;
16109
- const focusNode = effective.node;
16110
- const focusOffset = effective.offset;
16111
- const scope = editorRootOf(focusNode);
16112
- const focusBlock = textBlockOfNode(focusNode);
16113
- if (focusBlock === null) return false;
16114
- const focusBlockId = focusBlock.dataset.blockId;
16115
- const movable = focusBlockId === selection.to.blockId ? selection.to : focusBlockId === selection.from.blockId ? selection.from : null;
16116
- if (movable === null) return false;
16117
- const offset = caretOffsetIn(focusBlock, focusNode, focusOffset);
16118
- const length = doc.getTextLength(movable.blockId);
16119
- const chain = selection.blocks ?? [selection.from.blockId, selection.to.blockId];
16120
- const index = chain.indexOf(movable.blockId);
16121
- let next = null;
16122
- if (key === "ArrowRight") {
16123
- if (offset < length) next = {
16124
- blockId: movable.blockId,
16125
- offset: offset + 1
16126
- };
16127
- else {
16128
- const nextId = chain[index + 1];
16129
- if (nextId !== void 0) next = {
16130
- blockId: nextId,
16131
- offset: 0
16132
- };
16133
- }
16134
- } else if (key === "ArrowLeft") {
16135
- if (offset > 0) next = {
16136
- blockId: movable.blockId,
16137
- offset: offset - 1
16138
- };
16139
- else {
16140
- const prevId = chain[index - 1];
16141
- if (prevId !== void 0) next = {
16142
- blockId: prevId,
16143
- offset: doc.getTextLength(prevId)
16144
- };
16145
- }
16146
- } else if (key === "End") next = {
16147
- blockId: movable.blockId,
16148
- offset: length
16149
- };
16150
- else if (key === "Home") next = {
16151
- blockId: movable.blockId,
16152
- offset: 0
16153
- };
16154
- if (next === null) return false;
16155
- if (next.blockId === movable.blockId && next.offset === offset) return false;
16156
- const target = scope.querySelector(`[data-block-id="${CSS.escape(next.blockId)}"][data-slot="docblocks/block-content"]`);
16157
- if (target === null) return false;
16158
- const position = locatePosition(target, next.offset);
16159
- applyDomSelection(anchorNode, anchorOffset, position.node, position.offset);
16160
- return true;
16161
- }
16162
- //#endregion
16163
- //#region src/editing/selection-mapping.ts
16164
- /**
16165
- * Map the DOM selection to a core Selection for one editor root.
16166
- *
16167
- * Contract:
16168
- * - a selection with both endpoints in one text block maps to the per-block
16169
- * text range (a caret when collapsed);
16170
- * - a selection with endpoints in (possibly different) text blocks maps to
16171
- * the text range over the resolved points;
16172
- * - an endpoint in a non-text region (image, divider, table, …) resolves to
16173
- * the nearest text boundary in reading order: the document-order-first
16174
- * endpoint to the END of the nearest preceding text block (or the START
16175
- * of the nearest following one when there is no preceding one), the
16176
- * document-order-last endpoint the other way around; a range that reaches
16177
- * into a non-text region only through its endpoints (the range itself
16178
- * spans a text block) is resolved the same way;
16179
- * - a selection touching no text block maps to a `blocks` selection over
16180
- * the blocks the range touches (no per-block text range);
16181
- * - a selection inside a nested editor (a sync-embed) or outside the
16182
- * editor root maps to `none` (the nested editor owns the selection);
16183
- * - a selection whose endpoint stands in the empty-cell activation layer
16184
- * maps to `none` (the layer holds a view-local caret — the cell holds no
16185
- * doc blocks while the layer stands);
16186
- * - `reverse` comes from the anchor/focus order (a right-to-left drag).
16187
- *
16188
- * The engine fills the cross-block `blocks` chain on `set` — the mapping
16189
- * never computes it. Offsets of boundary endpoints come from the doc
16190
- * (getTextLength), not a DOM text walk.
16191
- */
16192
- function mapDomSelection(root, domSelection, doc) {
16193
- if (domSelection === null || domSelection.rangeCount === 0) return { kind: "none" };
16194
- const { anchorNode, anchorOffset, focusNode, focusOffset } = domSelection;
16195
- if (anchorNode === null || focusNode === null) return { kind: "none" };
16196
- if (!root.contains(anchorNode) || !root.contains(focusNode)) return { kind: "none" };
16197
- if (!ownScopeOf(anchorNode, root) || !ownScopeOf(focusNode, root)) return { kind: "none" };
16198
- if (inActivationLayer(anchorNode) || inActivationLayer(focusNode)) return { kind: "none" };
16199
- if (inDatabaseBlock(anchorNode) || inDatabaseBlock(focusNode)) return { kind: "none" };
16200
- const range = domSelection.getRangeAt(0);
16201
- const anchorBlock = textBlockOf(anchorNode, root);
16202
- const focusBlock = textBlockOf(focusNode, root);
16203
- if ((anchorNode instanceof Element ? anchorNode : anchorNode.parentElement ?? null)?.closest("[data-slot=\"docblocks/canvas-view\"]") !== null && anchorBlock === null && editableOfNode(anchorNode) === null) return { kind: "none" };
16204
- const startEditable = editableOfNode(range.startContainer);
16205
- const endEditable = range.startContainer === range.endContainer ? startEditable : editableOfNode(range.endContainer);
16206
- if (startEditable !== null && endEditable !== null && startEditable !== endEditable) {
16207
- const first = {
16208
- node: range.startContainer,
16209
- offset: range.startOffset,
16210
- textBlock: textBlockOf(range.startContainer, root)
16211
- };
16212
- const last = {
16213
- node: range.endContainer,
16214
- offset: range.endOffset,
16215
- textBlock: textBlockOf(range.endContainer, root)
16216
- };
16217
- if (first.textBlock === null && last.textBlock === null && !rangeTouchesTextBlock(root, range)) return mapBlocksSelection(root, domSelection, anchorBlock);
16218
- const from = resolveEndpoint(doc, root, first, "first");
16219
- const to = resolveEndpoint(doc, root, last, "last");
16220
- if (from === null || to === null) return mapBlocksSelection(root, domSelection, anchorBlock);
16221
- if (from.blockId === to.blockId && from.offset === to.offset) return {
16222
- kind: "text",
16223
- from,
16224
- to: null
16225
- };
16226
- return {
16227
- kind: "text",
16228
- from,
16229
- to,
16230
- ...!(range.startContainer === anchorNode && range.startOffset === anchorOffset) ? { reverse: true } : {}
16231
- };
16232
- }
16233
- if (anchorBlock !== null && focusBlock === anchorBlock) return mapTextSelection(anchorBlock, anchorNode, anchorOffset, focusNode, focusOffset);
16234
- const anchorIsFirst = range.startContainer === anchorNode && range.startOffset === anchorOffset;
16235
- const first = {
16236
- node: anchorIsFirst ? anchorNode : focusNode,
16237
- offset: anchorIsFirst ? anchorOffset : focusOffset,
16238
- textBlock: anchorIsFirst ? anchorBlock : focusBlock
16239
- };
16240
- const last = {
16241
- node: anchorIsFirst ? focusNode : anchorNode,
16242
- offset: anchorIsFirst ? focusOffset : anchorOffset,
16243
- textBlock: anchorIsFirst ? focusBlock : anchorBlock
16244
- };
16245
- if (first.textBlock === null && last.textBlock === null && !rangeTouchesTextBlock(root, range)) return mapBlocksSelection(root, domSelection, anchorBlock);
16246
- const from = resolveEndpoint(doc, root, first, "first");
16247
- const to = resolveEndpoint(doc, root, last, "last");
16248
- if (from === null || to === null) return mapBlocksSelection(root, domSelection, anchorBlock);
16249
- if (from.blockId === to.blockId && from.offset === to.offset) return {
16250
- kind: "text",
16251
- from,
16252
- to: null
16253
- };
16254
- return {
16255
- kind: "text",
16256
- from,
16257
- to,
16258
- ...!anchorIsFirst ? { reverse: true } : {}
16308
+ }
16309
+ if (rows.length === 0) return;
16310
+ const cols = Math.max(...rows.map((row) => row.length));
16311
+ for (const row of rows) while (row.length < cols) row.push([]);
16312
+ blocks.push({
16313
+ type: "table",
16314
+ indent,
16315
+ attrs: { cols },
16316
+ runs: [],
16317
+ rows
16318
+ });
16319
+ return;
16320
+ }
16321
+ case "P":
16322
+ pushBlock("paragraph", indent, {}, blockRunsOf(element, tag));
16323
+ return;
16324
+ case "ADDRESS":
16325
+ case "ARTICLE":
16326
+ case "ASIDE":
16327
+ case "DD":
16328
+ case "DIV":
16329
+ case "DL":
16330
+ case "DT":
16331
+ case "FIELDSET":
16332
+ case "FIGCAPTION":
16333
+ case "FIGURE":
16334
+ case "FOOTER":
16335
+ case "HEADER":
16336
+ case "MAIN":
16337
+ case "NAV":
16338
+ case "SECTION": {
16339
+ let inline = [];
16340
+ const flushInline = () => {
16341
+ const runs = dropEdgeWhitespaceRuns(inline);
16342
+ inline = [];
16343
+ if (runs.length > 0) pushBlock("paragraph", indent, {}, runs);
16344
+ };
16345
+ for (const child of Array.from(element.childNodes)) if (child.nodeType === Node.ELEMENT_NODE) {
16346
+ const childElement = child;
16347
+ const childTag = childElement.nodeName.toUpperCase();
16348
+ if (isLineAnchor(childElement)) continue;
16349
+ if (childTag === "SCRIPT" || childTag === "STYLE") continue;
16350
+ if (BLOCK_LEVEL_TAGS.has(childTag)) {
16351
+ flushInline();
16352
+ visitBlock(childElement, indent);
16353
+ continue;
16354
+ }
16355
+ for (const run of runsOf(childElement, {}, false)) pushRun(inline, run.text, run.marks);
16356
+ } else if (child.nodeType === Node.TEXT_NODE) {
16357
+ const text = inlineTextOf(child.nodeValue ?? "", false);
16358
+ if (text !== "") pushRun(inline, text, {});
16359
+ }
16360
+ flushInline();
16361
+ return;
16362
+ }
16363
+ }
16364
+ const runs = blockRunsOf(element, tag);
16365
+ if (runs.length > 0) pushBlock("paragraph", indent, {}, runs);
16259
16366
  };
16367
+ for (const node of Array.from(parsed.body.childNodes)) {
16368
+ if (node.nodeType === Node.TEXT_NODE) {
16369
+ const text = inlineTextOf(node.nodeValue ?? "", false);
16370
+ if (text !== "") pushRun(pending, text, {});
16371
+ continue;
16372
+ }
16373
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
16374
+ const element = node;
16375
+ if (isLineAnchor(element)) continue;
16376
+ const tag = element.nodeName.toUpperCase();
16377
+ if (tag === "SCRIPT" || tag === "STYLE") continue;
16378
+ if (BLOCK_LEVEL_TAGS.has(tag)) {
16379
+ flushPending();
16380
+ visitBlock(element, 0);
16381
+ } else {
16382
+ const runs = runsOf(element, {}, false);
16383
+ for (const run of runs) pushRun(pending, run.text, run.marks);
16384
+ }
16385
+ }
16386
+ flushPending();
16387
+ return blocks;
16260
16388
  }
16261
16389
  /**
16262
- * Whether the endpoint stands inside the empty-cell activation layer: the
16263
- * endpoint is the layer itself or a node it contains (the layer's text is
16264
- * local, never doc-derived).
16390
+ * The text content of a rich payload (the cell paste stands the plain text
16391
+ * even for an HTML-only clipboard — the cell's data is plain text and the
16392
+ * marks are dropped).
16265
16393
  */
16266
- function inActivationLayer(node) {
16267
- return (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/cell-activation\"]") !== null;
16394
+ function plainTextOfHtml(html) {
16395
+ return new DOMParser().parseFromString(html, "text/html").body?.textContent ?? "";
16268
16396
  }
16269
16397
  /**
16270
- * Whether the endpoint sits inside a database block (the interactive
16271
- * surface with its own cell selection; the cells AND the chrome — the
16272
- * toolbar and the Add row / Add column buttons live outside the
16273
- * `database-grid` scroller but inside the block, so the guard stands the
16274
- * whole block). A DOM caret there carries no doc selection — the block's
16275
- * own keys / gestures own the stand.
16398
+ * Apply a rich paste: the code target takes the raw text (no parsing, no
16399
+ * marks); the page targets materialize the parsed blocks through the
16400
+ * shared multi-block pipeline (the caret block split; the merge; the
16401
+ * demotion; the re-based indents) — one transaction, one undo step.
16402
+ * Returns the caret landing, or `null` when nothing was pasted.
16276
16403
  */
16277
- function inDatabaseBlock(node) {
16278
- return (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/database\"]") !== null;
16279
- }
16280
- /** A selection with both endpoints in one text block. */
16281
- function mapTextSelection(block, anchorNode, anchorOffset, focusNode, focusOffset) {
16282
- const anchor = caretOffsetIn(block, anchorNode, anchorOffset);
16283
- const focus = caretOffsetIn(block, focusNode, focusOffset);
16284
- const reverse = focus < anchor;
16285
- const start = reverse ? focus : anchor;
16286
- const end = reverse ? anchor : focus;
16287
- const blockId = block.dataset.blockId;
16288
- return {
16289
- kind: "text",
16290
- from: {
16291
- blockId,
16292
- offset: start
16293
- },
16294
- to: start === end ? null : {
16404
+ function applyRichPaste(doc, blockId, from, to, html, opts) {
16405
+ const block = doc.getBlock(blockId);
16406
+ if (block === null) return null;
16407
+ if (block.type === "code") {
16408
+ const raw = rawTextOfHtml(html).replace(/\r\n?/g, "\n");
16409
+ if (raw === "") return null;
16410
+ doc.transact(() => {
16411
+ if (to > from) doc.deleteText(blockId, from, to);
16412
+ doc.insertText(blockId, from, raw);
16413
+ });
16414
+ return {
16295
16415
  blockId,
16296
- offset: end
16297
- },
16298
- ...reverse ? { reverse: true } : {}
16299
- };
16300
- }
16301
- /**
16302
- * Resolve one endpoint to a text point. An endpoint inside a text block is
16303
- * its caret offset there. An endpoint in a non-text region takes the
16304
- * nearest text boundary in reading order per the endpoint's role (see the
16305
- * module header). Null when no boundary exists in either fallback direction.
16306
- */
16307
- function resolveEndpoint(doc, root, endpoint, role) {
16308
- if (endpoint.textBlock !== null) return {
16309
- blockId: endpoint.textBlock.dataset.blockId,
16310
- offset: caretOffsetIn(endpoint.textBlock, endpoint.node, endpoint.offset)
16311
- };
16312
- const blocks = textBlockElementsIn(root);
16313
- if (role === "first") {
16314
- const preceding = nearestBefore(endpoint.node, blocks);
16315
- if (preceding !== null) return {
16316
- blockId: blockIdOf(preceding),
16317
- offset: doc.getTextLength(blockIdOf(preceding))
16318
- };
16319
- const following = nearestAfter(endpoint.node, blocks);
16320
- return following === null ? null : {
16321
- blockId: blockIdOf(following),
16322
- offset: 0
16416
+ offset: from + raw.length
16323
16417
  };
16324
16418
  }
16325
- const following = nearestAfter(endpoint.node, blocks);
16326
- if (following !== null) return {
16327
- blockId: blockIdOf(following),
16328
- offset: 0
16329
- };
16330
- const preceding = nearestBefore(endpoint.node, blocks);
16331
- return preceding === null ? null : {
16332
- blockId: blockIdOf(preceding),
16333
- offset: doc.getTextLength(blockIdOf(preceding))
16334
- };
16335
- }
16336
- /** The block id of a text-editable element. */
16337
- function blockIdOf(element) {
16338
- return element.dataset.blockId;
16339
- }
16340
- /** A selection spanning blocks: the touched block ids in document order. */
16341
- function mapBlocksSelection(root, domSelection, anchorBlock) {
16342
- const range = domSelection.getRangeAt(0);
16343
- const ids = [];
16344
- for (const element of Array.from(root.querySelectorAll("[data-block-id]"))) {
16345
- const blockId = element.dataset.blockId;
16346
- if (ids.includes(blockId)) continue;
16347
- if (range.intersectsNode(element)) ids.push(blockId);
16348
- }
16349
- if (ids.length === 0) return { kind: "none" };
16350
- const anchorId = anchorBlock !== null ? anchorBlock.dataset.blockId : ids[0];
16351
- return {
16352
- kind: "blocks",
16353
- ids,
16354
- anchorId: ids.includes(anchorId) ? anchorId : ids[0]
16355
- };
16356
- }
16357
- /** Whether the range intersects a text-editable block of the editor. */
16358
- function rangeTouchesTextBlock(root, range) {
16359
- for (const element of textBlockElementsIn(root)) if (range.intersectsNode(element)) return true;
16360
- return false;
16419
+ return materializePaste(doc, blockId, from, to, htmlToBlocks(html), opts);
16361
16420
  }
16421
+ //#endregion
16422
+ //#region src/editing/keyboard/utils.ts
16423
+ /** The keyboard unit's helpers: the mark-toggle action, the sibling text
16424
+ * block lookup, the parent block id, and the cell descent target. */
16362
16425
  /**
16363
- * The text-editable blocks of the editor's OWN scope (contenteditable
16364
- * [data-block-id], in DOM order). Blocks of a nested editor (a sync-embed
16365
- * rendering another doc) are excluded: a boundary resolved to a foreign
16366
- * block id would not exist in this doc's `doc`, so the mapping must never
16367
- * consider them (compare the `ownScopeOf` endpoint guard in
16368
- * `mapDomSelection`).
16426
+ * The toggle decision for one mark over [from, to): "unset" when every run
16427
+ * overlapping the range already carries the mark, "set" otherwise. A
16428
+ * partially covered run counts only if it carries the mark. Reads the block
16429
+ * snapshot via `getBlock`; the caller issues the command.
16369
16430
  */
16370
- function textBlockElementsIn(root) {
16371
- return Array.from(root.querySelectorAll("[data-block-id]")).filter((element) => isTextBlockElement(element) && ownScopeOf(element, root));
16431
+ function markToggleAction(doc, blockId, from, to, mark) {
16432
+ const block = doc.getBlock(blockId);
16433
+ if (block === null || !("content" in block)) return "set";
16434
+ let pos = 0;
16435
+ let overlaps = false;
16436
+ for (const run of block.content ?? []) {
16437
+ const start = pos;
16438
+ pos += run.text.length;
16439
+ if (pos <= from || start >= to) continue;
16440
+ overlaps = true;
16441
+ if (run.marks[mark] !== true) return "set";
16442
+ }
16443
+ return overlaps ? "unset" : "set";
16372
16444
  }
16373
16445
  /**
16374
- * Whether the element is a text-editable block (the inner contenteditable
16375
- * [data-block-id] element).
16446
+ * The adjacent sibling a cross-block arrow can land in: the nearest
16447
+ * previous/next sibling whose type carries text content — non-text siblings
16448
+ * (divider, image, ...) are skipped. Null when nothing with content remains
16449
+ * in that direction.
16376
16450
  */
16377
- function isTextBlockElement(element) {
16378
- return element.dataset.blockId !== void 0 && element.getAttribute("contenteditable") === "true";
16379
- }
16380
- /** The nearest text-editable block strictly before the node in reading order. */
16381
- function nearestBefore(node, blocks) {
16382
- for (let i = blocks.length - 1; i >= 0; i--) {
16383
- const element = blocks[i];
16384
- if (node.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING) return element;
16451
+ function findSiblingTextBlock(doc, id, parentId, direction) {
16452
+ const siblings = doc.getChildren(parentId);
16453
+ const index = siblings.indexOf(id);
16454
+ if (index === -1) return null;
16455
+ const step = direction === "previous" ? -1 : 1;
16456
+ for (let i = index + step; i >= 0 && i < siblings.length; i += step) {
16457
+ const siblingId = siblings[i];
16458
+ if (siblingId === void 0) return null;
16459
+ const sibling = doc.getBlock(siblingId);
16460
+ if (sibling === null || !BLOCK_REGISTRY[sibling.type].content) continue;
16461
+ return {
16462
+ id: siblingId,
16463
+ length: doc.getTextLength(siblingId)
16464
+ };
16385
16465
  }
16386
16466
  return null;
16387
16467
  }
16388
- /** The nearest text-editable block strictly after the node in reading order. */
16389
- function nearestAfter(node, blocks) {
16390
- for (const element of blocks) if (node.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING) return element;
16391
- return null;
16392
- }
16393
16468
  /**
16394
- * Whether the node sits in the editor root's own scope: inside a deeper
16395
- * nested editor root (a sync-embed rendering another doc) the node
16396
- * belongs to that editor, not this one.
16397
- */
16398
- function ownScopeOf(node, root) {
16399
- return ((node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-slot=\"docblocks/editor\"]") ?? null) === root;
16400
- }
16401
- /**
16402
- * The closest text block (a contenteditable [data-block-id] element) that
16403
- * contains the node; null when the node is in a non-text block or outside
16404
- * the editor root.
16469
+ * The data parent of a focused text block (the container whose children
16470
+ * sequence the block stands in): the nearest block ancestor that actually
16471
+ * owns it as a child (the table cell over its content, the surface over
16472
+ * the canvas item). The flat page model's nesting is render-only (the
16473
+ * derived segment's DOM parent — the parent list item — is not the data
16474
+ * parent: the page content is the root's flat sequence), so a block with
16475
+ * no such ancestor stands at the document root.
16405
16476
  */
16406
- function textBlockOf(node, root) {
16407
- let current = node;
16408
- while (current !== null && current !== root) {
16409
- if (current instanceof HTMLElement && isTextBlockElement(current)) return current;
16410
- current = current.parentNode;
16477
+ function parentBlockIdOf(blockEl, doc) {
16478
+ const selfId = blockEl.dataset.blockId;
16479
+ if (selfId === void 0) return doc.meta.id;
16480
+ let current = blockEl.parentElement;
16481
+ while (current !== null) {
16482
+ const id = current.dataset.blockId;
16483
+ if (id !== void 0 && id !== selfId && doc.getBlock(id) !== null && doc.getChildren(id).includes(selfId)) return id;
16484
+ current = current.parentElement;
16411
16485
  }
16412
- return null;
16486
+ return doc.meta.id;
16413
16487
  }
16414
16488
  /**
16415
- * Structural equality over the fields a DOM mapping produces. The
16416
- * engine-maintained `blocks` chain of a text selection is derived from
16417
- * from/to, so it is not compared.
16489
+ * The down-edge descent of a focused text block's cell's own content
16490
+ * layer: the layer stands above the cell's children sequence, so the
16491
+ * first text child takes the caret (the row's sibling walk finds the next
16492
+ * cell instead). Null for every other block or edge.
16418
16493
  */
16419
- function selectionsEqual(a, b) {
16420
- if (a.kind !== b.kind) return false;
16421
- if (a.kind === "none") return true;
16422
- if (a.kind === "blocks" && b.kind === "blocks") return a.anchorId === b.anchorId && a.ids.length === b.ids.length && a.ids.every((id, i) => id === b.ids[i]);
16423
- if (a.kind === "text" && b.kind === "text") {
16424
- if (a.from.blockId !== b.from.blockId || a.from.offset !== b.from.offset) return false;
16425
- if (a.to === null !== (b.to === null)) return false;
16426
- if (a.to !== null && b.to !== null && (a.to.blockId !== b.to.blockId || a.to.offset !== b.to.offset)) return false;
16427
- return a.reverse === b.reverse;
16494
+ function cellDescendTarget(doc, focusBlockId) {
16495
+ const block = doc.getBlock(focusBlockId);
16496
+ if (block === null || block.type !== "table-cell") return null;
16497
+ for (const childId of doc.getChildren(focusBlockId)) {
16498
+ if (childId === void 0) return null;
16499
+ const child = doc.getBlock(childId);
16500
+ if (child === null || !BLOCK_REGISTRY[child.type].content) continue;
16501
+ return {
16502
+ id: childId,
16503
+ length: doc.getTextLength(childId)
16504
+ };
16428
16505
  }
16429
- return false;
16506
+ return null;
16430
16507
  }
16508
+ //#endregion
16509
+ //#region src/editing/range-extend.ts
16431
16510
  /**
16432
- * Map the DOM selection to the view at gesture time. The browser does not
16433
- * reliably dispatch `selectionchange` for a cross-boundary selection (and
16434
- * headless dispatch is flaky in general), so every gesture that re-bases
16435
- * the DOM selection pushes the mapping to the view itself; the event-based
16436
- * path then stands as the idempotent backstop.
16511
+ * The keyboard extension of a cross-block text range: move the selection's
16512
+ * focus end with the arrow / home / end keys.
16513
+ *
16514
+ * The browser cannot extend a DOM selection across a contenteditable
16515
+ * boundary (a drag or a native shift+arrow stays inside the starting
16516
+ * editable), so the editor owns the movement for a cross range: the
16517
+ * moving end steps by one character (arrows) or to the block's edge
16518
+ * (home / end), and steps across the edge into the adjacent chain block.
16519
+ * The moving end's stand (the anchor's identity's stand): the user's
16520
+ * anchor stands the view's direction (the DOM's read-back stands the
16521
+ * range's start over the backward seat's flipped anchor), so the moving
16522
+ * end is the opposite point — the reverse's `from`, the `to` otherwise.
16523
+ * The move re-bases the DOM selection with the anchor end standing (the
16524
+ * view's points, not the DOM's read-back); the selectionchange mapping
16525
+ * then updates the view. A move with nothing left to extend (the range's
16526
+ * edge) stands as a no-op; a move to the fixed end shrinks the range to
16527
+ * the caret (the selection's shrink's parity). Returns whether the moving
16528
+ * end moved (the caller suppresses the browser default then: the native
16529
+ * extension would race the re-base).
16437
16530
  */
16438
- function syncDomSelection(root, doc, view) {
16439
- const next = mapDomSelection(root, window.getSelection(), doc);
16440
- if (!selectionsEqual(next, view.get())) view.set(next);
16531
+ function extendRangeFocusEnd(doc, selection, key) {
16532
+ if (selection.kind !== "text" || selection.to === null) return false;
16533
+ const domSelection = window.getSelection();
16534
+ if (domSelection === null || domSelection.rangeCount === 0) return false;
16535
+ const scope = editorRootOf(domSelection.anchorNode ?? domSelection.focusNode ?? document.body);
16536
+ const movable = selection.reverse ? selection.from : selection.to;
16537
+ const fixed = selection.reverse ? selection.to : selection.from;
16538
+ const offset = movable.offset;
16539
+ const length = doc.getTextLength(movable.blockId);
16540
+ const chain = selection.blocks ?? [selection.from.blockId, selection.to.blockId];
16541
+ const index = chain.indexOf(movable.blockId);
16542
+ let next = null;
16543
+ if (key === "ArrowRight") {
16544
+ if (offset < length) next = {
16545
+ blockId: movable.blockId,
16546
+ offset: offset + 1
16547
+ };
16548
+ else {
16549
+ const nextId = chain[index + 1];
16550
+ if (nextId !== void 0) next = {
16551
+ blockId: nextId,
16552
+ offset: 0
16553
+ };
16554
+ }
16555
+ } else if (key === "ArrowLeft") {
16556
+ if (offset > 0) next = {
16557
+ blockId: movable.blockId,
16558
+ offset: offset - 1
16559
+ };
16560
+ else {
16561
+ const prevId = chain[index - 1];
16562
+ if (prevId !== void 0) next = {
16563
+ blockId: prevId,
16564
+ offset: doc.getTextLength(prevId)
16565
+ };
16566
+ }
16567
+ } else if (key === "End") next = {
16568
+ blockId: movable.blockId,
16569
+ offset: length
16570
+ };
16571
+ else if (key === "Home") next = {
16572
+ blockId: movable.blockId,
16573
+ offset: 0
16574
+ };
16575
+ if (next === null) return false;
16576
+ if (next.blockId === movable.blockId && next.offset === offset) return false;
16577
+ const anchorEl = scope.querySelector(`[data-block-id="${CSS.escape(fixed.blockId)}"][data-slot="docblocks/block-content"]`);
16578
+ if (anchorEl === null) return false;
16579
+ const anchorPos = locatePosition(anchorEl, fixed.offset);
16580
+ const target = scope.querySelector(`[data-block-id="${CSS.escape(next.blockId)}"][data-slot="docblocks/block-content"]`);
16581
+ if (target === null) return false;
16582
+ const position = locatePosition(target, next.offset);
16583
+ applyDomSelection(anchorPos.node, anchorPos.offset, position.node, position.offset);
16584
+ return true;
16441
16585
  }
16442
16586
  /**
16443
- * Whether the DOM selection's endpoints stand inside a block's editable
16444
- * (of any editor root): the caret is live in an editable, so the
16445
- * selection's mapping expresses a real edit position. A selection
16446
- * collapsed outside the editables (the chrome, the stale residue) does
16447
- * not — the mapping must not clobber a `blocks` view there. Neither does
16448
- * a caret parked at a pure page-container position (the page's single
16449
- * editable container is an editable, but the caret stands in no block —
16450
- * the reseat's transient, the gutter's focus park).
16451
- */
16452
- function domSelectionInEditable(domSelection) {
16453
- const inText = (node) => {
16454
- const editable = editableOfNode(node);
16455
- if (editable === null) return false;
16456
- return editable.getAttribute("data-slot") !== "docblocks/page";
16587
+ * The vertical keyboard extension of a cross-block text range: the
16588
+ * shift+arrow up/down move of the selection's moving end. The browser's
16589
+ * vertical shift arrow cannot extend a range across the block boundary
16590
+ * (the extension stands inside the focus's inner) and collapses the range
16591
+ * at the block's edge instead of a no-op (the Chromium's stand), so the
16592
+ * editor owns the key over the cross range: the moving end's stand (the
16593
+ * anchor's identity's stand — the DOM's read-back's flip's stand) is the
16594
+ * view's direction's opposite point; a moving end over a single-line block
16595
+ * crosses to the adjacent text block (the up's the previous block's end,
16596
+ * the down's the next's start — the caret's cross model's parity, the
16597
+ * chain's continuation over the adjacent blocks, the non-text siblings'
16598
+ * skip), a multi-line block's inner line stands the native's in-block's
16599
+ * extension (the browser's line's walk), and the multi-line's outer line
16600
+ * stands the edge's cross or a suppressed no-op. `owned` signals the
16601
+ * default's suppression (the passthrough's stand the browser's native
16602
+ * line's walk); `moved` the re-base (the view's sync's stand).
16603
+ */
16604
+ function extendRangeFocusEndVertical(doc, selection, key) {
16605
+ if (selection.kind !== "text" || selection.to === null) return {
16606
+ owned: false,
16607
+ moved: false
16608
+ };
16609
+ const domSelection = window.getSelection();
16610
+ if (domSelection === null || domSelection.rangeCount === 0) return {
16611
+ owned: false,
16612
+ moved: false
16613
+ };
16614
+ const scope = editorRootOf(domSelection.anchorNode ?? domSelection.focusNode ?? document.body);
16615
+ const movable = selection.reverse ? selection.from : selection.to;
16616
+ const fixed = selection.reverse ? selection.to : selection.from;
16617
+ const block = doc.getBlock(movable.blockId);
16618
+ if (block === null || !BLOCK_REGISTRY[block.type]?.content) return {
16619
+ owned: true,
16620
+ moved: false
16621
+ };
16622
+ const movableEl = scope.querySelector(`[data-block-id="${CSS.escape(movable.blockId)}"][data-slot="docblocks/block-content"]`);
16623
+ if (movableEl === null) return {
16624
+ owned: true,
16625
+ moved: false
16626
+ };
16627
+ const offset = movable.offset;
16628
+ const text = ("content" in block ? block.content ?? [] : []).map((run) => run.text).join("");
16629
+ const length = text.length;
16630
+ const lines = text.split("\n");
16631
+ const lineIndex = text.slice(0, Math.max(0, Math.min(offset, length))).split("\n").length - 1;
16632
+ const isUp = key === "ArrowUp";
16633
+ if (lines.length > 1 && (isUp && lineIndex > 0 || !isUp && lineIndex < lines.length - 1)) return {
16634
+ owned: false,
16635
+ moved: false
16636
+ };
16637
+ if (lines.length > 1 && (isUp ? offset !== 0 : offset !== length)) return {
16638
+ owned: true,
16639
+ moved: false
16640
+ };
16641
+ const target = findSiblingTextBlock(doc, movable.blockId, parentBlockIdOf(movableEl, doc), isUp ? "previous" : "next");
16642
+ if (target === null) return {
16643
+ owned: true,
16644
+ moved: false
16645
+ };
16646
+ const next = {
16647
+ blockId: target.id,
16648
+ offset: isUp ? target.length : 0
16649
+ };
16650
+ const anchorEl = scope.querySelector(`[data-block-id="${CSS.escape(fixed.blockId)}"][data-slot="docblocks/block-content"]`);
16651
+ if (anchorEl === null) return {
16652
+ owned: true,
16653
+ moved: false
16654
+ };
16655
+ const anchorPos = locatePosition(anchorEl, fixed.offset);
16656
+ const targetEl = scope.querySelector(`[data-block-id="${CSS.escape(next.blockId)}"][data-slot="docblocks/block-content"]`);
16657
+ if (targetEl === null) return {
16658
+ owned: true,
16659
+ moved: false
16660
+ };
16661
+ const targetPos = locatePosition(targetEl, next.offset);
16662
+ applyDomSelection(anchorPos.node, anchorPos.offset, targetPos.node, targetPos.offset);
16663
+ return {
16664
+ owned: true,
16665
+ moved: true
16457
16666
  };
16458
- return inText(domSelection?.anchorNode ?? null) && inText(domSelection?.focusNode ?? null);
16459
- }
16460
- /** The contenteditable that owns a node (the node's element or its parent's), or null. */
16461
- function editableOfNode(node) {
16462
- return (node === null ? null : node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[contenteditable=\"true\"]") ?? null;
16463
16667
  }
16464
16668
  //#endregion
16465
16669
  //#region src/editing/cross-range-keys.ts
@@ -16478,8 +16682,11 @@ function editableOfNode(node) {
16478
16682
  * updates the view). The horizontal shift arrows / home / end never reach
16479
16683
  * the browser (a native extension acts on the anchor's editable and would
16480
16684
  * retract the range); at the range's edge they stand as a suppressed
16481
- * no-op. The vertical shift arrows pass through (the native within-block
16482
- * extension is the browser's; the remap reconciles the view). `root`
16685
+ * no-op. The vertical shift arrows stand the editor's own cross (the
16686
+ * browser's cannot cross the boundary and collapses the range at the
16687
+ * block's edge — the single-line block's focus end crosses to the adjacent
16688
+ * block, the multi-line's inner line stands the native's in-block's line's
16689
+ * walk, the outer line's non-edge stands the suppressed no-op). `root`
16483
16690
  * scopes the gesture-time view sync (the
16484
16691
  * browser does not dispatch selectionchange for the re-based selection).
16485
16692
  */
@@ -16491,6 +16698,13 @@ function handleCrossRangeKey(doc, view, selection, root, event) {
16491
16698
  if (moved) syncDomSelection(root, doc, view);
16492
16699
  return true;
16493
16700
  }
16701
+ if (event.shiftKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
16702
+ const { owned, moved } = extendRangeFocusEndVertical(doc, selection, event.key);
16703
+ if (!owned) return false;
16704
+ event.preventDefault();
16705
+ if (moved) syncDomSelection(root, doc, view);
16706
+ return true;
16707
+ }
16494
16708
  if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
16495
16709
  const domSelection = window.getSelection();
16496
16710
  if (domSelection === null || domSelection.rangeCount === 0 || domSelection.focusNode === null) return false;
@@ -18625,7 +18839,16 @@ function useBlockInput({ id, blockType, context, innerRef, wrapperRef, declareLo
18625
18839
  };
18626
18840
  doc.transact(() => {
18627
18841
  const deleted = doc.deleteTextRange(from, to);
18628
- if (deleted === null) return;
18842
+ if (deleted === null) {
18843
+ const seat = doc.insertBlock("paragraph", void 0, { parent: rootBlockId });
18844
+ if (html !== "") seam.landing = applyRichPaste(doc, seat, 0, 0, html);
18845
+ else if (text !== "") seam.landing = applyMdPaste(doc, seat, 0, 0, text);
18846
+ seam.point = seam.landing ?? {
18847
+ blockId: seat,
18848
+ offset: 0
18849
+ };
18850
+ return;
18851
+ }
18629
18852
  const seamBlock = doc.getBlock(deleted.blockId);
18630
18853
  const seamRaw = seamBlock !== null && seamBlock.type === "code";
18631
18854
  const seamCellId = findParentId(doc, deleted.blockId);
@@ -18984,93 +19207,6 @@ function useBlockInput({ id, blockType, context, innerRef, wrapperRef, declareLo
18984
19207
  };
18985
19208
  }
18986
19209
  //#endregion
18987
- //#region src/editing/keyboard/utils.ts
18988
- /** The keyboard unit's helpers: the mark-toggle action, the sibling text
18989
- * block lookup, the parent block id, and the cell descent target. */
18990
- /**
18991
- * The toggle decision for one mark over [from, to): "unset" when every run
18992
- * overlapping the range already carries the mark, "set" otherwise. A
18993
- * partially covered run counts only if it carries the mark. Reads the block
18994
- * snapshot via `getBlock`; the caller issues the command.
18995
- */
18996
- function markToggleAction(doc, blockId, from, to, mark) {
18997
- const block = doc.getBlock(blockId);
18998
- if (block === null || !("content" in block)) return "set";
18999
- let pos = 0;
19000
- let overlaps = false;
19001
- for (const run of block.content ?? []) {
19002
- const start = pos;
19003
- pos += run.text.length;
19004
- if (pos <= from || start >= to) continue;
19005
- overlaps = true;
19006
- if (run.marks[mark] !== true) return "set";
19007
- }
19008
- return overlaps ? "unset" : "set";
19009
- }
19010
- /**
19011
- * The adjacent sibling a cross-block arrow can land in: the nearest
19012
- * previous/next sibling whose type carries text content — non-text siblings
19013
- * (divider, image, ...) are skipped. Null when nothing with content remains
19014
- * in that direction.
19015
- */
19016
- function findSiblingTextBlock(doc, id, parentId, direction) {
19017
- const siblings = doc.getChildren(parentId);
19018
- const index = siblings.indexOf(id);
19019
- if (index === -1) return null;
19020
- const step = direction === "previous" ? -1 : 1;
19021
- for (let i = index + step; i >= 0 && i < siblings.length; i += step) {
19022
- const siblingId = siblings[i];
19023
- if (siblingId === void 0) return null;
19024
- const sibling = doc.getBlock(siblingId);
19025
- if (sibling === null || !BLOCK_REGISTRY[sibling.type].content) continue;
19026
- return {
19027
- id: siblingId,
19028
- length: doc.getTextLength(siblingId)
19029
- };
19030
- }
19031
- return null;
19032
- }
19033
- /**
19034
- * The data parent of a focused text block (the container whose children
19035
- * sequence the block stands in): the nearest block ancestor that actually
19036
- * owns it as a child (the table cell over its content, the surface over
19037
- * the canvas item). The flat page model's nesting is render-only (the
19038
- * derived segment's DOM parent — the parent list item — is not the data
19039
- * parent: the page content is the root's flat sequence), so a block with
19040
- * no such ancestor stands at the document root.
19041
- */
19042
- function parentBlockIdOf(blockEl, doc) {
19043
- const selfId = blockEl.dataset.blockId;
19044
- if (selfId === void 0) return doc.meta.id;
19045
- let current = blockEl.parentElement;
19046
- while (current !== null) {
19047
- const id = current.dataset.blockId;
19048
- if (id !== void 0 && id !== selfId && doc.getBlock(id) !== null && doc.getChildren(id).includes(selfId)) return id;
19049
- current = current.parentElement;
19050
- }
19051
- return doc.meta.id;
19052
- }
19053
- /**
19054
- * The down-edge descent of a focused text block's cell's own content
19055
- * layer: the layer stands above the cell's children sequence, so the
19056
- * first text child takes the caret (the row's sibling walk finds the next
19057
- * cell instead). Null for every other block or edge.
19058
- */
19059
- function cellDescendTarget(doc, focusBlockId) {
19060
- const block = doc.getBlock(focusBlockId);
19061
- if (block === null || block.type !== "table-cell") return null;
19062
- for (const childId of doc.getChildren(focusBlockId)) {
19063
- if (childId === void 0) return null;
19064
- const child = doc.getBlock(childId);
19065
- if (child === null || !BLOCK_REGISTRY[child.type].content) continue;
19066
- return {
19067
- id: childId,
19068
- length: doc.getTextLength(childId)
19069
- };
19070
- }
19071
- return null;
19072
- }
19073
- //#endregion
19074
19210
  //#region src/editing/keyboard/use-block-keyboard.ts
19075
19211
  /** The block keyboard hook: the format shortcuts, the navigation
19076
19212
  * (arrow-key) moves, and the table-cell descent. */
@@ -19160,6 +19296,8 @@ function useBlockKeyboard({ id, blockType, context, innerRef }) {
19160
19296
  if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
19161
19297
  if (mod || event.nativeEvent.isComposing) return;
19162
19298
  if (selectionRef.view?.get().kind === "blocks") return;
19299
+ const viewSelection = selectionRef.view?.get();
19300
+ if (viewSelection?.kind === "text" && viewSelection.to !== null && viewSelection.to.blockId !== viewSelection.from.blockId) return;
19163
19301
  const domSelection = window.getSelection();
19164
19302
  if (domSelection === null || domSelection.rangeCount === 0) return;
19165
19303
  const { anchorNode, anchorOffset } = domSelection;
@@ -31562,7 +31700,10 @@ function positionAtPoint(doc, root, x, y) {
31562
31700
  * press (the multi-click's own mousedown tears the session down and lets
31563
31701
  * the default action stand; the pointer's detail stands 0 under synthetic
31564
31702
  * input, the mousedown's stands the real count, so the decision stands on
31565
- * the mousedown's). The triple press is the editor's: the browser's
31703
+ * the mousedown's). The shift's press stands the same tear-down (the
31704
+ * shift+click's extension's parity — the native extension's stand over
31705
+ * the default's suppression), and the triple press is the editor's: the
31706
+ * browser's
31566
31707
  * "paragraph" select of a pre-wrap block stands at one visual line (the
31567
31708
  * soft-break lines), so a detail-3 press inside a text inner is
31568
31709
  * suppressed and the editor stands the whole-block selection (all the
@@ -31631,6 +31772,10 @@ function useCrossDrag(rootRef, doc) {
31631
31772
  tearDown();
31632
31773
  return;
31633
31774
  }
31775
+ if (event.shiftKey) {
31776
+ tearDown();
31777
+ return;
31778
+ }
31634
31779
  if (document.activeElement instanceof HTMLIFrameElement) {
31635
31780
  tearDown();
31636
31781
  return;
@@ -31807,13 +31952,47 @@ function useEditing() {
31807
31952
  viewMode
31808
31953
  ]);
31809
31954
  const onKeyDown = (event) => {
31810
- if (viewMode) return;
31811
31955
  const root = rootRef.current;
31812
31956
  const target = event.target instanceof Element ? event.target : null;
31813
31957
  const nearest = target?.closest("[data-slot=\"docblocks/editor\"]") ?? null;
31814
31958
  if (root !== null && nearest !== null && nearest !== root) return;
31815
31959
  const formControl = target?.closest("input, textarea, [contenteditable='true']") ?? null;
31816
31960
  if (root !== null && target !== null && formControl !== null && !root.contains(target)) return;
31961
+ if (root !== null && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "a" && !event.shiftKey) {
31962
+ if (target !== null && target !== root && (target.closest("input, textarea") !== null || target.closest("[data-slot=\"docblocks/canvas-view\"]") !== null)) return;
31963
+ event.preventDefault();
31964
+ const textIds = doc.getChildren(rootBlockId).filter((id) => {
31965
+ const block = doc.getBlock(id);
31966
+ return block !== null && "content" in block;
31967
+ });
31968
+ const firstId = textIds[0];
31969
+ const lastId = textIds[textIds.length - 1];
31970
+ if (firstId === void 0 || lastId === void 0) return;
31971
+ const firstInner = root.querySelector(`[data-block-id="${CSS.escape(firstId)}"][data-slot="docblocks/block-content"]`);
31972
+ const lastInner = firstId === lastId ? firstInner : root.querySelector(`[data-block-id="${CSS.escape(lastId)}"][data-slot="docblocks/block-content"]`);
31973
+ if (firstInner === null || lastInner === null) return;
31974
+ const head = locatePosition(firstInner, 0);
31975
+ const tail = locatePosition(lastInner, doc.getTextLength(lastId));
31976
+ applyDomSelection(head.node, head.offset, tail.node, tail.offset);
31977
+ return;
31978
+ }
31979
+ if (root !== null && (event.metaKey || event.ctrlKey) && !event.shiftKey && (event.key === "Home" || event.key === "End")) {
31980
+ if (target !== null && target !== root && (target.closest("input, textarea") !== null || target.closest("[data-slot=\"docblocks/canvas-view\"]") !== null)) return;
31981
+ event.preventDefault();
31982
+ const textIds = doc.getChildren(rootBlockId).filter((id) => {
31983
+ const block = doc.getBlock(id);
31984
+ return block !== null && "content" in block;
31985
+ });
31986
+ const targetId = event.key === "Home" ? textIds[0] : textIds[textIds.length - 1];
31987
+ if (targetId === void 0) return;
31988
+ const inner = root.querySelector(`[data-block-id="${CSS.escape(targetId)}"][data-slot="docblocks/block-content"]`);
31989
+ if (inner === null) return;
31990
+ const position = locatePosition(inner, event.key === "Home" ? 0 : doc.getTextLength(targetId));
31991
+ applyDomSelection(position.node, position.offset, position.node, position.offset);
31992
+ (position.node instanceof Element ? position.node : position.node.parentElement)?.scrollIntoView({ block: event.key === "Home" ? "start" : "end" });
31993
+ return;
31994
+ }
31995
+ if (viewMode) return;
31817
31996
  const view = selectionRef.view;
31818
31997
  if (view !== null) {
31819
31998
  const selection = view.get();