Path: blob/master/src/packages/frontend/editors/slate/elements/math/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 { Element } from "slate";7import { register, RenderElementProps, SlateElement } from "../register";8import { useFileContext } from "@cocalc/frontend/lib/file-context";9import DefaultMath from "@cocalc/frontend/components/math/ssr";1011export interface DisplayMath extends SlateElement {12type: "math_block";13value: string;14isVoid: true;15}1617export interface InlineMath extends SlateElement {18type: "math_inline";19value: string;20display?: boolean; // inline but acts as displayed math21isVoid: true;22isInline: true;23}2425export const StaticElement: React.FC<RenderElementProps> = ({26attributes,27element,28}) => {29const { MathComponent } = useFileContext();30if (element.type != "math_block" && element.type != "math_inline") {31// type guard.32throw Error("bug");33}34const C = MathComponent ?? DefaultMath;35return (36<span {...attributes}>37<C38data={wrap(39element.value,40element.type == "math_inline" && !element.display41)}42inMarkdown43/>44</span>45);46};4748function wrap(math, isInline) {49math = "$" + math + "$";50if (!isInline) {51math = "$" + math + "$";52}53return math;54}5556register({57slateType: ["math_inline", "math_inline_double"],58StaticElement,59toSlate: ({ token }) => {60return {61type: "math_inline",62value: stripMathEnvironment(token.content),63isVoid: true,64isInline: true,65children: [{ text: "" }],66display: token.type == "math_inline_double",67} as Element;68},69});7071export function toDisplayMath({ token }) {72return {73type: "math_block",74value: stripMathEnvironment(token.content).trim(),75isVoid: true,76children: [{ text: "" }],77} as Element;78}7980register({81slateType: ["math_block", "math_block_eqno"],82StaticElement,83toSlate: toDisplayMath,84});8586export function stripMathEnvironment(s: string): string {87// These environments get detected, but we must remove them, since once in88// math mode they make no sense. All the other environments do make sense.89for (const env of ["math", "displaymath"]) {90if (s.startsWith(`\\begin{${env}}`)) {91return s.slice(92`\\begin{${env}}`.length,93s.length - `\\end{${env}}`.length94);95}96}97return s;98}99100101