Path: blob/master/src/packages/frontend/editors/slate/static-markdown.tsx
1691 views
/*1Static Markdown23This is a react component that renders markdown text using React. See the4comments in mostly-static-markdown.tsx for more details, since that's a very5similar, but more complicated component.67A constraint of this component is that it should easily render in the next.js8application.9*/1011import { CSSProperties, useEffect, useState } from "react";12import "./elements/init-ssr";13import { getStaticRender } from "./elements/register";14import Leaf from "./leaf";15import { markdown_to_slate as markdownToSlate } from "./markdown-to-slate";16import { ChangeContext } from "./use-change";1718interface Props {19value: string;20style?: CSSProperties;21className?: string;22}2324type PartialSlateEditor = any; // TODO2526export default function StaticMarkdown({ value, style, className }: Props) {27const [editor, setEditor] = useState<PartialSlateEditor>({28children: markdownToSlate(value),29});30const [change, setChange] = useState<number>(0);31useEffect(() => {32setChange(change + 1);33if (change > 0) {34// no need to set it the first time because it is set in the useState initialization.35// and we *have* to set it there so it works for server side rendering and exporting to html/pdf.36setEditor({ children: markdownToSlate(value) });37}38}, [value]);3940if (editor == null) {41return null;42}4344return (45<ChangeContext.Provider46value={{47change,48editor,49setEditor: (editor) => {50setEditor(editor);51setChange(change + 1);52},53}}54>55<div style={{ width: "100%", ...style }} className={className}>56{editor.children.map((element, n) => {57return <RenderElement key={n} element={element} />;58})}59</div>60</ChangeContext.Provider>61);62}6364function RenderElement({ element }) {65let children: React.JSX.Element[] = [];66if (element["children"]) {67let n = 0;68for (const child of element["children"]) {69children.push(<RenderElement key={n} element={child} />);70n += 1;71}72}73if (element["type"]) {74const C = getStaticRender(element.type);75return <C children={children} element={element} attributes={{} as any} />;76}77// It's text78return (79<Leaf leaf={element} text={{} as any} attributes={{} as any}>80{element["text"]}81</Leaf>82);83}848586