/** * Converts plain text (from client textareas) into Payload-compatible lexical * editor state so richText fields can be populated from simple forms. * * Paragraph breaks: double newlines split paragraphs; single newlines become * line breaks inside a paragraph. */ interface LexicalTextNode { type: "text"; version: 1; detail: 0; format: 0; mode: "normal"; style: ""; text: string; [k: string]: unknown; } interface LexicalLinebreakNode { type: "linebreak"; version: 1; [k: string]: unknown; } type LexicalInlineNode = LexicalTextNode | LexicalLinebreakNode; interface LexicalParagraphNode { type: "paragraph"; version: 1; direction: "ltr"; format: ""; indent: 0; textFormat: 0; textStyle: ""; children: LexicalInlineNode[]; [k: string]: unknown; } export interface PlaintextLexicalState { root: { type: "root"; version: 1; direction: "ltr"; format: ""; indent: 0; children: LexicalParagraphNode[]; }; [k: string]: unknown; } function inlineNodes(text: string): LexicalInlineNode[] { const nodes: LexicalInlineNode[] = []; const lines = text.split("\n"); for (let i = 0; i < lines.length; i++) { if (lines[i].length > 0) { nodes.push({ type: "text", version: 1, detail: 0, format: 0, mode: "normal", style: "", text: lines[i] }); } if (i < lines.length - 1) { nodes.push({ type: "linebreak", version: 1 }); } } return nodes; } export function plaintextToLexical(text: string): PlaintextLexicalState { const trimmed = text.trim(); const paragraphs = trimmed.length === 0 ? [""] : trimmed.split(/\n{2,}/); return { root: { type: "root", version: 1, direction: "ltr", format: "", indent: 0, children: paragraphs.map((para) => ({ type: "paragraph", version: 1, direction: "ltr", format: "", indent: 0, textFormat: 0, textStyle: "", children: inlineNodes(para), })), }, }; }