@lexical/html 0.44.1-nightly.20260519.0 → 0.45.1-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/{DOMRenderExtension.d.ts → dist/DOMRenderExtension.d.ts} +12 -1
  2. package/dist/DOMRenderRuntime.d.ts +51 -0
  3. package/dist/LexicalHtml.dev.js +3289 -0
  4. package/dist/LexicalHtml.dev.mjs +3242 -0
  5. package/{LexicalHtml.js.flow → dist/LexicalHtml.js.flow} +16 -16
  6. package/dist/LexicalHtml.mjs +57 -0
  7. package/dist/LexicalHtml.node.mjs +55 -0
  8. package/dist/LexicalHtml.prod.js +9 -0
  9. package/dist/LexicalHtml.prod.mjs +9 -0
  10. package/dist/RenderContext.d.ts +68 -0
  11. package/{compileDOMRenderConfigOverrides.d.ts → dist/compileDOMRenderConfigOverrides.d.ts} +1 -1
  12. package/{constants.d.ts → dist/constants.d.ts} +2 -0
  13. package/dist/domOverride.d.ts +23 -0
  14. package/dist/import/CoreImportExtension.d.ts +11 -0
  15. package/dist/import/DOMImportExtension.d.ts +82 -0
  16. package/dist/import/HorizontalRuleImportExtension.d.ts +28 -0
  17. package/dist/import/ImportContext.d.ts +208 -0
  18. package/dist/import/compileImportRules.d.ts +50 -0
  19. package/dist/import/coreImportRules.d.ts +25 -0
  20. package/dist/import/defineImportRule.d.ts +32 -0
  21. package/dist/import/defineOverlayRules.d.ts +66 -0
  22. package/dist/import/index.d.ts +38 -0
  23. package/dist/import/inlineStylesFromStyleSheets.d.ts +28 -0
  24. package/dist/import/parseCss.d.ts +18 -0
  25. package/dist/import/runImport.d.ts +19 -0
  26. package/dist/import/schemas.d.ts +106 -0
  27. package/dist/import/sel.d.ts +74 -0
  28. package/dist/import/types.d.ts +394 -0
  29. package/dist/index.d.ts +44 -0
  30. package/{types.d.ts → dist/types.d.ts} +96 -8
  31. package/package.json +33 -18
  32. package/src/ContextRecord.ts +243 -0
  33. package/src/DOMRenderExtension.ts +96 -0
  34. package/src/DOMRenderRuntime.ts +265 -0
  35. package/src/RenderContext.ts +168 -0
  36. package/src/compileDOMRenderConfigOverrides.ts +416 -0
  37. package/src/constants.ts +18 -0
  38. package/src/domOverride.ts +46 -0
  39. package/src/import/CoreImportExtension.ts +26 -0
  40. package/src/import/DOMImportExtension.ts +221 -0
  41. package/src/import/HorizontalRuleImportExtension.ts +52 -0
  42. package/src/import/ImportContext.ts +339 -0
  43. package/src/import/compileImportRules.ts +178 -0
  44. package/src/import/coreImportRules.ts +545 -0
  45. package/src/import/defineImportRule.ts +40 -0
  46. package/src/import/defineOverlayRules.ts +105 -0
  47. package/src/import/index.ts +97 -0
  48. package/src/import/inlineStylesFromStyleSheets.ts +104 -0
  49. package/src/import/parseCss.ts +219 -0
  50. package/src/import/runImport.ts +245 -0
  51. package/src/import/schemas.ts +280 -0
  52. package/src/import/sel.ts +314 -0
  53. package/src/import/types.ts +471 -0
  54. package/src/index.ts +561 -0
  55. package/src/types.ts +470 -0
  56. package/LexicalHtml.dev.js +0 -914
  57. package/LexicalHtml.dev.mjs +0 -900
  58. package/LexicalHtml.mjs +0 -24
  59. package/LexicalHtml.node.mjs +0 -22
  60. package/LexicalHtml.prod.js +0 -9
  61. package/LexicalHtml.prod.mjs +0 -9
  62. package/RenderContext.d.ts +0 -32
  63. package/domOverride.d.ts +0 -18
  64. package/index.d.ts +0 -32
  65. /package/{ContextRecord.d.ts → dist/ContextRecord.d.ts} +0 -0
  66. /package/{LexicalHtml.js → dist/LexicalHtml.js} +0 -0
@@ -1,900 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
-
9
- import { $sliceSelectedTextNodeContent } from '@lexical/selection';
10
- import { $getEditor, createState, DEFAULT_EDITOR_DOM_CONFIG, $isLexicalNode, getStaticNodeConfig, defineExtension, shallowMergeConfig, RootNode, $getRoot, $getEditorDOMRenderConfig, isDOMDocumentNode, $isTextNode, $isElementNode, isHTMLElement, isDocumentFragment, $isRootOrShadowRoot, $isBlockElementNode, isBlockDomNode, $createLineBreakNode, ArtificialNode__DO_NOT_USE, isInlineDomNode, $createParagraphNode } from 'lexical';
11
- import { getPeerDependencyFromEditor, getKnownTypesAndNodes } from '@lexical/extension';
12
-
13
- /**
14
- * Copyright (c) Meta Platforms, Inc. and affiliates.
15
- *
16
- * This source code is licensed under the MIT license found in the
17
- * LICENSE file in the root directory of this source tree.
18
- *
19
- */
20
-
21
- // Do not require this module directly! Use normal `invariant` calls.
22
-
23
- function formatDevErrorMessage(message) {
24
- throw new Error(message);
25
- }
26
-
27
- /**
28
- * Copyright (c) Meta Platforms, Inc. and affiliates.
29
- *
30
- * This source code is licensed under the MIT license found in the
31
- * LICENSE file in the root directory of this source tree.
32
- *
33
- */
34
-
35
- let activeContext;
36
-
37
- /**
38
- * @experimental
39
- *
40
- * The LexicalEditor with context
41
- */
42
-
43
- /**
44
- * @experimental
45
- *
46
- * @param contextRecord The ContextRecord
47
- * @param cfg The configuration
48
- * @returns The value or defaultValue of cfg
49
- */
50
- function getContextValue(contextRecord, cfg) {
51
- const {
52
- key
53
- } = cfg;
54
- return contextRecord && key in contextRecord ? contextRecord[key] : cfg.defaultValue;
55
- }
56
- function getEditorContext(editor) {
57
- return activeContext && activeContext.editor === editor ? activeContext : undefined;
58
- }
59
-
60
- /**
61
- * @experimental
62
- *
63
- * @param sym The symbol for this ContextRecord (e.g. DOMRenderContextSymbol)
64
- * @param editor The editor
65
- * @returns The current context or undefined
66
- */
67
- function getContextRecord(sym, editor) {
68
- const editorContext = getEditorContext(editor);
69
- return editorContext && editorContext[sym];
70
- }
71
- function toPair(contextRecord, pairOrUpdater) {
72
- if ('cfg' in pairOrUpdater) {
73
- const {
74
- cfg,
75
- updater
76
- } = pairOrUpdater;
77
- return [cfg, updater(getContextValue(contextRecord, cfg))];
78
- }
79
- return pairOrUpdater;
80
- }
81
-
82
- /**
83
- * Construct a new context from a parent context and pairs
84
- *
85
- * @param pairs The pairs and updaters to build the context from
86
- * @param parent The parent context
87
- * @returns The new context
88
- */
89
- function contextFromPairs(pairs, parent) {
90
- let rval = parent;
91
- for (const pairOrUpdater of pairs) {
92
- const [k, v] = toPair(rval, pairOrUpdater);
93
- const key = k.key;
94
- if (rval === parent && getContextValue(rval, k) === v) {
95
- continue;
96
- }
97
- const ctx = rval || createChildContext(parent);
98
- ctx[key] = v;
99
- rval = ctx;
100
- }
101
- return rval;
102
- }
103
- function createChildContext(parent) {
104
- return Object.create(parent || null);
105
- }
106
-
107
- /**
108
- * Create a context config pair that sets a value in the render context.
109
- * @experimental
110
- */
111
- function contextValue(cfg, value) {
112
- return [cfg, value];
113
- }
114
-
115
- /**
116
- * Create a context config updater that transforms a value in the render context.
117
- * @experimental
118
- */
119
- function contextUpdater(cfg, updater) {
120
- return {
121
- cfg,
122
- updater
123
- };
124
- }
125
-
126
- /**
127
- * @internal
128
- * @experimental
129
- * @__NO_SIDE_EFFECTS__
130
- */
131
- function $withFullContext(sym, contextRecord, f, editor = $getEditor()) {
132
- const prevDOMContext = activeContext;
133
- const parentEditorContext = getEditorContext(editor);
134
- try {
135
- activeContext = {
136
- ...parentEditorContext,
137
- editor,
138
- [sym]: contextRecord
139
- };
140
- return f();
141
- } finally {
142
- activeContext = prevDOMContext;
143
- }
144
- }
145
-
146
- /**
147
- * @internal
148
- * @experimental
149
- * @__NO_SIDE_EFFECTS__
150
- */
151
- function $withContext(sym, $defaults = () => undefined) {
152
- return (cfg, editor = $getEditor()) => {
153
- return f => {
154
- const parentEditorContext = getEditorContext(editor);
155
- const parentContextRecord = parentEditorContext && parentEditorContext[sym];
156
- const contextRecord = contextFromPairs(cfg, parentContextRecord || $defaults(editor));
157
- if (!contextRecord || contextRecord === parentContextRecord) {
158
- return f();
159
- }
160
- return $withFullContext(sym, contextRecord, f, editor);
161
- };
162
- };
163
- }
164
-
165
- /**
166
- * @experimental
167
- * @internal
168
- * @__NO_SIDE_EFFECTS__
169
- */
170
- function createContextState(tag, name, getDefaultValue, isEqual) {
171
- return Object.assign(createState(Symbol(name), {
172
- isEqual,
173
- parse: getDefaultValue
174
- }), {
175
- [tag]: true
176
- });
177
- }
178
-
179
- /**
180
- * Copyright (c) Meta Platforms, Inc. and affiliates.
181
- *
182
- * This source code is licensed under the MIT license found in the
183
- * LICENSE file in the root directory of this source tree.
184
- *
185
- */
186
- const DOMRenderExtensionName = '@lexical/html/DOM';
187
- const DOMRenderContextSymbol = Symbol.for('@lexical/html/DOMExportContext');
188
- const ALWAYS_TRUE = () => true;
189
-
190
- /**
191
- * Copyright (c) Meta Platforms, Inc. and affiliates.
192
- *
193
- * This source code is licensed under the MIT license found in the
194
- * LICENSE file in the root directory of this source tree.
195
- *
196
- */
197
- /**
198
- * Create a context state to be used during render.
199
- *
200
- * Note that to support the ValueOrUpdater pattern you can not use a
201
- * function for V (but you may wrap it in an array or object).
202
- *
203
- * @experimental
204
- * @__NO_SIDE_EFFECTS__
205
- */
206
- function createRenderState(name, getDefaultValue, isEqual) {
207
- return createContextState(DOMRenderContextSymbol, name, getDefaultValue, isEqual);
208
- }
209
-
210
- /**
211
- * Render context state that is true if the export was initiated from the root of the document.
212
- * @experimental
213
- */
214
- const RenderContextRoot = createRenderState('root', Boolean);
215
-
216
- /**
217
- * Render context state that is true if this is an export operation ($generateHtmlFromNodes).
218
- * @experimental
219
- */
220
- const RenderContextExport = createRenderState('isExport', Boolean);
221
- function getDefaultRenderContext(editor) {
222
- const dep = getPeerDependencyFromEditor(editor, DOMRenderExtensionName);
223
- return dep ? dep.output.defaults : undefined;
224
- }
225
- function getRenderContext(editor) {
226
- return getContextRecord(DOMRenderContextSymbol, editor) || getDefaultRenderContext(editor);
227
- }
228
-
229
- /**
230
- * Get a render context value during a DOM render or export operation.
231
- * @experimental
232
- */
233
- function $getRenderContextValue(cfg, editor = $getEditor()) {
234
- return getContextValue(getRenderContext(editor), cfg);
235
- }
236
-
237
- /**
238
- * Execute a callback within a render context with the given config pairs.
239
- * @experimental
240
- */
241
- const $withRenderContext = $withContext(DOMRenderContextSymbol, getDefaultRenderContext);
242
-
243
- /**
244
- * Copyright (c) Meta Platforms, Inc. and affiliates.
245
- *
246
- * This source code is licensed under the MIT license found in the
247
- * LICENSE file in the root directory of this source tree.
248
- *
249
- */
250
-
251
- /**
252
- * A convenience function for type inference when constructing DOM overrides for
253
- * use with {@link DOMRenderExtension}.
254
- *
255
- * @experimental
256
- * @__NO_SIDE_EFFECTS__
257
- */
258
-
259
- function domOverride(nodes, config) {
260
- return {
261
- ...config,
262
- nodes
263
- };
264
- }
265
-
266
- function buildTypeTree(editorConfig) {
267
- const t = {};
268
- const {
269
- nodes
270
- } = getKnownTypesAndNodes(editorConfig);
271
- for (const klass of nodes) {
272
- const type = klass.getType();
273
- t[type] = {
274
- klass,
275
- types: {}
276
- };
277
- }
278
- for (const baseRec of Object.values(t)) {
279
- if (baseRec) {
280
- const baseType = baseRec.klass.getType();
281
- for (let {
282
- klass
283
- } = baseRec; $isLexicalNode(klass.prototype); klass = Object.getPrototypeOf(klass)) {
284
- const {
285
- ownNodeType
286
- } = getStaticNodeConfig(klass);
287
- const superRec = ownNodeType && t[ownNodeType];
288
- if (superRec) {
289
- superRec.types[baseType] = true;
290
- }
291
- }
292
- }
293
- }
294
- return t;
295
- }
296
- function buildNodePredicate(klass) {
297
- return node => node instanceof klass;
298
- }
299
- function getPredicate(typeTree, {
300
- nodes
301
- }) {
302
- if (nodes === '*') {
303
- return ALWAYS_TRUE;
304
- }
305
- let types = {};
306
- const predicates = [];
307
- for (const klassOrPredicate of nodes) {
308
- if ('getType' in klassOrPredicate) {
309
- const type = klassOrPredicate.getType();
310
- if (types) {
311
- const tree = typeTree[type];
312
- if (!(tree !== undefined)) {
313
- formatDevErrorMessage(`Node class ${klassOrPredicate.name} with type ${type} not registered in editor`);
314
- }
315
- types = Object.assign(types, tree.types);
316
- }
317
- predicates.push(buildNodePredicate(klassOrPredicate));
318
- } else {
319
- types = undefined;
320
- predicates.push(klassOrPredicate);
321
- }
322
- }
323
- if (types) {
324
- return types;
325
- } else if (predicates.length === 1) {
326
- return predicates[0];
327
- }
328
- return node => {
329
- for (const predicate of predicates) {
330
- if (predicate(node)) {
331
- return true;
332
- }
333
- }
334
- return false;
335
- };
336
- }
337
- function makePrerender() {
338
- return {
339
- $createDOM: [],
340
- $decorateDOM: [],
341
- $exportDOM: [],
342
- $extractWithChild: [],
343
- $getDOMSlot: [],
344
- $shouldExclude: [],
345
- $shouldInclude: [],
346
- $updateDOM: []
347
- };
348
- }
349
-
350
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
351
-
352
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
353
-
354
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
-
356
- function ignoreNext2(acc) {
357
- return (node, _$next, editor) => acc(node, editor);
358
- }
359
- function ignoreNext3(acc) {
360
- return (node, a, _$next, editor) => acc(node, a, editor);
361
- }
362
- function ignoreNext4(acc) {
363
- return (node, a, b, _$next, editor) => acc(node, a, b, editor);
364
- }
365
- function ignoreNext5(acc) {
366
- return (node, a, b, c, _$next, editor) => acc(node, a, b, c, editor);
367
- }
368
- function merge2($acc, $getOverride) {
369
- return (node, editor) => {
370
- const $next = () => $acc(node, editor);
371
- const $override = $getOverride(node);
372
- return $override ? $override(node, $next, editor) : $next();
373
- };
374
- }
375
- function merge3(acc, $getOverride) {
376
- return (node, a, editor) => {
377
- const $next = () => acc(node, a, editor);
378
- const $override = $getOverride(node);
379
- return $override ? $override(node, a, $next, editor) : $next();
380
- };
381
- }
382
- function merge4($acc, $getOverride) {
383
- return (node, a, b, editor) => {
384
- const $next = () => $acc(node, a, b, editor);
385
- const $override = $getOverride(node);
386
- return $override ? $override(node, a, b, $next, editor) : $next();
387
- };
388
- }
389
- function merge5(acc, $getOverride) {
390
- return (node, a, b, c, editor) => {
391
- const $next = () => acc(node, a, b, c, editor);
392
- const $override = $getOverride(node);
393
- return $override ? $override(node, a, b, c, $next, editor) : $next();
394
- };
395
- }
396
- function sequence4($acc, $getOverride) {
397
- return (node, a, b, editor) => {
398
- $acc(node, a, b, editor);
399
- const $override = $getOverride(node);
400
- if ($override) {
401
- $override(node, a, b, editor);
402
- }
403
- };
404
- }
405
- function compilePrerenderKey(prerender, k, defaults, mergeFunction, ignoreNextFunction) {
406
- let acc = defaults[k];
407
- for (const pair of prerender[k]) {
408
- if (typeof pair[0] === 'function') {
409
- const [$predicate, $override] = pair;
410
- acc = mergeFunction(acc, node => $predicate(node) && $override || undefined);
411
- } else {
412
- const typeOverrides = pair[1];
413
- const compiled = {};
414
- for (const type in typeOverrides) {
415
- const arr = typeOverrides[type];
416
- if (arr) {
417
- compiled[type] = arr.reduce(($acc, $override) => mergeFunction($acc, () => $override), acc);
418
- }
419
- }
420
- acc = mergeFunction(acc, node => {
421
- const f = compiled[node.getType()];
422
- return f && ignoreNextFunction(f);
423
- });
424
- }
425
- }
426
- defaults[k] = acc;
427
- }
428
- function addOverride(prerender, k, predicateOrTypes, override) {
429
- if (!override) {
430
- return;
431
- }
432
- const arr = prerender[k];
433
- if (typeof predicateOrTypes === 'function') {
434
- arr.push([predicateOrTypes, override]);
435
- } else {
436
- const last = arr[arr.length - 1];
437
- let types;
438
- if (last && last[0] === 'types') {
439
- types = last[1];
440
- } else {
441
- types = {};
442
- arr.push(['types', types]);
443
- }
444
- for (const type in predicateOrTypes) {
445
- const typeArr = types[type] || [];
446
- types[type] = typeArr;
447
- typeArr.push(override);
448
- }
449
- }
450
- }
451
- function isWildcard(override) {
452
- return override.nodes === '*';
453
- }
454
- function sortedOverrides(overrides) {
455
- const byWildcard = [];
456
- const byPredicate = [];
457
- const byNode = [];
458
- for (const override of overrides) {
459
- if (isWildcard(override)) {
460
- byWildcard.push(override);
461
- } else if (Array.isArray(override.nodes)) {
462
- for (const klassOrPredicate of override.nodes) {
463
- if ($isLexicalNode(klassOrPredicate.prototype)) {
464
- byNode.push(override.nodes.length === 1 ? override : {
465
- ...override,
466
- nodes: [klassOrPredicate]
467
- });
468
- } else {
469
- byPredicate.push(override.nodes.length === 1 ? override : {
470
- ...override,
471
- nodes: [klassOrPredicate]
472
- });
473
- }
474
- }
475
- }
476
- }
477
- const depths = new Map();
478
- const depthOf = klass => {
479
- let depth = depths.get(klass);
480
- if (depth === undefined) {
481
- depth = 0;
482
- for (let k = klass; $isLexicalNode(k.prototype); k = Object.getPrototypeOf(k)) {
483
- depth++;
484
- }
485
- depths.set(klass, depth);
486
- }
487
- return depth;
488
- };
489
- byNode.sort((a, b) => depthOf(a.nodes[0]) - depthOf(b.nodes[0]));
490
- return [...byNode, ...byPredicate, ...byWildcard];
491
- }
492
- function precompileDOMRenderConfigOverrides(editorConfig, overrides) {
493
- const typeTree = buildTypeTree(editorConfig);
494
- const prerender = makePrerender();
495
- for (const override of sortedOverrides(overrides)) {
496
- const predicateOrTypes = getPredicate(typeTree, override);
497
- for (const k_ in prerender) {
498
- const k = k_;
499
- addOverride(prerender, k, predicateOrTypes, override[k]);
500
- }
501
- }
502
- return prerender;
503
- }
504
- function identity(v) {
505
- return v;
506
- }
507
- function compileDOMRenderConfigOverrides(editorConfig, {
508
- overrides
509
- }) {
510
- const prerender = precompileDOMRenderConfigOverrides(editorConfig, overrides);
511
- const dom = {
512
- ...DEFAULT_EDITOR_DOM_CONFIG,
513
- ...editorConfig.dom
514
- };
515
- compilePrerenderKey(prerender, '$createDOM', dom, merge2, ignoreNext2);
516
- compilePrerenderKey(prerender, '$exportDOM', dom, merge2, ignoreNext2);
517
- compilePrerenderKey(prerender, '$extractWithChild', dom, merge5, ignoreNext5);
518
- compilePrerenderKey(prerender, '$getDOMSlot', dom, merge3, ignoreNext3);
519
- compilePrerenderKey(prerender, '$shouldExclude', dom, merge3, ignoreNext3);
520
- compilePrerenderKey(prerender, '$shouldInclude', dom, merge3, ignoreNext3);
521
- compilePrerenderKey(prerender, '$updateDOM', dom, merge4, ignoreNext4);
522
- compilePrerenderKey(prerender, '$decorateDOM', dom, sequence4, identity);
523
- return dom;
524
- }
525
-
526
- /**
527
- * Copyright (c) Meta Platforms, Inc. and affiliates.
528
- *
529
- * This source code is licensed under the MIT license found in the
530
- * LICENSE file in the root directory of this source tree.
531
- *
532
- */
533
-
534
-
535
- /**
536
- * @experimental
537
- *
538
- * An extension that allows overriding the render and export behavior for an
539
- * editor. This is highly experimental and subject to change from one version
540
- * to the next.
541
- **/
542
- const DOMRenderExtension = defineExtension({
543
- build(editor, config, state) {
544
- return {
545
- defaults: contextFromPairs(config.contextDefaults, undefined)
546
- };
547
- },
548
- config: {
549
- contextDefaults: [],
550
- overrides: []
551
- },
552
- html: {
553
- // Define a RootNode export for $generateDOMFromRoot
554
- export: new Map([[RootNode, () => {
555
- const element = document.createElement('div');
556
- element.role = 'textbox';
557
- return {
558
- element
559
- };
560
- }]])
561
- },
562
- init(editorConfig, config) {
563
- editorConfig.dom = compileDOMRenderConfigOverrides(editorConfig, config);
564
- },
565
- mergeConfig(config, partial) {
566
- const merged = shallowMergeConfig(config, partial);
567
- for (const k of ['overrides', 'contextDefaults']) {
568
- if (partial[k]) {
569
- merged[k] = [...config[k], ...partial[k]];
570
- }
571
- }
572
- return merged;
573
- },
574
- name: DOMRenderExtensionName
575
- });
576
-
577
- function isStyleRule(rule) {
578
- return rule.constructor.name === CSSStyleRule.name;
579
- }
580
-
581
- /**
582
- * Inlines CSS rules from <style> tags onto matching elements as inline styles.
583
- * This is needed because apps like Excel generate HTML where styles live in
584
- * class-based <style> rules (e.g. `.xl65 { background: #FFFF00; color: blue; }`)
585
- * rather than inline styles. Since Lexical's import converters read inline styles,
586
- * we resolve stylesheet rules into inline styles before conversion.
587
- *
588
- * Mutates the DOM in-place. Original inline styles always take precedence over
589
- * stylesheet rules (matching CSS specificity behavior).
590
- */
591
- function inlineStylesFromStyleSheets(doc) {
592
- if (doc.querySelector('style') === null) {
593
- return;
594
- }
595
- const originalInlineStyles = new Map();
596
- function getOriginalInlineProps(el) {
597
- let props = originalInlineStyles.get(el);
598
- if (props === undefined) {
599
- props = new Set();
600
- for (let i = 0; i < el.style.length; i++) {
601
- props.add(el.style[i]);
602
- }
603
- originalInlineStyles.set(el, props);
604
- }
605
- return props;
606
- }
607
- try {
608
- for (const sheet of Array.from(doc.styleSheets)) {
609
- let rules;
610
- try {
611
- rules = sheet.cssRules;
612
- } catch (_unused) {
613
- continue;
614
- }
615
- for (const rule of Array.from(rules)) {
616
- if (!isStyleRule(rule)) {
617
- continue;
618
- }
619
- let elements;
620
- try {
621
- elements = doc.querySelectorAll(rule.selectorText);
622
- } catch (_unused2) {
623
- continue;
624
- }
625
- for (const el of Array.from(elements)) {
626
- if (!isHTMLElement(el)) {
627
- continue;
628
- }
629
- const originalProps = getOriginalInlineProps(el);
630
- for (let i = 0; i < rule.style.length; i++) {
631
- const prop = rule.style[i];
632
- if (!originalProps.has(prop)) {
633
- el.style.setProperty(prop, rule.style.getPropertyValue(prop), rule.style.getPropertyPriority(prop));
634
- }
635
- }
636
- }
637
- }
638
- }
639
- } catch (_unused3) {
640
- // styleSheets API not supported in this environment
641
- }
642
- }
643
- const IGNORE_TAGS = new Set(['STYLE', 'SCRIPT']);
644
-
645
- /**
646
- * How you parse your html string to get a document is left up to you. In the browser you can use the native
647
- * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
648
- * or an equivalent library and pass in the document here.
649
- */
650
- function $generateNodesFromDOM(editor, dom) {
651
- if (isDOMDocumentNode(dom)) {
652
- inlineStylesFromStyleSheets(dom);
653
- }
654
- const elements = isDOMDocumentNode(dom) ? dom.body.childNodes : dom.childNodes;
655
- const lexicalNodes = [];
656
- const allArtificialNodes = [];
657
- for (const element of elements) {
658
- if (!IGNORE_TAGS.has(element.nodeName)) {
659
- const lexicalNode = $createNodesFromDOM(element, editor, allArtificialNodes, false);
660
- if (lexicalNode !== null) {
661
- for (const node of lexicalNode) {
662
- lexicalNodes.push(node);
663
- }
664
- }
665
- }
666
- }
667
- $unwrapArtificialNodes(allArtificialNodes);
668
- return lexicalNodes;
669
- }
670
-
671
- /**
672
- * Generate DOM nodes from the editor state into the given container element,
673
- * using the editor's {@link EditorDOMRenderConfig}.
674
- * @experimental
675
- */
676
- function $generateDOMFromNodes(container, selection = null, editor = $getEditor()) {
677
- return $withRenderContext([contextValue(RenderContextExport, true)], editor)(() => {
678
- const root = $getRoot();
679
- const domConfig = $getEditorDOMRenderConfig(editor);
680
- const parentElementAppend = container.append.bind(container);
681
- for (const topLevelNode of root.getChildren()) {
682
- $appendNodesToHTML(editor, topLevelNode, parentElementAppend, selection, domConfig);
683
- }
684
- return container;
685
- });
686
- }
687
-
688
- /**
689
- * Generate DOM nodes from a root node into the given container element,
690
- * including the root node itself. Uses the editor's {@link EditorDOMRenderConfig}.
691
- * @experimental
692
- */
693
- function $generateDOMFromRoot(container, root = $getRoot()) {
694
- const editor = $getEditor();
695
- return $withRenderContext([contextValue(RenderContextExport, true), contextValue(RenderContextRoot, true)], editor)(() => {
696
- const selection = null;
697
- const domConfig = $getEditorDOMRenderConfig(editor);
698
- const parentElementAppend = container.append.bind(container);
699
- $appendNodesToHTML(editor, root, parentElementAppend, selection, domConfig);
700
- return container;
701
- });
702
- }
703
- function $generateHtmlFromNodes(editor, selection = null) {
704
- if (typeof document === 'undefined' || typeof window === 'undefined' && typeof global.window === 'undefined') {
705
- {
706
- formatDevErrorMessage(`To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom or use withDOM from @lexical/headless/dom before calling this function.`);
707
- }
708
- }
709
- return $generateDOMFromNodes(document.createElement('div'), selection, editor).innerHTML;
710
- }
711
- function $appendNodesToHTML(editor, currentNode, parentElementAppend, selection = null, domConfig = $getEditorDOMRenderConfig(editor)) {
712
- let shouldInclude = domConfig.$shouldInclude(currentNode, selection, editor);
713
- const shouldExclude = domConfig.$shouldExclude(currentNode, selection, editor);
714
- let target = currentNode;
715
- if (selection !== null && $isTextNode(currentNode)) {
716
- target = $sliceSelectedTextNodeContent(selection, currentNode, 'clone');
717
- }
718
- const exportProps = domConfig.$exportDOM(target, editor);
719
- const {
720
- element,
721
- after,
722
- append,
723
- $getChildNodes
724
- } = exportProps;
725
- if (!element) {
726
- return false;
727
- }
728
- const fragment = document.createDocumentFragment();
729
- const children = $getChildNodes ? $getChildNodes() : $isElementNode(target) ? target.getChildren() : [];
730
- const fragmentAppend = fragment.append.bind(fragment);
731
- for (const childNode of children) {
732
- const shouldIncludeChild = $appendNodesToHTML(editor, childNode, fragmentAppend, selection, domConfig);
733
- if (!shouldInclude && shouldIncludeChild && domConfig.$extractWithChild(currentNode, childNode, selection, 'html', editor)) {
734
- shouldInclude = true;
735
- }
736
- }
737
- if (shouldInclude && !shouldExclude) {
738
- if (isHTMLElement(element) || isDocumentFragment(element)) {
739
- if (append) {
740
- append(fragment);
741
- } else {
742
- element.append(fragment);
743
- }
744
- }
745
- parentElementAppend(element);
746
- if (after) {
747
- const newElement = after.call(target, element);
748
- if (newElement) {
749
- if (isDocumentFragment(element)) {
750
- element.replaceChildren(newElement);
751
- } else {
752
- element.replaceWith(newElement);
753
- }
754
- }
755
- }
756
- } else {
757
- parentElementAppend(fragment);
758
- }
759
- return shouldInclude;
760
- }
761
- function getConversionFunction(domNode, editor) {
762
- const {
763
- nodeName
764
- } = domNode;
765
- const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
766
- let currentConversion = null;
767
- if (cachedConversions !== undefined) {
768
- for (const cachedConversion of cachedConversions) {
769
- const domConversion = cachedConversion(domNode);
770
- if (domConversion !== null && (currentConversion === null ||
771
- // Given equal priority, prefer the last registered importer
772
- // which is typically an application custom node or HTMLConfig['import']
773
- (currentConversion.priority || 0) <= (domConversion.priority || 0))) {
774
- currentConversion = domConversion;
775
- }
776
- }
777
- }
778
- return currentConversion !== null ? currentConversion.conversion : null;
779
- }
780
- function $createNodesFromDOM(node, editor, allArtificialNodes, hasBlockAncestorLexicalNode, forChildMap = new Map(), parentLexicalNode) {
781
- const lexicalNodes = [];
782
- if (IGNORE_TAGS.has(node.nodeName)) {
783
- return lexicalNodes;
784
- }
785
- let currentLexicalNode = null;
786
- const transformFunction = getConversionFunction(node, editor);
787
- const transformOutput = transformFunction ? transformFunction(node) : null;
788
- let postTransform = null;
789
- if (transformOutput !== null) {
790
- postTransform = transformOutput.after;
791
- const transformNodes = transformOutput.node;
792
- currentLexicalNode = Array.isArray(transformNodes) ? transformNodes[transformNodes.length - 1] : transformNodes;
793
- if (currentLexicalNode !== null) {
794
- for (const [, forChildFunction] of forChildMap) {
795
- currentLexicalNode = forChildFunction(currentLexicalNode, parentLexicalNode);
796
- if (!currentLexicalNode) {
797
- break;
798
- }
799
- }
800
- if (currentLexicalNode) {
801
- lexicalNodes.push(...(Array.isArray(transformNodes) ? transformNodes : [currentLexicalNode]));
802
- }
803
- }
804
- if (transformOutput.forChild != null) {
805
- forChildMap.set(node.nodeName, transformOutput.forChild);
806
- }
807
- }
808
-
809
- // If the DOM node doesn't have a transformer, we don't know what
810
- // to do with it but we still need to process any childNodes.
811
- const children = node.childNodes;
812
- let childLexicalNodes = [];
813
- const hasBlockAncestorLexicalNodeForChildren = currentLexicalNode != null && $isRootOrShadowRoot(currentLexicalNode) ? false : currentLexicalNode != null && $isBlockElementNode(currentLexicalNode) || hasBlockAncestorLexicalNode;
814
- for (let i = 0; i < children.length; i++) {
815
- childLexicalNodes.push(...$createNodesFromDOM(children[i], editor, allArtificialNodes, hasBlockAncestorLexicalNodeForChildren, new Map(forChildMap), currentLexicalNode));
816
- }
817
- if (postTransform != null) {
818
- childLexicalNodes = postTransform(childLexicalNodes);
819
- }
820
- if (isBlockDomNode(node)) {
821
- if (!hasBlockAncestorLexicalNodeForChildren) {
822
- childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, $createParagraphNode);
823
- } else {
824
- childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, () => {
825
- const artificialNode = new ArtificialNode__DO_NOT_USE();
826
- allArtificialNodes.push(artificialNode);
827
- return artificialNode;
828
- });
829
- }
830
- }
831
- if (currentLexicalNode == null) {
832
- if (childLexicalNodes.length > 0) {
833
- // If it hasn't been converted to a LexicalNode, we hoist its children
834
- // up to the same level as it.
835
- for (const childNode of childLexicalNodes) {
836
- lexicalNodes.push(childNode);
837
- }
838
- } else {
839
- if (isBlockDomNode(node) && isDomNodeBetweenTwoInlineNodes(node)) {
840
- // Empty block dom node that hasnt been converted, we replace it with a linebreak if its between inline nodes
841
- lexicalNodes.push($createLineBreakNode());
842
- }
843
- }
844
- } else {
845
- if ($isElementNode(currentLexicalNode)) {
846
- // If the current node is a ElementNode after conversion,
847
- // we can append all the children to it.
848
- currentLexicalNode.append(...childLexicalNodes);
849
- }
850
- }
851
- return lexicalNodes;
852
- }
853
- function wrapContinuousInlines(domNode, nodes, createWrapperFn) {
854
- const textAlign = domNode.style.textAlign;
855
- const out = [];
856
- let continuousInlines = [];
857
- // wrap contiguous inline child nodes in para
858
- for (let i = 0; i < nodes.length; i++) {
859
- const node = nodes[i];
860
- if ($isBlockElementNode(node)) {
861
- if (textAlign && !node.getFormat()) {
862
- node.setFormat(textAlign);
863
- }
864
- out.push(node);
865
- } else {
866
- continuousInlines.push(node);
867
- if (i === nodes.length - 1 || i < nodes.length - 1 && $isBlockElementNode(nodes[i + 1])) {
868
- const wrapper = createWrapperFn();
869
- wrapper.setFormat(textAlign);
870
- wrapper.append(...continuousInlines);
871
- out.push(wrapper);
872
- continuousInlines = [];
873
- }
874
- }
875
- }
876
- return out;
877
- }
878
- function $unwrapArtificialNodes(allArtificialNodes) {
879
- // Replace artificial node with its children, inserting a linebreak
880
- // between adjacent artificial nodes
881
- for (const node of allArtificialNodes) {
882
- if (node.getParent() && node.getNextSibling() instanceof ArtificialNode__DO_NOT_USE) {
883
- node.insertAfter($createLineBreakNode());
884
- }
885
- }
886
- for (const node of allArtificialNodes) {
887
- const parent = node.getParent();
888
- if (parent) {
889
- parent.splice(node.getIndexWithinParent(), 1, node.getChildren());
890
- }
891
- }
892
- }
893
- function isDomNodeBetweenTwoInlineNodes(node) {
894
- if (node.nextSibling == null || node.previousSibling == null) {
895
- return false;
896
- }
897
- return isInlineDomNode(node.nextSibling) && isInlineDomNode(node.previousSibling);
898
- }
899
-
900
- export { $generateDOMFromNodes, $generateDOMFromRoot, $generateHtmlFromNodes, $generateNodesFromDOM, $getRenderContextValue, $withRenderContext, DOMRenderExtension, RenderContextExport, RenderContextRoot, contextUpdater, contextValue, createRenderState, domOverride };