@astryxdesign/richtext 0.7.6 → 0.7.7-canary.36f8ea1

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.
@@ -5,34 +5,43 @@
5
5
  /**
6
6
  * @file CodeSyntaxPlugin.tsx
7
7
  * @input Uses @lexical/react (composer context), @lexical/code (CodeNode),
8
- * lexical, and core CodeBlock's tokenizer, highlight ranges, and token
9
- * types.
8
+ * lexical, core CodeBlock's highlight styles and token types, and
9
+ * CodeLineTokens (codeLineTokens.ts), core CodeBlock's tokens kept line by
10
+ * line.
10
11
  * @output Exports CodeSyntaxPlugin, which colors the code in every fenced code
11
- * block with core CodeBlock's tokenizer and syntax color tokens;
12
- * CODE_SYNTAX_CLASS, the class the theme gives code blocks for it; and
13
- * renderedTokens, which lays tokens out over a block's rendered text.
12
+ * block with core CodeBlock's tokenizer and syntax color tokens; and
13
+ * CODE_SYNTAX_CLASS, the class the theme gives code blocks for it.
14
14
  * @position Rendered by RichTextEditor and RichTextView. A fenced code block
15
15
  * with a language core CodeBlock knows is colored as core Markdown colors
16
16
  * it: the same tokenizer finds the same tokens, and each token type takes
17
17
  * its `--color-syntax-*` token (spec:AST-061 FR1) — no palette of its own.
18
18
  * The colors are CSS Custom Highlight ranges over the text Lexical renders,
19
19
  * the way core CodeBlock colors editable code, so the document and its DOM
20
- * are untouched; the ranges are rebuilt when a block's code or language
21
- * changes. Browsers without the Highlight API show plain code.
20
+ * are untouched. A block is colored in full when it appears, or when its
21
+ * language, its element, or its set of text nodes changes. An edit that
22
+ * only rewrites one text node's text re-tokenizes just the lines
23
+ * CodeLineTokens says it can change, and replaces only the ranges in that
24
+ * text node, reading no other. Browsers without the Highlight API show
25
+ * plain code.
22
26
  */
23
27
 
24
28
  import {useEffect, useState} from 'react';
25
29
  import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
26
30
  import {$isCodeNode, CodeNode} from '@lexical/code';
27
- import {$getNodeByKey, type NodeKey} from 'lexical';
28
31
  import {
29
- applyHighlightRangesFlat,
32
+ $getNodeByKey,
33
+ $isTextNode,
34
+ type LexicalEditor,
35
+ type NodeKey,
36
+ type NodeMutation,
37
+ } from 'lexical';
38
+ import {
39
+ ensureHighlightStyles,
30
40
  TOKEN_TYPES,
31
- tokenize,
32
41
  type CodeLanguage,
33
- type TokenLine,
34
42
  } from '@astryxdesign/core/CodeBlock';
35
43
  import {listedLanguage, sameLanguages} from './codeLanguages';
44
+ import {CodeLineTokens} from './codeLineTokens';
36
45
 
37
46
  /** The class the theme adds to every code block (editorTheme.ts). */
38
47
  export const CODE_SYNTAX_CLASS = 'astryx-richtext-code';
@@ -65,44 +74,166 @@ function supportsHighlights(): boolean {
65
74
  );
66
75
  }
67
76
 
77
+ /** A colored token: its range, and the highlight that holds it. */
78
+ interface Painted {
79
+ readonly range: Range;
80
+ readonly highlight: Highlight;
81
+ }
82
+
68
83
  /**
69
- * The tokens of `code`, laid out for the rendered text of its block: line by
70
- * line when the text keeps the line breaks, or as one line of offsets when
71
- * each line break is an element with no text. Null when the rendered text is
72
- * not the code (it is mid-update), so nothing is colored out of place.
84
+ * A colored code block, with what an edit needs to recolor part of it.
85
+ * Offsets in the rendered text are offsets in the block's DOM text nodes
86
+ * laid end to end, which is the code itself when its line breaks render as
87
+ * text, and the code without them when each renders as an element (`flat`).
73
88
  */
74
- export function renderedTokens(
75
- code: string,
76
- language: string | CodeLanguage,
77
- rendered: string,
78
- ): TokenLine[] | null {
79
- const lines = tokenize(code, language);
80
- if (rendered === code) {
81
- return lines;
89
+ interface Colored {
90
+ readonly element: HTMLElement;
91
+ readonly language: string;
92
+ readonly lines: CodeLineTokens;
93
+ readonly flat: boolean;
94
+ /** The block's DOM text nodes in order. */
95
+ readonly texts: Text[];
96
+ /** Where each DOM text node starts in the rendered text. */
97
+ readonly starts: number[];
98
+ /** Where each leaf's DOM text node starts in the code (NaN for others). */
99
+ readonly codeStarts: number[];
100
+ /** The rendered text's length. */
101
+ length: number;
102
+ /** The Lexical text nodes that render as one DOM text node each, by key:
103
+ * that node's index in `texts`, and the text last colored. */
104
+ readonly leaves: Map<NodeKey, {readonly index: number; text: string}>;
105
+ /** Each line's colored tokens. */
106
+ ranges: Painted[][];
107
+ }
108
+
109
+ function highlightFor(type: string): Highlight {
110
+ const name = `astryx-${type}`;
111
+ let highlight = CSS.highlights.get(name);
112
+ if (highlight == null) {
113
+ highlight = new Highlight();
114
+ CSS.highlights.set(name, highlight);
82
115
  }
83
- if (rendered !== code.replaceAll('\n', '')) {
116
+ return highlight;
117
+ }
118
+
119
+ /**
120
+ * The DOM position of `offset` in a block's rendered text: in the text node
121
+ * that holds the character there when `inside`, else in the first text node
122
+ * that reaches it. Null past the end of the text.
123
+ */
124
+ function pointAt(
125
+ block: Colored,
126
+ offset: number,
127
+ inside: boolean,
128
+ ): [Text, number] | null {
129
+ const {texts, starts, length} = block;
130
+ if (texts.length === 0 || offset > length) {
84
131
  return null;
85
132
  }
86
- const flat: TokenLine = [];
87
- let offset = 0;
88
- code.split('\n').forEach((line, index) => {
89
- for (const token of lines[index] ?? []) {
90
- flat.push({
91
- type: token.type,
92
- start: offset + token.start,
93
- end: offset + token.end,
94
- });
133
+ let low = 0;
134
+ let high = texts.length - 1;
135
+ while (low < high) {
136
+ const mid = (low + high) >>> 1;
137
+ const end = mid + 1 < texts.length ? starts[mid + 1] : length;
138
+ if (inside ? end > offset : end >= offset) {
139
+ high = mid;
140
+ } else {
141
+ low = mid + 1;
95
142
  }
96
- offset += line.length;
97
- });
98
- return [flat];
143
+ }
144
+ return [texts[low], offset - starts[low]];
99
145
  }
100
146
 
101
- interface Colored {
102
- readonly element: HTMLElement;
103
- readonly code: string;
104
- readonly language: string;
105
- readonly cleanup: () => void;
147
+ /** Colors one line's tokens. */
148
+ function paintLine(block: Colored, line: number): void {
149
+ // A flat block's rendered text has no line breaks before this line.
150
+ const base = block.lines.starts[line] - (block.flat ? line : 0);
151
+ const painted: Painted[] = [];
152
+ for (const token of block.lines.tokens[line] ?? []) {
153
+ const start = base + token.start;
154
+ const end = base + token.end;
155
+ const from = pointAt(block, start, start < end);
156
+ const to = pointAt(block, end, false);
157
+ if (from == null || to == null) {
158
+ continue;
159
+ }
160
+ const highlight = highlightFor(token.type);
161
+ try {
162
+ const range = new Range();
163
+ range.setStart(...from);
164
+ range.setEnd(...to);
165
+ highlight.add(range);
166
+ painted.push({range, highlight});
167
+ } catch {
168
+ // A range the DOM refuses colors nothing.
169
+ }
170
+ }
171
+ block.ranges[line] = painted;
172
+ }
173
+
174
+ function unpaintLine(block: Colored, line: number): void {
175
+ for (const {range, highlight} of block.ranges[line] ?? []) {
176
+ highlight.delete(range);
177
+ }
178
+ block.ranges[line] = [];
179
+ }
180
+
181
+ function unpaintAll(block: Colored): void {
182
+ for (let line = 0; line < block.ranges.length; line++) {
183
+ unpaintLine(block, line);
184
+ }
185
+ block.ranges = [];
186
+ }
187
+
188
+ function repaintAll(block: Colored): void {
189
+ unpaintAll(block);
190
+ for (let line = 0; line < block.lines.tokens.length; line++) {
191
+ paintLine(block, line);
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Lists a block's DOM text nodes in order with their offsets, and the
197
+ * Lexical text nodes that render as exactly one of them.
198
+ */
199
+ function $indexText(
200
+ editor: LexicalEditor,
201
+ node: CodeNode,
202
+ block: Colored,
203
+ ): void {
204
+ const walker = document.createTreeWalker(block.element, NodeFilter.SHOW_TEXT);
205
+ while (walker.nextNode() != null) {
206
+ const text = walker.currentNode as Text;
207
+ block.texts.push(text);
208
+ block.starts.push(block.length);
209
+ block.codeStarts.push(NaN);
210
+ block.length += text.length;
211
+ }
212
+ const indexes = new Map(block.texts.map((text, index) => [text, index]));
213
+ let codeStart = 0;
214
+ for (const child of node.getChildren()) {
215
+ const dom = $isTextNode(child)
216
+ ? editor.getElementByKey(child.getKey())
217
+ : null;
218
+ const index =
219
+ dom?.childNodes.length === 1
220
+ ? indexes.get(dom.firstChild as Text)
221
+ : undefined;
222
+ if (index != null) {
223
+ block.leaves.set(child.getKey(), {index, text: child.getTextContent()});
224
+ block.codeStarts[index] = codeStart;
225
+ }
226
+ codeStart += child.getTextContentSize();
227
+ }
228
+ }
229
+
230
+ /** The key of the code block that holds the node `key`, if any. */
231
+ function $codeBlockOf(key: NodeKey): NodeKey | null {
232
+ let node = $getNodeByKey(key)?.getParent() ?? null;
233
+ while (node != null && !$isCodeNode(node)) {
234
+ node = node.getParent();
235
+ }
236
+ return node?.getKey() ?? null;
106
237
  }
107
238
 
108
239
  export function CodeSyntaxPlugin({
@@ -121,81 +252,233 @@ export function CodeSyntaxPlugin({
121
252
  }
122
253
 
123
254
  // Synchronizes the editor's code blocks with the CSS highlight registry:
124
- // Lexical update and mutation listeners colour each block, and the cleanup
255
+ // Lexical mutation and update listeners colour each block, and the cleanup
125
256
  // removes the listeners and every highlight range they added.
126
257
  useEffect(() => {
127
258
  if (!supportsHighlights()) {
128
259
  return undefined;
129
260
  }
130
261
  ensureRules();
131
- // Every code block in the editor, and the ones colored, by node key.
262
+ // Every code block in the editor, the ones colored, and the ones colored
263
+ // in full during the current update.
132
264
  const blocks = new Set<NodeKey>();
133
265
  const colored = new Map<NodeKey, Colored>();
266
+ const repainted = new Set<NodeKey>();
134
267
  const uncolor = (key: NodeKey) => {
135
- colored.get(key)?.cleanup();
136
- colored.delete(key);
268
+ const block = colored.get(key);
269
+ if (block != null) {
270
+ unpaintAll(block);
271
+ colored.delete(key);
272
+ }
137
273
  };
138
- const color = (key: NodeKey) => {
139
- const block = editor.getEditorState().read(() => {
140
- const node = $getNodeByKey(key);
141
- return $isCodeNode(node)
142
- ? {code: node.getTextContent(), language: node.getLanguage() ?? ''}
143
- : null;
144
- });
274
+ // Colors a block in full, unless `force` is false and its element,
275
+ // language, and code are as last colored.
276
+ const $color = (key: NodeKey, force: boolean) => {
277
+ const node = $getNodeByKey(key);
145
278
  const element = editor.getElementByKey(key);
146
- if (block == null || element == null) {
279
+ if (!$isCodeNode(node) || element == null) {
147
280
  uncolor(key);
148
281
  return;
149
282
  }
283
+ const code = node.getTextContent();
284
+ const language = node.getLanguage() ?? '';
150
285
  const previous = colored.get(key);
151
286
  if (
287
+ !force &&
152
288
  previous != null &&
153
289
  previous.element === element &&
154
- previous.code === block.code &&
155
- previous.language === block.language
290
+ previous.language === language &&
291
+ previous.lines.text === code
156
292
  ) {
157
293
  return;
158
294
  }
159
- previous?.cleanup();
160
- const tokens = renderedTokens(
161
- block.code,
162
- listedLanguage(languages, block.language) ?? block.language,
163
- element.textContent ?? '',
164
- );
165
- if (tokens == null) {
166
- // Not rendered yet; the next update tries again.
167
- colored.delete(key);
295
+ uncolor(key);
296
+ const rendered = element.textContent ?? '';
297
+ if (rendered !== code && rendered !== code.replaceAll('\n', '')) {
298
+ // Not rendered yet; the block's next change tries again.
168
299
  return;
169
300
  }
170
- colored.set(key, {
301
+ ensureHighlightStyles();
302
+ const block: Colored = {
171
303
  element,
172
- ...block,
173
- cleanup: applyHighlightRangesFlat(element, tokens),
174
- });
304
+ language,
305
+ lines: new CodeLineTokens(
306
+ code,
307
+ listedLanguage(languages, language) ?? language,
308
+ ),
309
+ flat: rendered !== code,
310
+ texts: [],
311
+ starts: [],
312
+ codeStarts: [],
313
+ length: 0,
314
+ leaves: new Map(),
315
+ ranges: [],
316
+ };
317
+ $indexText(editor, node, block);
318
+ repaintAll(block);
319
+ colored.set(key, block);
320
+ repainted.add(key);
321
+ };
322
+ // Recolors a block after an update that rewrote the text of its leaf
323
+ // `leafKey` and changed nothing else in it. False when the block must
324
+ // be colored in full instead.
325
+ const $recolorLeaf = (key: NodeKey, leafKey: NodeKey): boolean => {
326
+ const block = colored.get(key);
327
+ const leaf = block?.leaves.get(leafKey);
328
+ const node = $getNodeByKey(leafKey);
329
+ const parent = node?.getParent();
330
+ if (
331
+ block == null ||
332
+ leaf == null ||
333
+ !$isTextNode(node) ||
334
+ !$isCodeNode(parent) ||
335
+ parent.getKey() !== key ||
336
+ (parent.getLanguage() ?? '') !== block.language ||
337
+ editor.getElementByKey(key) !== block.element
338
+ ) {
339
+ return false;
340
+ }
341
+ const text = block.texts[leaf.index];
342
+ const dom = editor.getElementByKey(leafKey);
343
+ const after = node.getTextContent();
344
+ if (
345
+ dom?.childNodes.length !== 1 ||
346
+ dom.firstChild !== text ||
347
+ text.data !== after
348
+ ) {
349
+ return false;
350
+ }
351
+ const before = leaf.text;
352
+ if (after === before) {
353
+ return true;
354
+ }
355
+ let first = 0;
356
+ while (
357
+ first < before.length &&
358
+ first < after.length &&
359
+ before[first] === after[first]
360
+ ) {
361
+ first++;
362
+ }
363
+ let beforeEnd = before.length;
364
+ let afterEnd = after.length;
365
+ while (
366
+ beforeEnd > first &&
367
+ afterEnd > first &&
368
+ before[beforeEnd - 1] === after[afterEnd - 1]
369
+ ) {
370
+ beforeEnd--;
371
+ afterEnd--;
372
+ }
373
+ const inserted = after.slice(first, afterEnd);
374
+ // A flat block's text holds no line breaks; one typed in would no
375
+ // longer lay the code over its rendered text.
376
+ if (block.flat && inserted.includes('\n')) {
377
+ return false;
378
+ }
379
+ const leafStart = block.codeStarts[leaf.index];
380
+ const lines = block.lines.replace(
381
+ leafStart + first,
382
+ beforeEnd - first,
383
+ inserted,
384
+ );
385
+ const delta = after.length - before.length;
386
+ for (let i = leaf.index + 1; i < block.texts.length; i++) {
387
+ block.starts[i] += delta;
388
+ block.codeStarts[i] += delta;
389
+ }
390
+ block.length += delta;
391
+ leaf.text = after;
392
+ if (lines == null) {
393
+ repaintAll(block);
394
+ return true;
395
+ }
396
+ // Lexical rewrites a changed DOM text node whole, which leaves every
397
+ // range in it stale: recolor each line the node holds, and any other
398
+ // line the edit re-tokenized. Every other range sits in a text node of
399
+ // its own line and is still right.
400
+ const recolor = new Set(lines);
401
+ const last = block.lines.lineAt(
402
+ leafStart + Math.max(after.length - 1, 0),
403
+ );
404
+ for (let i = block.lines.lineAt(leafStart); i <= last; i++) {
405
+ recolor.add(i);
406
+ }
407
+ for (const i of recolor) {
408
+ unpaintLine(block, i);
409
+ paintLine(block, i);
410
+ }
411
+ return true;
175
412
  };
176
413
  const unregisterMutations = editor.registerMutationListener(
177
414
  CodeNode,
178
415
  mutations => {
179
- for (const [key, mutation] of mutations) {
180
- if (mutation === 'destroyed') {
181
- blocks.delete(key);
182
- uncolor(key);
183
- } else {
184
- blocks.add(key);
185
- color(key);
416
+ editor.getEditorState().read(() => {
417
+ for (const [key, mutation] of mutations) {
418
+ if (mutation === 'destroyed') {
419
+ blocks.delete(key);
420
+ uncolor(key);
421
+ } else {
422
+ blocks.add(key);
423
+ $color(key, false);
424
+ }
186
425
  }
187
- }
426
+ });
188
427
  },
189
428
  {skipInitialization: false},
190
429
  );
191
- // Typing in a block changes its text nodes, not always the block itself:
192
- // recheck every block after each update (unchanged ones stop at the
193
- // comparison above).
194
- const unregisterUpdates = editor.registerUpdateListener(() => {
195
- for (const key of blocks) {
196
- color(key);
197
- }
198
- });
430
+ repainted.clear();
431
+ // Typing in a block changes its text nodes, not the block itself: after
432
+ // each update, recolor the blocks whose text nodes changed. A block whose
433
+ // only change is one leaf's text takes the partial path; any other
434
+ // change colors it in full, unless the block listener just did.
435
+ const unregisterUpdates = editor.registerUpdateListener(
436
+ ({editorState, mutatedNodes, prevEditorState}) => {
437
+ if (mutatedNodes != null && blocks.size > 0) {
438
+ const mutations: Array<[NodeKey, NodeMutation]> = [];
439
+ for (const nodes of mutatedNodes.values()) {
440
+ for (const mutation of nodes) {
441
+ mutations.push(mutation);
442
+ }
443
+ }
444
+ const before = prevEditorState.read(() =>
445
+ mutations.map(([key, mutation]) =>
446
+ mutation === 'created' ? null : $codeBlockOf(key),
447
+ ),
448
+ );
449
+ editorState.read(() => {
450
+ // Each changed block, with the one leaf whose text an update
451
+ // rewrote, or null when anything else in it changed.
452
+ const changed = new Map<NodeKey, NodeKey | null>();
453
+ const note = (key: NodeKey | null, leafKey: NodeKey | null) => {
454
+ if (key != null && blocks.has(key)) {
455
+ changed.set(key, changed.has(key) ? null : leafKey);
456
+ }
457
+ };
458
+ mutations.forEach(([key, mutation], i) => {
459
+ const after = mutation === 'destroyed' ? null : $codeBlockOf(key);
460
+ const rewritten =
461
+ mutation === 'updated' &&
462
+ after === before[i] &&
463
+ $isTextNode($getNodeByKey(key));
464
+ note(after, rewritten ? key : null);
465
+ if (before[i] !== after) {
466
+ note(before[i], null);
467
+ }
468
+ });
469
+ for (const [key, leafKey] of changed) {
470
+ if (
471
+ !repainted.has(key) &&
472
+ (leafKey == null || !$recolorLeaf(key, leafKey))
473
+ ) {
474
+ $color(key, true);
475
+ }
476
+ }
477
+ });
478
+ }
479
+ repainted.clear();
480
+ },
481
+ );
199
482
  return () => {
200
483
  unregisterMutations();
201
484
  unregisterUpdates();