import { $applyNodeReplacement, type EditorConfig, type LexicalNode, type NodeKey, type SerializedTextNode, TextNode, } from "lexical"; export type SerializedVariableNode = SerializedTextNode & { variableName: string; }; export class VariableNode extends TextNode { __variableName: string; static getType(): string { return "variable"; } static clone(node: VariableNode): VariableNode { return new VariableNode(node.__variableName, node.__text, node.__key); } constructor(variableName: string, text?: string, key?: NodeKey) { super(text ?? `{{${variableName}}}`, key); this.__variableName = variableName; } createDOM(config: EditorConfig): HTMLElement { const dom = super.createDOM(config); // Add custom class for styling (e.g. slight background color) dom.classList.add("lexical-variable"); // Also give it a data attribute so we can easily find it dom.setAttribute("data-variable", this.__variableName); return dom; } exportJSON(): SerializedVariableNode { return { ...super.exportJSON(), type: "variable", variableName: this.__variableName, version: 1, }; } static importJSON(serializedNode: SerializedVariableNode): VariableNode { const node = $createVariableNode(serializedNode.variableName); node.setFormat(serializedNode.format); node.setDetail(serializedNode.detail); node.setMode(serializedNode.mode); node.setStyle(serializedNode.style); return node; } } export function $createVariableNode(variableName: string): VariableNode { const node = new VariableNode(variableName); node.setMode("segmented"); return $applyNodeReplacement(node); } export function $isVariableNode(node: LexicalNode | null | undefined): node is VariableNode { return node instanceof VariableNode; }