Skip to content

Commit

Permalink
Add suport for custom font size,color and highlight color for importe…
Browse files Browse the repository at this point in the history
…d text nodes
  • Loading branch information
citruscai committed Oct 30, 2024
1 parent efc55d2 commit 7f6388a
Showing 1 changed file with 56 additions and 1 deletion.
57 changes: 56 additions & 1 deletion packages/lexical-playground/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ import {$createLinkNode} from '@lexical/link';
import {$createListItemNode, $createListNode} from '@lexical/list';
import {LexicalComposer} from '@lexical/react/LexicalComposer';
import {$createHeadingNode, $createQuoteNode} from '@lexical/rich-text';
import {$createParagraphNode, $createTextNode, $getRoot} from 'lexical';
import {
$createParagraphNode,
$createTextNode,
$getRoot,
$isTextNode, DOMConversion,
DOMConversionMap,
TextNode} from 'lexical';
import * as React from 'react';

import {isDevPlayground} from './appSettings';
Expand Down Expand Up @@ -124,13 +130,62 @@ function App(): JSX.Element {
: emptyEditor
? undefined
: $prepopulatedRichText,
html: {import: buildImportMap()},
namespace: 'Playground',
nodes: [...PlaygroundNodes],
onError: (error: Error) => {
throw error;
},
theme: PlaygroundEditorTheme,
};
function buildImportMap(): DOMConversionMap {
const importMap: DOMConversionMap = {};
// Create a conversion map that overrides every conversion from
// TextNode with a higher priority version that does the same thing
// and then adds extra styles to the node if applicable

for (const [tag, fn] of Object.entries(TextNode.importDOM()!)) {
importMap[tag] = (node) => {
const importer = fn(node);
if (!importer) {
return null;
}
return {
conversion: (element) => {
const output = importer.conversion(element);

if (
output &&
output.node &&
!Array.isArray(output.node) &&
$isTextNode(output.node)
) {
let extraStyles = '';
// read extra styles from elmeent
if (element.style.cssText.includes('font-size')) {
extraStyles += `font-size: ${element.style.fontSize};`;
}
if (element.style.cssText.includes('background-color')) {
extraStyles += `background-color: ${element.style.backgroundColor};`;
}
if (element.style.cssText.includes('color')) {
extraStyles += `color: ${element.style.color};`;
}
if (extraStyles.length > 0) {
output.node.setStyle(output.node.getStyle() + extraStyles);
}
}
return output;
},
priority: Math.min(
4,
(importer.priority || 0) + 1,
) as DOMConversion['priority'],
};
};
}
return importMap;
}

return (
<LexicalComposer initialConfig={initialConfig}>
Expand Down

0 comments on commit 7f6388a

Please sign in to comment.