smartrte-core 1.0.0-beta.7 → 1.0.0-beta.9

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 CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.0-beta.9
4
+
5
+ - Fix converting a paragraph sitting directly after an existing list into a list of the same kind always creating a second, independently-numbered list instead of continuing the existing one — e.g. typing after exiting a numbered list (Enter twice) and clicking "Numbered list" again now correctly appends as the next item rather than restarting at "1." next to it. See `docs/bugs/list-creation-ignores-adjacent-identical-list.md`.
6
+ - Fix pressing Enter at the end of a code-block list item never being able to create a new sibling list item — it previously only ever added lines inside the current item's own code block, with the only way "out" leaving a permanent stray empty paragraph behind. The same "type, Enter, Enter" rhythm already used to exit an empty list item now correctly starts a genuine new item instead. See `docs/bugs/code-block-list-item-cannot-exit-to-new-sibling-item.md`.
7
+ - Fix a further Enter pressed on that newly escaped (necessarily empty) item immediately exiting the list again instead of letting you type into it — indistinguishable from the editor's own separate "empty item + Enter exits the list" convention, so one extra keystroke silently undid the escape above and produced only stray paragraphs afterward. See `docs/bugs/code-block-list-item-cannot-exit-to-new-sibling-item.md`.
8
+ - Fix pressing Enter at the end of a code block's own content looking like it did nothing — a trailing "\n" with no following content rendered at zero extra height under `white-space:pre-wrap` (the model was correct; only the visible box failed to grow). See `docs/bugs/code-block-trailing-newline-invisible.md`.
9
+ - Fix any color or border live-preview (e.g. dragging the color picker, table-cell background/text colour) throwing "Children do not match 'text*'" and getting permanently stuck — unable to apply, unable to close by any means — the moment the document contained a multi-line code block anywhere in it, not just the target being colored. See `docs/bugs/checkpoint-restore-crashes-with-multiline-code-block.md`.
10
+ - Fix Shift+ArrowLeft/Shift+ArrowRight moving a collapsed caret instead of extending the selection (outside of a table cell, where this already worked) — the same gap already fixed once for Shift+Home/End, never carried over to plain arrows. See `docs/bugs/shift-arrow-left-right-does-not-extend-selection.md`.
11
+
12
+ ## 1.0.0-beta.8
13
+
14
+ - Fix Blockquote (and unwrap) throwing an uncaught error ("replaceNode before payload does not match document node.") and applying nothing, for a selection spanning a list item's own text and a nested sub-list item's text — two selected blocks resolving to two different, nested "list" ancestors were treated as independent (and mutually conflicting) wrap targets instead of recognizing the inner one is already covered by the outer one. Also fixed the identical latent issue for unwrapping nested blockquotes (the schema allows blockquote nesting), even though no live report had surfaced it yet. See `docs/bugs/blockquote-crashes-on-selection-spanning-outer-and-nested-list.md`.
15
+
3
16
  ## 1.0.0-beta.7
4
17
 
5
18
  - Fix copy, cut, and native drag throwing an uncaught error ("Clipboard copy is clamped to one structural parent.") for any selection whose two endpoints weren't immediate siblings — e.g. starting in a plain paragraph and dragging into a nested list item, or spanning two list items at different nesting depths. This was not an exotic shape: any selection reaching into a list, table, or blockquote from outside it hit this, and the failure was a silent no-op (nothing copied) with a console error, not a graceful fallback. See `docs/bugs/clipboard-copy-cut-throws-across-differently-nested-endpoints.md`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Smart RTE Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,28 +1,65 @@
1
- # Smart RTE Core
1
+ # smartrte-core
2
2
 
3
- Framework-agnostic document model, selection, transaction, history, and
4
- normalization primitives. This package is not yet wired into the published
5
- React editor; it establishes the compatibility-safe migration boundary.
3
+ [![npm version](https://img.shields.io/npm/v/smartrte-core.svg)](https://www.npmjs.com/package/smartrte-core)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
5
 
7
- ## Foundation contract
6
+ Framework-agnostic document model, selection, transaction, and editing primitives that power [`smartrte-react`](https://www.npmjs.com/package/smartrte-react). Everything here is plain TypeScript with no DOM/React dependency in its core data structures — schema, operations, and history all operate on a plain JSON document tree.
8
7
 
9
- The frozen Phase 1/C0 kernel is available from the dedicated subpath:
8
+ **If you're building a React app, install `smartrte-react` instead** — it depends on this package and re-exports everything you're likely to need. Install `smartrte-core` directly only if you're building a custom editing surface (a different UI framework, a headless document pipeline, a server-side format converter) on top of the same document model.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install smartrte-core
14
+ ```
15
+
16
+ ## What's in here
10
17
 
11
18
  ```ts
12
19
  import {
13
20
  createFoundationEditor,
14
21
  foundationSchema,
15
- resolveScope,
16
- type ResolvedPos,
17
- type SmartTransaction,
22
+ createPluginRegistry,
23
+ builtInPlugins,
18
24
  } from "smartrte-core/foundation";
19
25
  ```
20
26
 
21
- The package root remains the compatibility API for the current React adapter.
22
- New kernel and Phase 2 resolver work must use `smartrte-core/foundation`; do not
23
- extend the legacy raw-path contracts. `pnpm run lint:foundation-boundary`
24
- enforces that boundary. Root promotion is an explicit Phase 3 list-migration
25
- exit criterion. See `docs/FOUNDATION_CONTRACT.md` in the repository for the
26
- locked decisions and `docs/SEMANTIC_SELECTION_CONTRACT.md` for Phase 2.
27
- The persistent apply, incremental index, renderer, and browser-input contracts
28
- are recorded in `docs/CANONICAL_EDITING_SURFACE.md`.
27
+ - **Document model & schema** (`types`, `schema`, `identity`) — a plain JSON tree of typed nodes (paragraph, heading, list, table, image, formula, ...), each with a stable id that survives edits.
28
+ - **Editing engine** (`editor`, `transactions`, `operations`, `history`) — `createFoundationEditor` builds a stateful editor: dispatch a transaction, get back an updated document plus mapped selection, with full undo/redo.
29
+ - **Selection & scope resolution** (`scope/`) — resolves "what does the current selection actually touch" (a text range, a set of list items, a table-cell rectangle, a mix) so commands can act on the right thing regardless of how deeply nested it is.
30
+ - **Browser input surface** (`surface/`) — the `beforeinput`/paste/cut/drop/composition handling layer a real contentEditable-backed UI wires up to; this is what `smartrte-react` builds its editing surface on.
31
+ - **Format adapters** (`formats/`) — HTML, Markdown, DOCX (via `mammoth`/`@xmldom`), and PDF (`pdfjs-dist`) import/export, each declaring an explicit fidelity contract (`builtInFormatFidelity`) for exactly what's lossless vs. lossy per format/feature pair.
32
+ - **Diff, versioning, comments, suggestions, plugin system** (`diff/`, `versioning/`, `comments/`, `suggestions/`, `plugin/`) — the primitives `smartrte-react`'s version history, comment threads, and track-changes UI are built on. A `PluginRegistry` (`createPluginRegistry`, `builtInPlugins`) is how new commands, keyboard shortcuts, toolbar contributions, and renderer behavior are added — see [`docs/PLUGIN_ARCHITECTURE.md`](https://github.com/ayush1852017/smart-rte/blob/master/docs/PLUGIN_ARCHITECTURE.md) in the repository.
33
+ - **Collab contract** (`collab/`) — the operation-transform machinery (`mapOperation`) a real-time transport would rebase concurrent edits through. A contract for hosts building multi-writer collaboration against; no transport implementation ships here.
34
+
35
+ ## Subpath exports
36
+
37
+ ```json
38
+ {
39
+ ".": "compatibility root (legacy pre-foundation API)",
40
+ "./foundation": "the current, actively-developed API - use this",
41
+ "./legacy": "retired raw-path contracts, kept only for migration"
42
+ }
43
+ ```
44
+
45
+ New code should import from `smartrte-core/foundation` exclusively. The package root is a compatibility surface for older integrations; it is not where new capability lands.
46
+
47
+ ## Security
48
+
49
+ Format importers (HTML, DOCX, PDF) sanitize what they parse (DOMPurify for HTML), but this package holds no storage credentials and performs no network I/O itself — persistence, uploads, and real-time transport are all host-owned boundaries (see `smartrte-react`'s `MediaProvider`/`VersionProvider`/`CommentProvider`/`SuggestionProvider`/`CollabTransport`).
50
+
51
+ ## Development
52
+
53
+ This package lives in a pnpm workspace monorepo alongside `smartrte-react`.
54
+
55
+ ```bash
56
+ git clone https://github.com/ayush1852017/smart-rte.git
57
+ cd smart-rte
58
+ pnpm install
59
+ pnpm --filter smartrte-core build
60
+ pnpm --filter smartrte-core test
61
+ ```
62
+
63
+ ## License
64
+
65
+ MIT — see [LICENSE](https://github.com/ayush1852017/smart-rte/blob/master/LICENSE).
@@ -29,6 +29,31 @@ const ancestorWithRole = (nodeId, role, ctx) => {
29
29
  }
30
30
  return null;
31
31
  };
32
+ /**
33
+ * Two different selected blocks can resolve to two different target
34
+ * ancestors (both matching `role`) where one target is itself nested inside
35
+ * the other - e.g. a selection spanning a top-level list item and a
36
+ * sub-item of its own nested list has one selected block whose nearest
37
+ * "list" ancestor is the outer list, and another whose nearest "list"
38
+ * ancestor is the inner one. Both are real, valid `role` ancestors, but
39
+ * treating them as two independent wrap/unwrap targets is wrong: the outer
40
+ * target's own subtree already contains the inner one, so replacing both
41
+ * separately means the second operation's `before` snapshot (captured
42
+ * against the pre-edit document) no longer matches the document by the time
43
+ * it runs, since the first operation already mutated a node inside it -
44
+ * `applyOperations` throws "replaceNode before payload does not match
45
+ * document node." Kept only the outermost target per such chain - wrapping/
46
+ * unwrapping it already covers everything nested inside it.
47
+ */
48
+ const dropNestedTargets = (targets, ctx) => {
49
+ const idsToDrop = [];
50
+ targets.forEach((_target, id) => {
51
+ const resolved = ctx.positions.positionOf(id);
52
+ if (resolved?.ancestors.some((ancestor) => ancestor.id !== id && targets.has(ancestor.id)))
53
+ idsToDrop.push(id);
54
+ });
55
+ idsToDrop.forEach((id) => targets.delete(id));
56
+ };
32
57
  const ancestorTargets = (scope, role, ctx) => {
33
58
  const targets = new Map();
34
59
  selectedBlockIds(scope).forEach((nodeId) => {
@@ -37,6 +62,7 @@ const ancestorTargets = (scope, role, ctx) => {
37
62
  return;
38
63
  targets.set(ancestor.id, locate(ancestor.id, ctx));
39
64
  });
65
+ dropNestedTargets(targets, ctx);
40
66
  return [...targets.values()].sort((left, right) => right.pos.path.length - left.pos.path.length || right.pos.offset - left.pos.offset);
41
67
  };
42
68
  const typeAttrs = (node, type, attrs) => {
@@ -145,6 +171,7 @@ export const unwrapBlocks = (_document, scope, params, ctx) => {
145
171
  return;
146
172
  wrappers.set(target.id, locate(target.id, ctx));
147
173
  });
174
+ dropNestedTargets(wrappers, ctx);
148
175
  return [...wrappers.values()].sort((left, right) => right.pos.path.length - left.pos.path.length || right.pos.offset - left.pos.offset).flatMap(({ node, pos }) => {
149
176
  if (node.type !== wrapperType)
150
177
  return [];
@@ -13,7 +13,24 @@ export declare const insertCodeBlockNewline: (document: SmartDocument, pos: Smar
13
13
  readonly paragraphId?: string;
14
14
  }) => CodeBlockInputResult | null;
15
15
  export declare const indentInsideCodeBlock: (document: SmartDocument, pos: SmartPos) => CodeBlockInputResult | null;
16
- /** Ctrl/Cmd+Enter exits before only at offset zero; otherwise it exits after. */
16
+ /**
17
+ * Ctrl/Cmd+Enter exits before only at offset zero; otherwise it exits after.
18
+ *
19
+ * If the code block is the first/last content of a `list_item` (nothing
20
+ * else before/after it in the exit direction), exiting creates a new
21
+ * sibling *list item* instead of just another block stuffed inside the
22
+ * current one - list.ts's own `isInlineOwner` deliberately excludes
23
+ * `code_block` from its list-split logic (typing more lines of code must
24
+ * never accidentally split into a new item), which otherwise leaves no way
25
+ * to ever start a new item after one whose only content is a code block:
26
+ * "I create a number list ... type something ... clicked on number list
27
+ * tool which create new list again instead of becoming one with previous"
28
+ * was a *different*, already-fixed report, but the same investigation
29
+ * surfaced this - "Enter only creating new lines inside of code-block"
30
+ * when trying to add item 5 after a code-block item 4. This check doesn't
31
+ * require depending on the list module - it only reads generic node types,
32
+ * the same way `codeAt` above already does.
33
+ */
17
34
  export declare const exitCodeBlock: (document: SmartDocument, pos: SmartPos, paragraphId?: string) => CodeBlockInputResult | null;
18
35
  /** Canonical fragment insertion only; Phase 8 owns clipboard parsing. */
19
36
  export declare const insertPlainCodeFragment: (document: SmartDocument, pos: SmartPos, fragment: SmartDocument, _ctx: BlockCommandContext) => CodeBlockInputResult | null;
@@ -35,7 +35,24 @@ export const indentInsideCodeBlock = (document, pos) => {
35
35
  intent: "indent",
36
36
  };
37
37
  };
38
- /** Ctrl/Cmd+Enter exits before only at offset zero; otherwise it exits after. */
38
+ /**
39
+ * Ctrl/Cmd+Enter exits before only at offset zero; otherwise it exits after.
40
+ *
41
+ * If the code block is the first/last content of a `list_item` (nothing
42
+ * else before/after it in the exit direction), exiting creates a new
43
+ * sibling *list item* instead of just another block stuffed inside the
44
+ * current one - list.ts's own `isInlineOwner` deliberately excludes
45
+ * `code_block` from its list-split logic (typing more lines of code must
46
+ * never accidentally split into a new item), which otherwise leaves no way
47
+ * to ever start a new item after one whose only content is a code block:
48
+ * "I create a number list ... type something ... clicked on number list
49
+ * tool which create new list again instead of becoming one with previous"
50
+ * was a *different*, already-fixed report, but the same investigation
51
+ * surfaced this - "Enter only creating new lines inside of code-block"
52
+ * when trying to add item 5 after a code-block item 4. This check doesn't
53
+ * require depending on the list module - it only reads generic node types,
54
+ * the same way `codeAt` above already does.
55
+ */
39
56
  export const exitCodeBlock = (document, pos, paragraphId = createNodeId()) => {
40
57
  const code = codeAt(document, pos);
41
58
  if (!code || !pos.path.length)
@@ -43,6 +60,23 @@ export const exitCodeBlock = (document, pos, paragraphId = createNodeId()) => {
43
60
  const parentPath = pos.path.slice(0, -1);
44
61
  const codeIndex = pos.path[pos.path.length - 1];
45
62
  const before = pos.offset === 0;
63
+ const parent = nodeAtPath(document, parentPath);
64
+ const siblingCount = parent && !isTextNode(parent) ? (parent.children || []).length : 0;
65
+ const atListItemBoundary = parent && !isTextNode(parent) && parent.type === "list_item"
66
+ && (before ? codeIndex === 0 : codeIndex === siblingCount - 1) && parentPath.length > 0;
67
+ if (atListItemBoundary) {
68
+ const listItemIndex = parentPath[parentPath.length - 1];
69
+ const listPath = parentPath.slice(0, -1);
70
+ return {
71
+ operations: [{
72
+ type: "insertNode",
73
+ pos: { path: listPath, offset: listItemIndex + (before ? 0 : 1) },
74
+ node: { type: "list_item", id: createNodeId(), children: [{ type: "paragraph", id: paragraphId, children: [] }] },
75
+ }],
76
+ selectionTarget: { ownerId: paragraphId, offset: 0 },
77
+ intent: before ? "exit-before" : "exit-after",
78
+ };
79
+ }
46
80
  return {
47
81
  operations: [{
48
82
  type: "insertNode",
@@ -170,15 +170,48 @@ export const createList = (document, scope, params, ctx) => {
170
170
  ...(params.start !== undefined ? { start: params.start } : {}),
171
171
  ...(params.checkable !== undefined ? { checkable: params.checkable } : {}),
172
172
  };
173
+ // Only style/preset/checkable define whether two lists are "the same
174
+ // list" for merge purposes - `start` deliberately excluded, since
175
+ // appending items to an already-numbered list should keep continuing
176
+ // from wherever it already is, not require an exact `start` match.
177
+ const listIdentityMatches = (existing) => (existing?.preset ?? undefined) === listAttrs.preset
178
+ && (existing?.style ?? undefined) === listAttrs.style
179
+ && Boolean(existing?.checkable) === Boolean(listAttrs.checkable);
173
180
  return groups.flatMap((group) => {
174
181
  const depths = clampedDepths(group.entries.map((entry) => entry.node));
175
- const list = {
176
- type: "list",
177
- id: nextListId(),
178
- attrs: listAttrs,
179
- children: buildListItems(group.entries, depths, 0, () => itemIds[itemCursor++], nextListId, listAttrs),
180
- };
181
182
  const first = group.entries[0];
183
+ /**
184
+ * "I create a number list and press enter twice to take the cursor out
185
+ * from the list, then type something there and click the list tool" -
186
+ * previously always created a brand-new, independently-numbered list
187
+ * even when it sat directly after an existing, identical one - two
188
+ * separate "1."s instead of one continuous "1./2." list. If the
189
+ * immediately preceding sibling (same parent, same nesting level) is
190
+ * already a list of the exact same kind, the converted content joins
191
+ * it as trailing item(s) instead of starting a second list right next
192
+ * to the first.
193
+ */
194
+ const precedingIndex = first.pos.offset - 1;
195
+ const parent = ctx.positions.positionOf(first.id)?.parent;
196
+ const preceding = precedingIndex >= 0 ? parent?.children?.[precedingIndex] : undefined;
197
+ const mergeTarget = preceding && !isTextNode(preceding) && preceding.type === "list" && listIdentityMatches(preceding.attrs)
198
+ ? preceding : undefined;
199
+ const newItems = buildListItems(group.entries, depths, 0, () => itemIds[itemCursor++], nextListId, listAttrs);
200
+ if (mergeTarget) {
201
+ const operations = [{
202
+ type: "replaceNode",
203
+ pos: { path: [...first.pos.path], offset: precedingIndex },
204
+ before: mergeTarget,
205
+ after: withChildren(mergeTarget, [...(mergeTarget.children || []), ...newItems]),
206
+ }];
207
+ // Descending order so removing a later entry never shifts the index
208
+ // an earlier removeNode in this same batch still needs to target.
209
+ for (let index = group.entries.length - 1; index >= 0; index -= 1) {
210
+ operations.push({ type: "removeNode", pos: { path: [...first.pos.path], offset: first.pos.offset + index }, node: group.entries[index].node });
211
+ }
212
+ return operations;
213
+ }
214
+ const list = { type: "list", id: nextListId(), attrs: listAttrs, children: newItems };
182
215
  const operations = [{ type: "replaceNode", pos: first.pos, before: first.node, after: list }];
183
216
  group.entries.slice(1).forEach((entry) => operations.push({
184
217
  type: "removeNode",
@@ -7,7 +7,7 @@ export interface ListSelectionTarget {
7
7
  export interface ListInputResult {
8
8
  readonly operations: SmartOperation[];
9
9
  readonly selectionTarget: ListSelectionTarget;
10
- readonly intent: "split" | "indent" | "outdent" | "unwrap" | "merge-backward" | "merge-forward" | "line-break" | "check";
10
+ readonly intent: "split" | "indent" | "outdent" | "unwrap" | "merge-backward" | "merge-forward" | "line-break" | "check" | "noop";
11
11
  }
12
12
  export interface ListEnterIds {
13
13
  readonly itemId: string;
@@ -130,6 +130,13 @@ const splitInlineOwner = (owner, offset, newId) => {
130
130
  return [left, { ...owner, id: newId, children: after }];
131
131
  };
132
132
  const emptyParagraph = (id) => ({ type: "paragraph", id, children: [] });
133
+ const endsInCodeBlock = (item) => {
134
+ if (isTextNode(item))
135
+ return false;
136
+ const children = item.children || [];
137
+ const last = children[children.length - 1];
138
+ return Boolean(last) && !isTextNode(last) && last.type === "code_block";
139
+ };
133
140
  export const enterInList = (document, pos, ids, ctx) => {
134
141
  const context = contextAt(document, pos);
135
142
  if (!context)
@@ -139,6 +146,21 @@ export const enterInList = (document, pos, ids, ctx) => {
139
146
  const itemEmpty = (context.item.children || []).filter(isElementNode).filter((child) => child.type !== "list")
140
147
  .every((child) => isInlineOwner(child) && inlineSize(child) === 0);
141
148
  if (itemEmpty) {
149
+ // A code block can only ever be escaped into a *new*, necessarily empty
150
+ // sibling item (block/input.ts's exitCodeBlock) - so the very next Enter
151
+ // pressed on that item, before anything is typed, is exactly the
152
+ // one-keystroke-too-many trap of "type, Enter, Enter, Enter" reported
153
+ // live: the third Enter looks identical to any other empty-item Enter
154
+ // and immediately exits the list again, undoing the escape it just
155
+ // took two Enters to reach. Swallow it instead of exiting so the newly
156
+ // created item survives long enough to type into.
157
+ const preceding = context.itemIndex > 0 ? context.list.children?.[context.itemIndex - 1] : undefined;
158
+ if (preceding && endsInCodeBlock(preceding))
159
+ return {
160
+ operations: [],
161
+ selectionTarget: { ownerId: context.owner.id, offset: 0 },
162
+ intent: "noop",
163
+ };
142
164
  if (depth > 0)
143
165
  return {
144
166
  operations: outdentList(document, scope, {}, ctx),
@@ -9,6 +9,17 @@ export const migrateNewlineTextToHardBreaks = (document) => {
9
9
  return node;
10
10
  throw new Error("Text-node migration must be performed by its inline owner.");
11
11
  }
12
+ // code_block is the one node type whose schema is `content: "text*"` -
13
+ // it never accepts a hard_break child, and its own newline handling
14
+ // (block/input.ts's insertCodeBlockNewline) deliberately keeps line
15
+ // breaks as literal "\n" characters, unlike every inline-owner this
16
+ // migration actually targets. Splitting a code block's text here
17
+ // produced a hard_break inside a "text*"-only parent - a document that
18
+ // fails validate() on the very next restoreCheckpoint/replaceState
19
+ // call (live report: dragging the color picker on a document with any
20
+ // multi-line code block crashed with "Children do not match 'text*'").
21
+ if (node.type === "code_block")
22
+ return node;
12
23
  const children = [];
13
24
  let changed = false;
14
25
  (node.children || []).forEach((child) => {
@@ -1320,7 +1320,7 @@ export class FoundationInputPipeline {
1320
1320
  console.warn(`[Smart RTE canonical input] cancelled unsupported inputType: ${type || "unknown"}`);
1321
1321
  }
1322
1322
  }
1323
- moveCaret(direction, word = false) {
1323
+ moveCaret(direction, word = false, extend = false) {
1324
1324
  const selection = this.editor.selection;
1325
1325
  const active = selection.head;
1326
1326
  const activeOwner = nodeAtPath(this.editor.document, active.path);
@@ -1372,7 +1372,16 @@ export class FoundationInputPipeline {
1372
1372
  }
1373
1373
  }
1374
1374
  const next = { path: [...path], offset };
1375
- const model = { type: "text", anchor: next, head: next };
1375
+ // Shift+Left/Right is the standard "extend selection one character/word"
1376
+ // gesture - keep the existing anchor (from wherever the shift-extend
1377
+ // sequence started) and only move `head`, matching how Shift+Home/End
1378
+ // already does this (see that handler's own doc comment for the
1379
+ // matching bug this mirrors). Not threaded through
1380
+ // moveFromStructuralBoundary above - extending a text selection through
1381
+ // or onto a structural/atomic node is a materially different problem
1382
+ // (a different selection shape entirely), out of scope here.
1383
+ const anchor = extend ? selection.anchor : next;
1384
+ const model = { type: "text", anchor, head: next };
1376
1385
  this.editor.setSelection(model, { source: "keyboard" });
1377
1386
  this.renderer.render(this.editor.document, model);
1378
1387
  }
@@ -1531,7 +1540,7 @@ export class FoundationInputPipeline {
1531
1540
  this.renderer.render(this.editor.document, model);
1532
1541
  return;
1533
1542
  }
1534
- this.moveCaret(direction, modifier || event.altKey);
1543
+ this.moveCaret(direction, modifier || event.altKey, event.shiftKey);
1535
1544
  }
1536
1545
  else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
1537
1546
  if (event.shiftKey && this.handleTableShiftArrow(event.key === "ArrowUp" ? -1 : 1, 0)) {
@@ -39,6 +39,8 @@ export declare class FoundationSubtreeRenderer implements CanonicalSubtreeRender
39
39
  * caret. This <br> is renderer UI, not canonical document content.
40
40
  */
41
41
  private syncEmptyLineProjection;
42
+ /** Renderer-only <br> forcing the last, otherwise-invisible blank line of a code block's trailing "\n" to actually take up space. Must run after real text children are already in the DOM, since it's appended after them. */
43
+ private syncTrailingNewlineProjection;
42
44
  private diffElement;
43
45
  private selectionMatches;
44
46
  private restoreSelection;
@@ -38,6 +38,22 @@ const atomTypes = new Set(["image", "block_image", "formula", "block_formula", "
38
38
  */
39
39
  const atomErrorTitle = (node, fallback) => typeof node.attrs?.error === "string" && node.attrs.error ? node.attrs.error : fallback;
40
40
  const emptyLineOwnerTypes = new Set(["paragraph", "heading", "code_block"]);
41
+ const SMART_TRAILING_NEWLINE_ATTRIBUTE = "data-smart-trailing-newline";
42
+ /**
43
+ * A code block stores line breaks as literal "\n" characters inside its text
44
+ * (unlike a paragraph, which uses explicit hard_break nodes) - so a trailing
45
+ * "\n" with nothing rendered after it renders with zero extra height under
46
+ * white-space:pre-wrap (there's no following content to anchor a new line
47
+ * box against). Pressing Enter at the end of a code block's content was
48
+ * indistinguishable from doing nothing until a second character followed it.
49
+ */
50
+ const codeBlockEndsInNewline = (node) => {
51
+ if (node.type !== "code_block")
52
+ return false;
53
+ const children = node.children || [];
54
+ const last = children[children.length - 1];
55
+ return Boolean(last) && isTextNode(last) && last.text.endsWith("\n");
56
+ };
41
57
  const tagForNode = (node) => {
42
58
  if (node.type === "paragraph")
43
59
  return "p";
@@ -622,6 +638,7 @@ export class FoundationSubtreeRenderer {
622
638
  }
623
639
  });
624
640
  this.syncEmptyLineProjection(element, node);
641
+ this.syncTrailingNewlineProjection(element, node);
625
642
  }
626
643
  this.modelById.set(node.id, node);
627
644
  this.mapping.track(node, path, element);
@@ -661,6 +678,22 @@ export class FoundationSubtreeRenderer {
661
678
  this.recordWrite(node.id);
662
679
  }
663
680
  }
681
+ /** Renderer-only <br> forcing the last, otherwise-invisible blank line of a code block's trailing "\n" to actually take up space. Must run after real text children are already in the DOM, since it's appended after them. */
682
+ syncTrailingNewlineProjection(element, node) {
683
+ const existing = element.querySelector(`:scope > [${SMART_TRAILING_NEWLINE_ATTRIBUTE}]`);
684
+ const needsProjection = codeBlockEndsInNewline(node);
685
+ if (needsProjection && !existing) {
686
+ const line = element.ownerDocument.createElement("br");
687
+ line.setAttribute(SMART_TRAILING_NEWLINE_ATTRIBUTE, "true");
688
+ line.setAttribute(SMART_UI_ATTRIBUTE, "trailing-newline");
689
+ element.appendChild(line);
690
+ this.recordWrite(node.id);
691
+ }
692
+ else if (!needsProjection && existing) {
693
+ existing.remove();
694
+ this.recordWrite(node.id);
695
+ }
696
+ }
664
697
  diffElement(element, before, after, path, listDepth = 0) {
665
698
  this.modelById.set(after.id, after);
666
699
  this.mapping.track(after, path, element);
@@ -779,6 +812,7 @@ export class FoundationSubtreeRenderer {
779
812
  structural = true;
780
813
  }
781
814
  this.syncEmptyLineProjection(element, after);
815
+ this.syncTrailingNewlineProjection(element, after);
782
816
  return structural;
783
817
  }
784
818
  selectionMatches(selection, anchor, head) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "smartrte-core",
3
- "version": "1.0.0-beta.7",
3
+ "version": "1.0.0-beta.9",
4
4
  "description": "Framework-agnostic document model and editing primitives for Smart RTE",
5
5
  "repository": {
6
6
  "type": "git",