Path: blob/master/src/packages/frontend/editors/slate/elements/heading/index.tsx
1698 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import React from "react";6import { register, SlateElement } from "../register";7import { useFileContext } from "@cocalc/frontend/lib/file-context";89export interface Heading extends SlateElement {10type: "heading";11level: number;12}1314register({15slateType: "heading",1617toSlate: ({ token, children }) => {18return {19type: "heading",20level: parseInt(token.tag?.slice(1) ?? "1"),21children,22};23},2425StaticElement: ({ attributes, children, element }) => {26if (element.type != "heading") throw Error("bug");2728const { HeadingTagComponent } = useFileContext();29if (HeadingTagComponent != null) {30// support custom heading component for static rendering.31return (32<HeadingTagComponent {...attributes} level={element.level}>33{children}34</HeadingTagComponent>35);36}37const { level } = element;38const id = toId(toText(element));39return React.createElement(`h${level}`, { id, ...attributes }, children);40},41});4243function toText(element) {44if (element.text != null) {45return element.text;46}47if (element.children != null) {48let s = "";49for (const child of element.children) {50s += toText(child);51}52return s;53}54return "";55}5657// We automatically generate id's for headers as follows:58// We make the underlying text lower case, replace spaces by dashes,59// and delete all other punctuation.60// This matches with some other markdown processor we were evidently once using.61function toId(text: string): string {62return text63.toLowerCase()64.replace(/\s+/g, "-")65.replace(/[.,\/#!$%\^&\*;:{}=_`~()]/g, "");66}676869