1
0
Fork 0
polaris-task-force/src/components/frontend/intelligence/LexicalRichTextEditor.tsx

207 lines
6.4 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import { $createParagraphNode, $getRoot, type EditorThemeClasses } from "lexical";
import { HorizontalRuleNode } from "@lexical/extension";
import { AutoLinkNode, LinkNode } from "@lexical/link";
import { HeadingNode, QuoteNode } from "@lexical/rich-text";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { HorizontalRulePlugin } from "@lexical/react/LexicalHorizontalRulePlugin";
import { CheckListPlugin } from "@lexical/react/LexicalCheckListPlugin";
import { ListPlugin } from "@lexical/react/LexicalListPlugin";
import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
import { ListItemNode, ListNode } from "@lexical/list";
import { cn } from "@/lib/utils";
import { LexicalRichTextToolbar } from "./LexicalRichTextToolbar";
export type LexicalJson = Record<string, unknown>;
const EXTERNAL_STATE_TAG = "polaris-external-state";
const EDITOR_NODES = [
HeadingNode,
QuoteNode,
ListNode,
ListItemNode,
HorizontalRuleNode,
LinkNode,
AutoLinkNode,
] as const;
const EDITOR_THEME: EditorThemeClasses = {
heading: {
h2: "mt-4 mb-2 text-lg font-semibold",
h3: "mt-3 mb-2 text-base font-semibold",
h4: "mt-2 mb-1 text-sm font-semibold",
},
hr: "my-4 border-border",
link: "text-primary underline underline-offset-2",
list: {
checklist: "pl-6",
listitem: "mb-1 pl-1",
listitemChecked: "text-muted-foreground line-through",
listitemUnchecked: "",
nested: { list: "pl-6", listitem: "pl-1" },
ol: "mb-4 list-decimal pl-6",
ul: "mb-4 list-disc pl-6",
},
paragraph: "mb-4 last:mb-0",
quote: "mb-4 border-l-2 border-border pl-3 italic text-muted-foreground",
text: {
bold: "font-semibold",
code: "rounded-sm bg-muted px-1 font-mono text-xs",
italic: "italic",
strikethrough: "line-through",
underline: "underline",
underlineStrikethrough: "underline line-through",
},
};
function serializeValue(value: LexicalJson | null): string | null {
return value === null ? null : (JSON.stringify(value) ?? null);
}
function EditablePlugin({ disabled }: { disabled: boolean }) {
const [editor] = useLexicalComposerContext();
useEffect(() => {
editor.setEditable(!disabled);
}, [disabled, editor]);
return null;
}
function ExternalStatePlugin({
lastEmittedJsonRef,
value,
}: {
lastEmittedJsonRef: { current: string | null };
value: LexicalJson | null;
}) {
const [editor] = useLexicalComposerContext();
const previousValueRef = useRef(value);
useEffect(() => {
if (previousValueRef.current === value) return;
previousValueRef.current = value;
const serializedValue = serializeValue(value);
if (serializedValue !== null && serializedValue === lastEmittedJsonRef.current) {
lastEmittedJsonRef.current = null;
return;
}
lastEmittedJsonRef.current = null;
if (serializedValue === null) {
editor.update(
() => {
const root = $getRoot();
root.clear();
root.append($createParagraphNode());
},
{ tag: EXTERNAL_STATE_TAG },
);
return;
}
editor.setEditorState(editor.parseEditorState(serializedValue), { tag: EXTERNAL_STATE_TAG });
}, [editor, lastEmittedJsonRef, value]);
return null;
}
function SerializeOnChangePlugin({
lastEmittedJsonRef,
onChange,
}: {
lastEmittedJsonRef: { current: string | null };
onChange: (json: LexicalJson) => void;
}) {
const [editor] = useLexicalComposerContext();
const onChangeRef = useRef(onChange);
useEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);
useEffect(
() =>
editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, editorState, tags }) => {
if (tags.has(EXTERNAL_STATE_TAG) || (dirtyElements.size === 0 && dirtyLeaves.size === 0)) {
return;
}
const json: LexicalJson = { ...editorState.toJSON() };
lastEmittedJsonRef.current = JSON.stringify(json);
onChangeRef.current(json);
}),
[editor, lastEmittedJsonRef],
);
return null;
}
export interface LexicalRichTextEditorProps {
value: LexicalJson | null;
onChange: (json: LexicalJson) => void;
placeholder?: string;
disabled?: boolean;
}
export function LexicalRichTextEditor({
disabled = false,
onChange,
placeholder = "Write the operation details...",
value,
}: LexicalRichTextEditorProps) {
const lastEmittedJsonRef = useRef<string | null>(null);
const [initialConfig] = useState(() => ({
namespace: "PolarisSideOpNarrative",
nodes: EDITOR_NODES,
onError: (error: Error) => console.error("Lexical editor error.", error),
editorState: serializeValue(value),
theme: EDITOR_THEME,
editable: !disabled,
}));
return (
<LexicalComposer initialConfig={initialConfig}>
<div
className={cn(
"rounded-md border border-input bg-background transition-[box-shadow] focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",
disabled && "cursor-not-allowed opacity-60",
)}
>
<LexicalRichTextToolbar disabled={disabled} />
<div className="relative min-h-[120px]">
<RichTextPlugin
contentEditable={
<ContentEditable
className="min-h-[120px] px-3 py-2 text-sm outline-none"
aria-label="Rich text editor"
aria-placeholder={placeholder}
placeholder={<span className="sr-only">{placeholder}</span>}
/>
}
placeholder={
<div className="pointer-events-none absolute left-3 top-2 text-sm text-muted-foreground">
{placeholder}
</div>
}
ErrorBoundary={LexicalErrorBoundary}
/>
</div>
</div>
<HistoryPlugin />
<ListPlugin />
<CheckListPlugin />
<HorizontalRulePlugin />
<EditablePlugin disabled={disabled} />
<ExternalStatePlugin value={value} lastEmittedJsonRef={lastEmittedJsonRef} />
<SerializeOnChangePlugin onChange={onChange} lastEmittedJsonRef={lastEmittedJsonRef} />
</LexicalComposer>
);
}