1
0
Fork 0
mirror of https://github.com/kou029w/quot.git synced 2025-01-19 08:28:09 +00:00
quot/app/views/components/editor.tsx

48 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-08-28 17:49:49 +09:00
import {
2022-08-29 12:24:40 +09:00
$createLineBreakNode,
2022-08-28 17:49:49 +09:00
$createParagraphNode,
$createTextNode,
$getRoot,
createEditor,
} from "lexical";
import { registerPlainText } from "@lexical/plain-text";
import { onCleanup, onMount } from "solid-js";
2022-09-01 23:54:20 +09:00
import type Pages from "../../protocol/pages";
2022-08-23 09:49:34 +09:00
import "./editor.css";
2022-08-28 17:49:49 +09:00
const editor = createEditor();
function ref(el: HTMLElement) {
editor.setRootElement(el);
}
2022-08-24 12:49:02 +09:00
export default (props: {
2022-08-24 09:50:35 +09:00
id: number;
2022-08-28 17:49:49 +09:00
title: string;
text: string;
2022-08-24 12:49:02 +09:00
onUpdatePage: (content: Pages.RequestContentPage) => void;
2022-08-28 17:49:49 +09:00
}) => {
const initialEditorState = () => {
const root = $getRoot();
if (root.getFirstChild()) return;
const paragraphNode = $createParagraphNode();
2022-08-29 12:24:40 +09:00
const text = props.text
.split("\n")
.flatMap((line) => [$createTextNode(line), $createLineBreakNode()])
.slice(0, -1);
paragraphNode.append(...text);
2022-08-28 17:49:49 +09:00
root.append(paragraphNode);
};
onCleanup(registerPlainText(editor, initialEditorState));
onMount(() => {
onCleanup(
editor.registerTextContentListener((text) => {
const [title] = text.split("\n");
props.onUpdatePage({ id: props.id, title: title ?? "", text });
})
);
editor.focus();
});
return <article ref={ref} class="editor" contenteditable />;
};