Plate
PlateEditorsCreateTemplates
GitHub16kGitHub
DiscordDiscord
    • Stream
    • Copilot
    • Prompt Editor
  • Comments
  • Discussion
  • Suggestions
    • Basic Blocks
      • Blockquote
      • Heading
      • Horizontal Rule
    • Board
    • Callout
    • Code Block
    • Column
    • Date
    • Equation
    • FieldExperimental
    • Link
    • Media
    • MentionElement
    • Table
    • Table of Contents
    • Footnote
    • Details
  • Marks
    • Bold
    • Italic
    • Underline
    • Code
    • Highlight
    • Keyboard Input
    • Strikethrough
    • Subscript
    • Superscript
      • Font
      • Line Height
      • Text Align
      • Clear Formatting
      • Format Painter
    • Indent
    • List
      • Exit Break
      • Single Block
      • Trailing Block
    • Autoformat
    • Block Menu
    • Block Placeholder
    • Combobox
      • Emoji
      • MentionElement
      • Slash Command
    • Drag & Drop
    • Navigation Feedback
    • Linting
    • Tabbable
    • Toolbar
    • Yjs
    • Multi SelectEditor
    • DOCX
    • HTML
    • Markdown

Equation

PreviousNext

Block and inline LaTeX equation nodes rendered with KaTeX.

Equation ElementEquation Toolbar ButtonPlus

Equation adds block and inline void nodes for LaTeX expressions. Both nodes store source in latex and render through KaTeX. This page covers kit setup, block versus inline ownership, insertion, input rules, Markdown serialization, HTML copy and paste, and registry UI behavior.

Loading…
DateField

On This Page

FeaturesFast pathAdd the kitRender the nodesAdd the toolbar buttonOwnershipManual setupInstall packageAdd pluginsAdd static renderingInsert equationsValue shapeInput rulesRenderingMarkdownHTMLPlate PlusAPI Reference
Build your editor
Production-ready AI template and reusable components.
Get all-access

Features

  • Block equation element.
  • Inline void inlineEquation element.
  • Scoped block and inline equation insertion updates.
  • KaTeX rendering in editable and static UI.
  • $...$ inline input rule and $$ block input rule.
  • Markdown round-trip for inline math and block math.
  • HTML copy and paste that keeps the TeX, including math copied from KaTeX pages and Wikipedia, and rebuilds it from MathML when a copy lost it.
Report an issue

Fast path

Add the kit

MathKit installs both equation plugins, their registry components, and the default math input rules.

'use client';
 
import 'katex/dist/katex.min.css';
import { cn } from 'cn';
import katex, { type KatexOptions } from 'katex';
import { CornerDownLeftIcon, RadicalIcon } from 'lucide-react';
import { isHotkey, NodeApi } from 'platejs';
import { MathRules } from 'platejs/math';
import { EquationPlugin, InlineEquationPlugin } from 'platejs/math/react';
import {
  type EditorElementProps,
  EditorElement,
  useEditor,
  useEditorReadOnly,
  useElement,
  useElementSelected,
} from 'platejs/react';
import * as React from 'react';
import TextareaAutosize, {
  type TextareaAutosizeProps,
} from 'react-textarea-autosize';
 
import { Button } from '@/components/ui/button';
import {
  FloatingPopover,
  FloatingPopoverContent,
  FloatingPopoverTrigger,
} from '@/components/editor/floating-popover';
import { inlineSuggestionVariants } from '@/lib/inline-suggestion';
 
function useEquation({
  element,
  katexRef,
  options,
}: {
  element: { latex: string };
  katexRef: React.RefObject<HTMLDivElement | null>;
  options?: KatexOptions;
}) {
  React.useEffect(() => {
    if (!katexRef.current) return;
 
    katex.render(element.latex, katexRef.current, {
      ...options,
      throwOnError: false,
    });
  }, [element.latex, katexRef, options]);
}
 
// Undo and redo restore a selection the user did not move into an equation, so
// it must not open the equation's input and take focus from the editor.
function useSelectedByUser() {
  const editor = useEditor();
 
  return (selected: boolean) =>
    selected && !editor.read.lastCommit()?.tags.includes('historic');
}
 
export function EquationElement(
  props: EditorElementProps<typeof EquationPlugin> & {
    lineBreakBadge?: React.ReactNode;
  }
) {
  const selected = useElementSelected({ mode: 'text' });
  const selectedByUser = useSelectedByUser();
  const [open, setOpen] = React.useState(() => selectedByUser(selected));
  const katexRef = React.useRef<HTMLDivElement | null>(null);
  const { lineBreakBadge } = props;
 
  useEquation({
    element: props.element,
    katexRef,
    options: {
      displayMode: true,
      errorColor: '#cc0000',
      fleqn: false,
      leqno: false,
      macros: { '\\f': '#1f(#2)' },
      output: 'htmlAndMathml',
      strict: 'warn',
      throwOnError: false,
      trust: false,
    },
  });
 
  return (
    <EditorElement className="my-1" {...props}>
      <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
        <FloatingPopoverTrigger>
          <button
            aria-label={
              props.element.latex.length > 0 ? 'Edit equation' : 'Add equation'
            }
            className={cn(
              'group flex w-full cursor-pointer select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
              props.element.latex.length === 0
                ? 'bg-muted p-3 pe-9'
                : 'px-2 py-1'
            )}
            data-selected={selected}
            contentEditable={false}
            type="button"
          >
            {props.element.latex.length > 0 ? (
              <span ref={katexRef} dir="ltr" />
            ) : (
              <span className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
                <RadicalIcon className="size-6 text-muted-foreground/80" />
                <span>Add a Tex equation</span>
              </span>
            )}
            {lineBreakBadge}
          </button>
        </FloatingPopoverTrigger>
 
        <EquationPopoverContent
          open={open}
          placeholder={
            'f(x) = \\begin{cases}\n  x^2, &\\quad x > 0 \\\\\n  0, &\\quad x = 0 \\\\\n  -x^2, &\\quad x < 0\n\\end{cases}'
          }
          isInline={false}
          setOpen={setOpen}
        />
      </FloatingPopover>
 
      {props.children}
    </EditorElement>
  );
}
 
export function InlineEquationElement(
  props: EditorElementProps<typeof InlineEquationPlugin>
) {
  const { element } = props;
  const katexRef = React.useRef<HTMLDivElement | null>(null);
  const selected = useElementSelected({ mode: 'text' });
  const collapsedSelected = useElementSelected({ mode: 'collapsed' });
  const selectedByUser = useSelectedByUser();
  const [popoverState, setPopoverState] = React.useState(() => ({
    open: selectedByUser(collapsedSelected),
    selected,
  }));
  const openAtPointerDownRef = React.useRef(false);
  const open =
    popoverState.selected === selected
      ? popoverState.open
      : selected && (popoverState.open || selectedByUser(collapsedSelected));
 
  if (popoverState.selected !== selected) {
    setPopoverState({ open, selected });
  }
 
  const setOpen = React.useCallback(
    (nextOpen: boolean) => {
      setPopoverState({ open: nextOpen, selected });
    },
    [selected]
  );
 
  useEquation({
    element,
    katexRef,
    options: {
      displayMode: false,
      errorColor: '#cc0000',
      fleqn: false,
      leqno: false,
      macros: { '\\f': '#1f(#2)' },
      output: 'htmlAndMathml',
      strict: 'warn',
      throwOnError: false,
      trust: false,
    },
  });
 
  return (
    <EditorElement
      {...props}
      className="mx-1 inline-block rounded-sm select-none"
    >
      <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
        <FloatingPopoverTrigger>
          <button
            aria-label={
              element.latex.length > 0 ? 'Edit equation' : 'Add equation'
            }
            className={cn(
              'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
              'h-6',
              inlineSuggestionVariants({ on: 'parent' }),
              ((element.latex.length > 0 && open) || selected) &&
                'after:bg-editor-primary/15',
              element.latex.length === 0 &&
                'text-muted-foreground after:bg-muted-foreground/10'
            )}
            contentEditable={false}
            onClick={(event) => {
              if (event.detail === 0 || openAtPointerDownRef.current) return;
 
              event.preventDefault();
              setOpen(true);
            }}
            onPointerDown={() => {
              openAtPointerDownRef.current = open;
            }}
            type="button"
          >
            <span
              ref={katexRef}
              className={cn(
                element.latex.length === 0 && 'hidden',
                'font-mono leading-none'
              )}
              dir="ltr"
            />
            {element.latex.length === 0 && (
              <span>
                <RadicalIcon className="me-1 inline-block h-[19px] w-4 py-[1.5px] align-text-bottom" />
                New equation
              </span>
            )}
          </button>
        </FloatingPopoverTrigger>
 
        <EquationPopoverContent
          className="my-auto"
          open={open}
          placeholder="E = mc^2"
          setOpen={setOpen}
          isInline
        />
      </FloatingPopover>
 
      {props.children}
    </EditorElement>
  );
}
 
function EquationPopoverContent({
  className,
  isInline,
  open,
  setOpen,
  ...props
}: {
  isInline: boolean;
  open: boolean;
  setOpen: (open: boolean) => void;
} & TextareaAutosizeProps) {
  const editor = useEditor();
  const readOnly = useEditorReadOnly();
  const element = useElement(isInline ? InlineEquationPlugin : EquationPlugin);
  const key = editor.key(element);
  const ref = React.useRef<HTMLTextAreaElement>(null);
  const [draft, setDraft] = React.useState({
    open,
    source: element.latex,
    value: element.latex,
  });
  const changedSource = draft.source !== element.latex || draft.open !== open;
  const value = changedSource ? element.latex : draft.value;
 
  if (changedSource) {
    setDraft({ open, source: element.latex, value: element.latex });
  }
 
  React.useEffect(() => {
    if (!open) return undefined;
    const timeout = globalThis.setTimeout(() => {
      ref.current?.focus();
      ref.current?.select();
    }, 0);
    return () => globalThis.clearTimeout(timeout);
  }, [open]);
 
  if (readOnly) return null;
 
  const close = (commit: boolean, direction: 'after' | 'before' = 'after') => {
    const current = editor.read.nodes.get(key);
    setOpen(false);
    // Move the selection before saving: undoing the save restores the
    // selection from before it, and a caret inside an inline equation would
    // reopen its input.
    if (isInline) {
      const point = editor.read.points[direction](element);
      if (point) editor.update.selection.set(point);
    } else if (current) {
      editor.update.selection.setNodes([current[1]]);
    }
    if (
      commit &&
      current &&
      NodeApi.isElement(current[0]) &&
      current[0].type === element.type &&
      current[0].latex === element.latex &&
      value !== element.latex &&
      !editor.read.view.isReadOnly() &&
      !editor.read.nodes.elementReadOnly({ at: key })
    ) {
      const plugin = isInline ? InlineEquationPlugin : EquationPlugin;
      editor
        .plugin(plugin)
        .update({ history: 'new-batch' })
        .set({ latex: value }, { at: current[1] });
    }
    editor.api.dom.focus();
  };
 
  return (
    <FloatingPopoverContent
      className="flex gap-2"
      onFinalFocus={(event) => {
        if (isInline) event.preventDefault();
      }}
      onEscapeKeyDown={(event) => event.preventDefault()}
      contentEditable={false}
    >
      <TextareaAutosize
        ref={ref}
        className={cn('max-h-[50vh] grow resize-none p-2 text-sm', className)}
        dir="ltr"
        value={value}
        onChange={(event) =>
          setDraft({
            open,
            source: element.latex,
            value: event.currentTarget.value,
          })
        }
        onKeyDown={(event) => {
          if (event.nativeEvent.isComposing) return;
          if (isHotkey('enter')(event)) {
            event.preventDefault();
            close(true);
          } else if (isHotkey('escape')(event)) {
            event.preventDefault();
            close(false);
          } else if (isInline) {
            const { selectionEnd, selectionStart } = event.currentTarget;
            const atLeftEdge =
              selectionStart === 0 &&
              selectionEnd === 0 &&
              isHotkey('ArrowLeft')(event);
            const atRightEdge =
              selectionStart === value.length &&
              selectionEnd === value.length &&
              isHotkey('ArrowRight')(event);
 
            if (atLeftEdge || atRightEdge) {
              event.preventDefault();
              const node = editor.api.dom.resolveDOMNode(element);
              const rtl = !!node && getComputedStyle(node).direction === 'rtl';
 
              close(true, atLeftEdge === rtl ? 'after' : 'before');
            }
          }
        }}
        autoFocus
        {...props}
      />
      <Button variant="secondary" className="px-3" onClick={() => close(true)}>
        Done{' '}
        <CornerDownLeftIcon className="size-3.5 [&:dir(rtl)]:-scale-x-100" />
      </Button>
    </FloatingPopoverContent>
  );
}
 
export const MathKit = [
  InlineEquationPlugin.configure({
    component: InlineEquationElement,
    inputRules: [MathRules.markdown({ variant: '$' })],
  }),
  EquationPlugin.configure({
    component: EquationElement,
    inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
  }),
];
'use client';
 
import 'katex/dist/katex.min.css';
import { cn } from 'cn';
import katex, { type KatexOptions } from 'katex';
import { CornerDownLeftIcon, RadicalIcon } from 'lucide-react';
import { isHotkey, NodeApi } from 'platejs';
import { MathRules } from 'platejs/math';
import { EquationPlugin, InlineEquationPlugin } from 'platejs/math/react';
import {
  type EditorElementProps,
  EditorElement,
  useEditor,
  useEditorReadOnly,
  useElement,
  useElementSelected,
} from 'platejs/react'








































































































































































































































































































































































import { createEditor } from 'platejs/react';
 
import { MathKit } from '@/components/editor/math';
 
export const editor = createEditor({
  plugins: MathKit,
});
import { createEditor } from 'platejs/react';
 
import { MathKit } from '@/components/editor/math';
 
export const editor = createEditor({
  plugins: MathKit,

Render the nodes

math owns the block equation, inline equation, editable popover, textarea input, and KaTeX render target.

'use client';
 
import 'katex/dist/katex.min.css';
import { cn } from 'cn';
import katex, { type KatexOptions } from 'katex';
import { CornerDownLeftIcon, RadicalIcon } from 'lucide-react';
import { isHotkey, NodeApi } from 'platejs';
import { MathRules } from 'platejs/math';
import { EquationPlugin, InlineEquationPlugin } from 'platejs/math/react';
import {
  type EditorElementProps,
  EditorElement,
  useEditor,
  useEditorReadOnly,
  useElement,
  useElementSelected,
} from








































































































































































































































































































































































Add the toolbar button

equation-toolbar-button inserts an inline equation through editor.plugin(BaseInlineEquationPlugin).update.insert().

'use client';
 
import { RadicalIcon } from 'lucide-react';
import { BaseInlineEquationPlugin } from 'platejs/math';
import { useEditor } from 'platejs/react';
import * as React from 'react';
 
import { ToolbarButton } from '@/components/editor/toolbar';
 
export function InlineEquationToolbarButton(
  props: React.ComponentProps<typeof ToolbarButton>
) {
  const editor = useEditor();
 
  return (
    <









Ownership

LayerOwnerWhat It Does
platejs/mathPackageExports the base equation family, its Markdown math and inlineMath mappings, and MathRules.
platejs/math/reactPackageExports the React equation descriptors.
mathRegistryAdds block and inline React plugins with input rules and the editable equation elements.
math-staticRegistryAdds static equation elements for read-only rendering.
equation-toolbar-buttonRegistry UIInserts inline equations from the toolbar.
platejs/markdownPackageRuns the equation plugins' Markdown mappings when MarkdownPlugin is configured with remark-math.
platejs/docx/exportPackageExports equations as Word math. See DOCX.

platejs/math and platejs/math/react load no KaTeX. The math and math-static components and platejs/docx/export import katex, so install it wherever one of them runs.

Block and inline equations share the EquationElement shape, but they are different node types with different plugin names.

Manual setup

Install package

pnpm add platejs katex@0.16.22 lucide-react react-textarea-autosize
pnpm add platejs katex@0.16.22 lucide-react react-textarea-autosize

The math and math-static components import the KaTeX stylesheet, katex/dist/katex.min.css, and icons from lucide-react. math also imports react-textarea-autosize for its source input.

Add plugins

Use both React plugins when your editor supports block and inline equations.

import { MathRules } from 'platejs/math';
import {
  EquationPlugin,
  InlineEquationPlugin,
} from 'platejs/math/react';
import { createEditor } from 'platejs/react';
 
import {
  EquationElement,
  InlineEquationElement,
} from '@/components/editor/math';
 
export const editor = createEditor({
  plugins: [
    InlineEquationPlugin.configure({
      component: InlineEquationElement,
      inputRules: [MathRules.markdown({ variant: '$' })],
    }),
    EquationPlugin.configure({




Add static rendering

Use the base kit when rendering read-only output with platejs/static.

import { cn } from 'cn';
 
import 'katex/dist/katex.min.css';
import katex from 'katex';
import { RadicalIcon } from 'lucide-react';
import { BaseEquationPlugin, BaseInlineEquationPlugin } from 'platejs/math';
import { type EditorElementProps, EditorElement } from 'platejs/static';
import * as React from 'react';
 
export function EquationElementStatic(
  props: EditorElementProps<typeof BaseEquationPlugin>
) {
  const { element } = props;
























































































math-static imports the KaTeX stylesheet, so it runs only where a bundler loads CSS imports. Plain Node throws on that import. A Node process that converts equations without rendering them uses BaseEquationPlugin and BaseInlineEquationPlugin from platejs/math.

Insert equations

Use each plugin's scoped update surface.

import {
  BaseEquationPlugin,
  BaseInlineEquationPlugin,
} from 'platejs/math';
 
editor.plugin(BaseEquationPlugin).update.insert({}, { select: true });
editor
  .plugin(BaseInlineEquationPlugin)
  .update.insert({ latex: 'E = mc^2' }, { select: true });
import {
  BaseEquationPlugin,
  BaseInlineEquationPlugin,
} from 'platejs/math'




Value shape

Both equation nodes store source in latex. The child text is only the Plate-required child for a void element.

const value = [
  {
    children: [
      { text: 'Mass-energy equivalence: ' },
      {
        children: [{ text: '' }],
        latex: 'E = mc^2',
        type: 'inlineEquation',
      },
      { text: '.' },
    ],
    type: 'paragraph',
  },
  {
    children: [{ text: '' }],
    latex: '\\int_{a}^{b} f(x) \\, dx = F(b) - F(a)',
    type: 'equation',
  },
];
const value = [
  {
    children: [
      { text: 'Mass-energy equivalence: ' },
      {
        children: [{ text: '' }],
        latex: 'E = mc^2',
        type: 'inlineEquation',
      },
      { text: '.' },
    ],
    type: 'paragraph',
  },
  {
    children: [{ text: '' }],
    latex: '\\int_{a}^{b} f(x) \\, dx = F(b) - F(a)',
    type: 'equation',
  },
];
NodeTypeBehavior
BaseEquationPluginequationBlock void equation.
BaseInlineEquationPlugininlineEquationInline void equation.
EquationElement.latexstringLaTeX source rendered by KaTeX.

Input rules

MathRules.markdown creates editor input rules. It is separate from Markdown serialization.

RuleTriggerBehavior
MathRules.markdown({ variant: '$' })$...$Deletes the delimited text and inserts an inline equation with the matched expression.
MathRules.markdown({ on: 'break', variant: '$$' })$$ then line breakReplaces the paragraph fence with a block equation.
MathRules.markdown({ on: 'match', variant: '$$' })$$...$$ matchCreates a block equation on match.

Math input rules are disabled inside code blocks, block equations, and inline equations.

Rendering

The registry components render KaTeX and keep source editing in a popover.

SurfaceBehavior
Editable block equationmath calls katex.render with display-mode options.
Editable inline equationmath calls katex.render in inline mode, so the equation draws at the size of the surrounding text. Opens a popover when the inline void node is selected and the selection is collapsed.
Popover inputKeeps a local draft. External equation changes replace that draft.
Enter or DoneCommits the draft in one undo batch and closes the input. Composition Enter does not submit.
Escape or outside dismissalDiscards the draft without writing to the document.
Inline left/right edge arrowsCommit the draft and move selection out of the inline equation.
Static renderingmath-static calls katex.renderToString with the same modes as math.

KaTeX is configured with throwOnError: false, strict: 'warn', and trust: false in the registry UI.

Markdown

The equation plugins own the Markdown mapping. BaseEquationPlugin maps equation to the math node and BaseInlineEquationPlugin maps inlineEquation to inlineMath. MarkdownPlugin from platejs/markdown runs those mappings once remark-math is in its remark plugins, as the registry MarkdownKit configures it.

Inline $x+1$ math
Inline $x+1$ math
$$
x+1
$$
$$
x+1
$$

Inline math parses to inlineEquation. Block math parses to equation. Serialization writes the same Markdown math shapes from latex.

HTML

The equation plugins own the HTML mapping. editor.api.html.serialize and copy write each equation as an element that keeps its TeX in data-editor-equation-latex. Its text is the TeX between dollar signs, so an app that reads only the text still gets the source.

<p>Area <span data-editor-equation data-editor-equation-latex="x^2">$x^2$</span> units</p>
<div data-editor-equation="block" data-editor-equation-latex="E=mc^2">$$E=mc^2$$</div>
<p>Area <span data-editor-equation data-editor-equation-latex="x^2">$x^2$</span> units</p>
<div data-editor-equation="block" data-editor-equation-latex="E=mc^2">$$E=mc^2$$</div>

Paste and editor.api.html.parse take the TeX from the first source that holds it.

Pasted HTMLPlate readsResult
Plate's equation elementdata-editor-equation-latexThe same equation. data-editor-equation="block" gives equation, otherwise inlineEquation.
KaTeX's default output with its TeX annotation, such as a copy from a page that loads KaTeX's copy-tex extensionThe application/x-tex annotation inside its MathMLAn equation with that TeX, without KaTeX's drawn glyphs.
Wikipedia mathThe TeX in each math element's data-mw attributeAn equation with that TeX.
Other MathML with an application/x-tex annotationThe annotationAn equation with that TeX.
MathML without TeX, such as a Chrome copy of KaTeX output from a page without copy-tex, which leaves out the hidden annotationTeX that Plate rebuilds from the MathMLAn equation with that TeX, without KaTeX's drawn glyphs. When the MathML has no TeX form, Plate drops it with a diagnostic and KaTeX's drawn glyphs stay as text. The parse warns when the rebuild loses presentation that TeX cannot hold, such as a color, a size, spacing or a bracket's stretch. It also warns when the rebuild picks one of two commands that write the same MathML but draw differently, such as \mathcal and \mathscr. Each formula gets one warning that names each loss and pick.
MathML beside a hidden drawing that writes its letters as text, such as MathJax 2's CHTML outputNothingThe drawn letters, as text. Plate drops the MathML with a diagnostic, so editor.api.html.parse fails under the default lossPolicy: 'reject'.
MathML with no TeX form, such as mlongdiv or merrorNothingDropped, with an HTML diagnostic that names the element. Under the default lossPolicy: 'reject', editor.api.html.parse fails.
KaTeX output drawn without MathML (output: 'html')NothingKaTeX's drawn text.

Math with display="block" becomes equation and splits its paragraph. Inside a list item or a heading it becomes inlineEquation, so the list keeps its items and numbers and the heading stays one heading. Display math after a list item's first paragraph lands one level under the item, like other blocks there, when IndentPlugin targets equations. Math inside a code block becomes the text it draws, without its TeX. The parse reports that loss, so editor.api.html.parse fails under the default lossPolicy: 'reject', and a rebuild that lost presentation also reports its warning. Math with no TeX form is cut from the code with its diagnostic. Plate removes the link around an equation and warns, because a link holds only text. The link's other text stays where it was, without the link.

An editor reads math markup only when it has an equation plugin. Inside a math element, MathML elements pass the same safety checks as HTML elements and lose every URL attribute, and Plate removes any HTML or SVG. An editor without the equation plugins drops pasted math.

With only BaseInlineEquationPlugin, all pasted math becomes inlineEquation. With only BaseEquationPlugin, display math becomes equation. Plate drops inline math, and display math in a list item or heading, with a diagnostic. A dropped KaTeX formula leaves its drawn glyphs as text.

Plate Plus

  • Mark text as equation from the toolbar
  • Insert equation from slash command
  • Beautifully crafted UI
Get the code

API Reference

APIPackageUse
BaseEquationPluginplatejs/mathHeadless block equation plugin.
BaseInlineEquationPluginplatejs/mathHeadless inline equation plugin.
EquationPluginplatejs/math/reactReact block equation plugin.
InlineEquationPluginplatejs/math/reactReact inline equation plugin.
editor.plugin(BaseEquationPlugin).update.insert(props?, options?)platejs/mathInserts a block equation.
editor.plugin(BaseInlineEquationPlugin).update.insert(input?, options?)platejs/mathInserts an inline equation. latex defaults to the selected string.
MathRules.markdown(options)platejs/mathCreates inline or block math input rules.
EquationElement / InlineEquationElementmath registry UIRender KaTeX and own the editable popover interaction.
EquationElementplatejs/mathUnion of the block and inline equation element shapes.
;
import * as React from 'react';
import TextareaAutosize, {
type TextareaAutosizeProps,
} from 'react-textarea-autosize';
import { Button } from '@/components/ui/button';
import {
FloatingPopover,
FloatingPopoverContent,
FloatingPopoverTrigger,
} from '@/components/editor/floating-popover';
import { inlineSuggestionVariants } from '@/lib/inline-suggestion';
function useEquation({
element,
katexRef,
options,
}: {
element: { latex: string };
katexRef: React.RefObject<HTMLDivElement | null>;
options?: KatexOptions;
}) {
React.useEffect(() => {
if (!katexRef.current) return;
katex.render(element.latex, katexRef.current, {
...options,
throwOnError: false,
});
}, [element.latex, katexRef, options]);
}
// Undo and redo restore a selection the user did not move into an equation, so
// it must not open the equation's input and take focus from the editor.
function useSelectedByUser() {
const editor = useEditor();
return (selected: boolean) =>
selected && !editor.read.lastCommit()?.tags.includes('historic');
}
export function EquationElement(
props: EditorElementProps<typeof EquationPlugin> & {
lineBreakBadge?: React.ReactNode;
}
) {
const selected = useElementSelected({ mode: 'text' });
const selectedByUser = useSelectedByUser();
const [open, setOpen] = React.useState(() => selectedByUser(selected));
const katexRef = React.useRef<HTMLDivElement | null>(null);
const { lineBreakBadge } = props;
useEquation({
element: props.element,
katexRef,
options: {
displayMode: true,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
},
});
return (
<EditorElement className="my-1" {...props}>
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverTrigger>
<button
aria-label={
props.element.latex.length > 0 ? 'Edit equation' : 'Add equation'
}
className={cn(
'group flex w-full cursor-pointer select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
props.element.latex.length === 0
? 'bg-muted p-3 pe-9'
: 'px-2 py-1'
)}
data-selected={selected}
contentEditable={false}
type="button"
>
{props.element.latex.length > 0 ? (
<span ref={katexRef} dir="ltr" />
) : (
<span className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
<RadicalIcon className="size-6 text-muted-foreground/80" />
<span>Add a Tex equation</span>
</span>
)}
{lineBreakBadge}
</button>
</FloatingPopoverTrigger>
<EquationPopoverContent
open={open}
placeholder={
'f(x) = \\begin{cases}\n x^2, &\\quad x > 0 \\\\\n 0, &\\quad x = 0 \\\\\n -x^2, &\\quad x < 0\n\\end{cases}'
}
isInline={false}
setOpen={setOpen}
/>
</FloatingPopover>
{props.children}
</EditorElement>
);
}
export function InlineEquationElement(
props: EditorElementProps<typeof InlineEquationPlugin>
) {
const { element } = props;
const katexRef = React.useRef<HTMLDivElement | null>(null);
const selected = useElementSelected({ mode: 'text' });
const collapsedSelected = useElementSelected({ mode: 'collapsed' });
const selectedByUser = useSelectedByUser();
const [popoverState, setPopoverState] = React.useState(() => ({
open: selectedByUser(collapsedSelected),
selected,
}));
const openAtPointerDownRef = React.useRef(false);
const open =
popoverState.selected === selected
? popoverState.open
: selected && (popoverState.open || selectedByUser(collapsedSelected));
if (popoverState.selected !== selected) {
setPopoverState({ open, selected });
}
const setOpen = React.useCallback(
(nextOpen: boolean) => {
setPopoverState({ open: nextOpen, selected });
},
[selected]
);
useEquation({
element,
katexRef,
options: {
displayMode: false,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
},
});
return (
<EditorElement
{...props}
className="mx-1 inline-block rounded-sm select-none"
>
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverTrigger>
<button
aria-label={
element.latex.length > 0 ? 'Edit equation' : 'Add equation'
}
className={cn(
'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
'h-6',
inlineSuggestionVariants({ on: 'parent' }),
((element.latex.length > 0 && open) || selected) &&
'after:bg-editor-primary/15',
element.latex.length === 0 &&
'text-muted-foreground after:bg-muted-foreground/10'
)}
contentEditable={false}
onClick={(event) => {
if (event.detail === 0 || openAtPointerDownRef.current) return;
event.preventDefault();
setOpen(true);
}}
onPointerDown={() => {
openAtPointerDownRef.current = open;
}}
type="button"
>
<span
ref={katexRef}
className={cn(
element.latex.length === 0 && 'hidden',
'font-mono leading-none'
)}
dir="ltr"
/>
{element.latex.length === 0 && (
<span>
<RadicalIcon className="me-1 inline-block h-[19px] w-4 py-[1.5px] align-text-bottom" />
New equation
</span>
)}
</button>
</FloatingPopoverTrigger>
<EquationPopoverContent
className="my-auto"
open={open}
placeholder="E = mc^2"
setOpen={setOpen}
isInline
/>
</FloatingPopover>
{props.children}
</EditorElement>
);
}
function EquationPopoverContent({
className,
isInline,
open,
setOpen,
...props
}: {
isInline: boolean;
open: boolean;
setOpen: (open: boolean) => void;
} & TextareaAutosizeProps) {
const editor = useEditor();
const readOnly = useEditorReadOnly();
const element = useElement(isInline ? InlineEquationPlugin : EquationPlugin);
const key = editor.key(element);
const ref = React.useRef<HTMLTextAreaElement>(null);
const [draft, setDraft] = React.useState({
open,
source: element.latex,
value: element.latex,
});
const changedSource = draft.source !== element.latex || draft.open !== open;
const value = changedSource ? element.latex : draft.value;
if (changedSource) {
setDraft({ open, source: element.latex, value: element.latex });
}
React.useEffect(() => {
if (!open) return undefined;
const timeout = globalThis.setTimeout(() => {
ref.current?.focus();
ref.current?.select();
}, 0);
return () => globalThis.clearTimeout(timeout);
}, [open]);
if (readOnly) return null;
const close = (commit: boolean, direction: 'after' | 'before' = 'after') => {
const current = editor.read.nodes.get(key);
setOpen(false);
// Move the selection before saving: undoing the save restores the
// selection from before it, and a caret inside an inline equation would
// reopen its input.
if (isInline) {
const point = editor.read.points[direction](element);
if (point) editor.update.selection.set(point);
} else if (current) {
editor.update.selection.setNodes([current[1]]);
}
if (
commit &&
current &&
NodeApi.isElement(current[0]) &&
current[0].type === element.type &&
current[0].latex === element.latex &&
value !== element.latex &&
!editor.read.view.isReadOnly() &&
!editor.read.nodes.elementReadOnly({ at: key })
) {
const plugin = isInline ? InlineEquationPlugin : EquationPlugin;
editor
.plugin(plugin)
.update({ history: 'new-batch' })
.set({ latex: value }, { at: current[1] });
}
editor.api.dom.focus();
};
return (
<FloatingPopoverContent
className="flex gap-2"
onFinalFocus={(event) => {
if (isInline) event.preventDefault();
}}
onEscapeKeyDown={(event) => event.preventDefault()}
contentEditable={false}
>
<TextareaAutosize
ref={ref}
className={cn('max-h-[50vh] grow resize-none p-2 text-sm', className)}
dir="ltr"
value={value}
onChange={(event) =>
setDraft({
open,
source: element.latex,
value: event.currentTarget.value,
})
}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing) return;
if (isHotkey('enter')(event)) {
event.preventDefault();
close(true);
} else if (isHotkey('escape')(event)) {
event.preventDefault();
close(false);
} else if (isInline) {
const { selectionEnd, selectionStart } = event.currentTarget;
const atLeftEdge =
selectionStart === 0 &&
selectionEnd === 0 &&
isHotkey('ArrowLeft')(event);
const atRightEdge =
selectionStart === value.length &&
selectionEnd === value.length &&
isHotkey('ArrowRight')(event);
if (atLeftEdge || atRightEdge) {
event.preventDefault();
const node = editor.api.dom.resolveDOMNode(element);
const rtl = !!node && getComputedStyle(node).direction === 'rtl';
close(true, atLeftEdge === rtl ? 'after' : 'before');
}
}
}}
autoFocus
{...props}
/>
<Button variant="secondary" className="px-3" onClick={() => close(true)}>
Done{' '}
<CornerDownLeftIcon className="size-3.5 [&:dir(rtl)]:-scale-x-100" />
</Button>
</FloatingPopoverContent>
);
}
export const MathKit = [
InlineEquationPlugin.configure({
component: InlineEquationElement,
inputRules: [MathRules.markdown({ variant: '$' })],
}),
EquationPlugin.configure({
component: EquationElement,
inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
}),
];
});
'platejs/react'
;
import * as React from 'react';
import TextareaAutosize, {
type TextareaAutosizeProps,
} from 'react-textarea-autosize';
import { Button } from '@/components/ui/button';
import {
FloatingPopover,
FloatingPopoverContent,
FloatingPopoverTrigger,
} from '@/components/editor/floating-popover';
import { inlineSuggestionVariants } from '@/lib/inline-suggestion';
function useEquation({
element,
katexRef,
options,
}: {
element: { latex: string };
katexRef: React.RefObject<HTMLDivElement | null>;
options?: KatexOptions;
}) {
React.useEffect(() => {
if (!katexRef.current) return;
katex.render(element.latex, katexRef.current, {
...options,
throwOnError: false,
});
}, [element.latex, katexRef, options]);
}
// Undo and redo restore a selection the user did not move into an equation, so
// it must not open the equation's input and take focus from the editor.
function useSelectedByUser() {
const editor = useEditor();
return (selected: boolean) =>
selected && !editor.read.lastCommit()?.tags.includes('historic');
}
export function EquationElement(
props: EditorElementProps<typeof EquationPlugin> & {
lineBreakBadge?: React.ReactNode;
}
) {
const selected = useElementSelected({ mode: 'text' });
const selectedByUser = useSelectedByUser();
const [open, setOpen] = React.useState(() => selectedByUser(selected));
const katexRef = React.useRef<HTMLDivElement | null>(null);
const { lineBreakBadge } = props;
useEquation({
element: props.element,
katexRef,
options: {
displayMode: true,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
},
});
return (
<EditorElement className="my-1" {...props}>
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverTrigger>
<button
aria-label={
props.element.latex.length > 0 ? 'Edit equation' : 'Add equation'
}
className={cn(
'group flex w-full cursor-pointer select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
props.element.latex.length === 0
? 'bg-muted p-3 pe-9'
: 'px-2 py-1'
)}
data-selected={selected}
contentEditable={false}
type="button"
>
{props.element.latex.length > 0 ? (
<span ref={katexRef} dir="ltr" />
) : (
<span className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
<RadicalIcon className="size-6 text-muted-foreground/80" />
<span>Add a Tex equation</span>
</span>
)}
{lineBreakBadge}
</button>
</FloatingPopoverTrigger>
<EquationPopoverContent
open={open}
placeholder={
'f(x) = \\begin{cases}\n x^2, &\\quad x > 0 \\\\\n 0, &\\quad x = 0 \\\\\n -x^2, &\\quad x < 0\n\\end{cases}'
}
isInline={false}
setOpen={setOpen}
/>
</FloatingPopover>
{props.children}
</EditorElement>
);
}
export function InlineEquationElement(
props: EditorElementProps<typeof InlineEquationPlugin>
) {
const { element } = props;
const katexRef = React.useRef<HTMLDivElement | null>(null);
const selected = useElementSelected({ mode: 'text' });
const collapsedSelected = useElementSelected({ mode: 'collapsed' });
const selectedByUser = useSelectedByUser();
const [popoverState, setPopoverState] = React.useState(() => ({
open: selectedByUser(collapsedSelected),
selected,
}));
const openAtPointerDownRef = React.useRef(false);
const open =
popoverState.selected === selected
? popoverState.open
: selected && (popoverState.open || selectedByUser(collapsedSelected));
if (popoverState.selected !== selected) {
setPopoverState({ open, selected });
}
const setOpen = React.useCallback(
(nextOpen: boolean) => {
setPopoverState({ open: nextOpen, selected });
},
[selected]
);
useEquation({
element,
katexRef,
options: {
displayMode: false,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
},
});
return (
<EditorElement
{...props}
className="mx-1 inline-block rounded-sm select-none"
>
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverTrigger>
<button
aria-label={
element.latex.length > 0 ? 'Edit equation' : 'Add equation'
}
className={cn(
'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
'h-6',
inlineSuggestionVariants({ on: 'parent' }),
((element.latex.length > 0 && open) || selected) &&
'after:bg-editor-primary/15',
element.latex.length === 0 &&
'text-muted-foreground after:bg-muted-foreground/10'
)}
contentEditable={false}
onClick={(event) => {
if (event.detail === 0 || openAtPointerDownRef.current) return;
event.preventDefault();
setOpen(true);
}}
onPointerDown={() => {
openAtPointerDownRef.current = open;
}}
type="button"
>
<span
ref={katexRef}
className={cn(
element.latex.length === 0 && 'hidden',
'font-mono leading-none'
)}
dir="ltr"
/>
{element.latex.length === 0 && (
<span>
<RadicalIcon className="me-1 inline-block h-[19px] w-4 py-[1.5px] align-text-bottom" />
New equation
</span>
)}
</button>
</FloatingPopoverTrigger>
<EquationPopoverContent
className="my-auto"
open={open}
placeholder="E = mc^2"
setOpen={setOpen}
isInline
/>
</FloatingPopover>
{props.children}
</EditorElement>
);
}
function EquationPopoverContent({
className,
isInline,
open,
setOpen,
...props
}: {
isInline: boolean;
open: boolean;
setOpen: (open: boolean) => void;
} & TextareaAutosizeProps) {
const editor = useEditor();
const readOnly = useEditorReadOnly();
const element = useElement(isInline ? InlineEquationPlugin : EquationPlugin);
const key = editor.key(element);
const ref = React.useRef<HTMLTextAreaElement>(null);
const [draft, setDraft] = React.useState({
open,
source: element.latex,
value: element.latex,
});
const changedSource = draft.source !== element.latex || draft.open !== open;
const value = changedSource ? element.latex : draft.value;
if (changedSource) {
setDraft({ open, source: element.latex, value: element.latex });
}
React.useEffect(() => {
if (!open) return undefined;
const timeout = globalThis.setTimeout(() => {
ref.current?.focus();
ref.current?.select();
}, 0);
return () => globalThis.clearTimeout(timeout);
}, [open]);
if (readOnly) return null;
const close = (commit: boolean, direction: 'after' | 'before' = 'after') => {
const current = editor.read.nodes.get(key);
setOpen(false);
// Move the selection before saving: undoing the save restores the
// selection from before it, and a caret inside an inline equation would
// reopen its input.
if (isInline) {
const point = editor.read.points[direction](element);
if (point) editor.update.selection.set(point);
} else if (current) {
editor.update.selection.setNodes([current[1]]);
}
if (
commit &&
current &&
NodeApi.isElement(current[0]) &&
current[0].type === element.type &&
current[0].latex === element.latex &&
value !== element.latex &&
!editor.read.view.isReadOnly() &&
!editor.read.nodes.elementReadOnly({ at: key })
) {
const plugin = isInline ? InlineEquationPlugin : EquationPlugin;
editor
.plugin(plugin)
.update({ history: 'new-batch' })
.set({ latex: value }, { at: current[1] });
}
editor.api.dom.focus();
};
return (
<FloatingPopoverContent
className="flex gap-2"
onFinalFocus={(event) => {
if (isInline) event.preventDefault();
}}
onEscapeKeyDown={(event) => event.preventDefault()}
contentEditable={false}
>
<TextareaAutosize
ref={ref}
className={cn('max-h-[50vh] grow resize-none p-2 text-sm', className)}
dir="ltr"
value={value}
onChange={(event) =>
setDraft({
open,
source: element.latex,
value: event.currentTarget.value,
})
}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing) return;
if (isHotkey('enter')(event)) {
event.preventDefault();
close(true);
} else if (isHotkey('escape')(event)) {
event.preventDefault();
close(false);
} else if (isInline) {
const { selectionEnd, selectionStart } = event.currentTarget;
const atLeftEdge =
selectionStart === 0 &&
selectionEnd === 0 &&
isHotkey('ArrowLeft')(event);
const atRightEdge =
selectionStart === value.length &&
selectionEnd === value.length &&
isHotkey('ArrowRight')(event);
if (atLeftEdge || atRightEdge) {
event.preventDefault();
const node = editor.api.dom.resolveDOMNode(element);
const rtl = !!node && getComputedStyle(node).direction === 'rtl';
close(true, atLeftEdge === rtl ? 'after' : 'before');
}
}
}}
autoFocus
{...props}
/>
<Button variant="secondary" className="px-3" onClick={() => close(true)}>
Done{' '}
<CornerDownLeftIcon className="size-3.5 [&:dir(rtl)]:-scale-x-100" />
</Button>
</FloatingPopoverContent>
);
}
export const MathKit = [
InlineEquationPlugin.configure({
component: InlineEquationElement,
inputRules: [MathRules.markdown({ variant: '$' })],
}),
EquationPlugin.configure({
component: EquationElement,
inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
}),
];
'use client';
 
import 'katex/dist/katex.min.css';
import { cn } from 'cn';
import katex, { type KatexOptions } from 'katex';
import { CornerDownLeftIcon, RadicalIcon } from 'lucide-react';
import { isHotkey, NodeApi } from 'platejs';
import { MathRules } from 'platejs/math';
import { EquationPlugin, InlineEquationPlugin } from 'platejs/math/react';
import {
  type EditorElementProps,
  EditorElement,
  useEditor,
  useEditorReadOnly,
  useElement,
  useElementSelected,
} from 'platejs/react';
import * as React from 'react';
import TextareaAutosize, {
  type TextareaAutosizeProps,
} from 'react-textarea-autosize';
 
import { Button } from '@/components/ui/button';
import {
  FloatingPopover,
  FloatingPopoverContent,
  FloatingPopoverTrigger,
} from '@/components/editor/floating-popover';
import { inlineSuggestionVariants } from '@/lib/inline-suggestion';
 
function useEquation({
  element,
  katexRef,
  options,
}: {
  element: { latex: string };
  katexRef: React.RefObject<HTMLDivElement | null>;
  options?: KatexOptions;
}) {
  React.useEffect(() => {
    if (!katexRef.current) return;
 
    katex.render(element.latex, katexRef.current, {
      ...options,
      throwOnError: false,
    });
  }, [element.latex, katexRef, options]);
}
 
// Undo and redo restore a selection the user did not move into an equation, so
// it must not open the equation's input and take focus from the editor.
function useSelectedByUser() {
  const editor = useEditor();
 
  return (selected: boolean) =>
    selected && !editor.read.lastCommit()?.tags.includes('historic');
}
 
export function EquationElement(
  props: EditorElementProps<typeof EquationPlugin> & {
    lineBreakBadge?: React.ReactNode;
  }
) {
  const selected = useElementSelected({ mode: 'text' });
  const selectedByUser = useSelectedByUser();
  const [open, setOpen] = React.useState(() => selectedByUser(selected));
  const katexRef = React.useRef<HTMLDivElement | null>(null);
  const { lineBreakBadge } = props;
 
  useEquation({
    element: props.element,
    katexRef,
    options: {
      displayMode: true,
      errorColor: '#cc0000',
      fleqn: false,
      leqno: false,
      macros: { '\\f': '#1f(#2)' },
      output: 'htmlAndMathml',
      strict: 'warn',
      throwOnError: false,
      trust: false,
    },
  });
 
  return (
    <EditorElement className="my-1" {...props}>
      <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
        <FloatingPopoverTrigger>
          <button
            aria-label={
              props.element.latex.length > 0 ? 'Edit equation' : 'Add equation'
            }
            className={cn(
              'group flex w-full cursor-pointer select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
              props.element.latex.length === 0
                ? 'bg-muted p-3 pe-9'
                : 'px-2 py-1'
            )}
            data-selected={selected}
            contentEditable={false}
            type="button"
          >
            {props.element.latex.length > 0 ? (
              <span ref={katexRef} dir="ltr" />
            ) : (
              <span className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
                <RadicalIcon className="size-6 text-muted-foreground/80" />
                <span>Add a Tex equation</span>
              </span>
            )}
            {lineBreakBadge}
          </button>
        </FloatingPopoverTrigger>
 
        <EquationPopoverContent
          open={open}
          placeholder={
            'f(x) = \\begin{cases}\n  x^2, &\\quad x > 0 \\\\\n  0, &\\quad x = 0 \\\\\n  -x^2, &\\quad x < 0\n\\end{cases}'
          }
          isInline={false}
          setOpen={setOpen}
        />
      </FloatingPopover>
 
      {props.children}
    </EditorElement>
  );
}
 
export function InlineEquationElement(
  props: EditorElementProps<typeof InlineEquationPlugin>
) {
  const { element } = props;
  const katexRef = React.useRef<HTMLDivElement | null>(null);
  const selected = useElementSelected({ mode: 'text' });
  const collapsedSelected = useElementSelected({ mode: 'collapsed' });
  const selectedByUser = useSelectedByUser();
  const [popoverState, setPopoverState] = React.useState(() => ({
    open: selectedByUser(collapsedSelected),
    selected,
  }));
  const openAtPointerDownRef = React.useRef(false);
  const open =
    popoverState.selected === selected
      ? popoverState.open
      : selected && (popoverState.open || selectedByUser(collapsedSelected));
 
  if (popoverState.selected !== selected) {
    setPopoverState({ open, selected });
  }
 
  const setOpen = React.useCallback(
    (nextOpen: boolean) => {
      setPopoverState({ open: nextOpen, selected });
    },
    [selected]
  );
 
  useEquation({
    element,
    katexRef,
    options: {
      displayMode: false,
      errorColor: '#cc0000',
      fleqn: false,
      leqno: false,
      macros: { '\\f': '#1f(#2)' },
      output: 'htmlAndMathml',
      strict: 'warn',
      throwOnError: false,
      trust: false,
    },
  });
 
  return (
    <EditorElement
      {...props}
      className="mx-1 inline-block rounded-sm select-none"
    >
      <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
        <FloatingPopoverTrigger>
          <button
            aria-label={
              element.latex.length > 0 ? 'Edit equation' : 'Add equation'
            }
            className={cn(
              'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
              'h-6',
              inlineSuggestionVariants({ on: 'parent' }),
              ((element.latex.length > 0 && open) || selected) &&
                'after:bg-editor-primary/15',
              element.latex.length === 0 &&
                'text-muted-foreground after:bg-muted-foreground/10'
            )}
            contentEditable={false}
            onClick={(event) => {
              if (event.detail === 0 || openAtPointerDownRef.current) return;
 
              event.preventDefault();
              setOpen(true);
            }}
            onPointerDown={() => {
              openAtPointerDownRef.current = open;
            }}
            type="button"
          >
            <span
              ref={katexRef}
              className={cn(
                element.latex.length === 0 && 'hidden',
                'font-mono leading-none'
              )}
              dir="ltr"
            />
            {element.latex.length === 0 && (
              <span>
                <RadicalIcon className="me-1 inline-block h-[19px] w-4 py-[1.5px] align-text-bottom" />
                New equation
              </span>
            )}
          </button>
        </FloatingPopoverTrigger>
 
        <EquationPopoverContent
          className="my-auto"
          open={open}
          placeholder="E = mc^2"
          setOpen={setOpen}
          isInline
        />
      </FloatingPopover>
 
      {props.children}
    </EditorElement>
  );
}
 
function EquationPopoverContent({
  className,
  isInline,
  open,
  setOpen,
  ...props
}: {
  isInline: boolean;
  open: boolean;
  setOpen: (open: boolean) => void;
} & TextareaAutosizeProps) {
  const editor = useEditor();
  const readOnly = useEditorReadOnly();
  const element = useElement(isInline ? InlineEquationPlugin : EquationPlugin);
  const key = editor.key(element);
  const ref = React.useRef<HTMLTextAreaElement>(null);
  const [draft, setDraft] = React.useState({
    open,
    source: element.latex,
    value: element.latex,
  });
  const changedSource = draft.source !== element.latex || draft.open !== open;
  const value = changedSource ? element.latex : draft.value;
 
  if (changedSource) {
    setDraft({ open, source: element.latex, value: element.latex });
  }
 
  React.useEffect(() => {
    if (!open) return undefined;
    const timeout = globalThis.setTimeout(() => {
      ref.current?.focus();
      ref.current?.select();
    }, 0);
    return () => globalThis.clearTimeout(timeout);
  }, [open]);
 
  if (readOnly) return null;
 
  const close = (commit: boolean, direction: 'after' | 'before' = 'after') => {
    const current = editor.read.nodes.get(key);
    setOpen(false);
    // Move the selection before saving: undoing the save restores the
    // selection from before it, and a caret inside an inline equation would
    // reopen its input.
    if (isInline) {
      const point = editor.read.points[direction](element);
      if (point) editor.update.selection.set(point);
    } else if (current) {
      editor.update.selection.setNodes([current[1]]);
    }
    if (
      commit &&
      current &&
      NodeApi.isElement(current[0]) &&
      current[0].type === element.type &&
      current[0].latex === element.latex &&
      value !== element.latex &&
      !editor.read.view.isReadOnly() &&
      !editor.read.nodes.elementReadOnly({ at: key })
    ) {
      const plugin = isInline ? InlineEquationPlugin : EquationPlugin;
      editor
        .plugin(plugin)
        .update({ history: 'new-batch' })
        .set({ latex: value }, { at: current[1] });
    }
    editor.api.dom.focus();
  };
 
  return (
    <FloatingPopoverContent
      className="flex gap-2"
      onFinalFocus={(event) => {
        if (isInline) event.preventDefault();
      }}
      onEscapeKeyDown={(event) => event.preventDefault()}
      contentEditable={false}
    >
      <TextareaAutosize
        ref={ref}
        className={cn('max-h-[50vh] grow resize-none p-2 text-sm', className)}
        dir="ltr"
        value={value}
        onChange={(event) =>
          setDraft({
            open,
            source: element.latex,
            value: event.currentTarget.value,
          })
        }
        onKeyDown={(event) => {
          if (event.nativeEvent.isComposing) return;
          if (isHotkey('enter')(event)) {
            event.preventDefault();
            close(true);
          } else if (isHotkey('escape')(event)) {
            event.preventDefault();
            close(false);
          } else if (isInline) {
            const { selectionEnd, selectionStart } = event.currentTarget;
            const atLeftEdge =
              selectionStart === 0 &&
              selectionEnd === 0 &&
              isHotkey('ArrowLeft')(event);
            const atRightEdge =
              selectionStart === value.length &&
              selectionEnd === value.length &&
              isHotkey('ArrowRight')(event);
 
            if (atLeftEdge || atRightEdge) {
              event.preventDefault();
              const node = editor.api.dom.resolveDOMNode(element);
              const rtl = !!node && getComputedStyle(node).direction === 'rtl';
 
              close(true, atLeftEdge === rtl ? 'after' : 'before');
            }
          }
        }}
        autoFocus
        {...props}
      />
      <Button variant="secondary" className="px-3" onClick={() => close(true)}>
        Done{' '}
        <CornerDownLeftIcon className="size-3.5 [&:dir(rtl)]:-scale-x-100" />
      </Button>
    </FloatingPopoverContent>
  );
}
 
export const MathKit = [
  InlineEquationPlugin.configure({
    component: InlineEquationElement,
    inputRules: [MathRules.markdown({ variant: '$' })],
  }),
  EquationPlugin.configure({
    component: EquationElement,
    inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
  }),
];
ToolbarButton
{...props}
onClick={() => {
editor.plugin(BaseInlineEquationPlugin).update.insert();
}}
tooltip="Mark as equation"
>
<RadicalIcon />
</ToolbarButton>
);
}
'use client';
 
import { RadicalIcon } from 'lucide-react';
import { BaseInlineEquationPlugin } from 'platejs/math';
import { useEditor } from 'platejs/react';
import * as React from 'react';
 
import { ToolbarButton } from '@/components/editor/toolbar';
 
export function InlineEquationToolbarButton(
  props: React.ComponentProps<typeof ToolbarButton>
) {
  const editor = useEditor();
 
  return (
    <ToolbarButton
      {...props}
      onClick={() => {
        editor.plugin(BaseInlineEquationPlugin).update.insert();
      }}
      tooltip="Mark as equation"
    >
      <RadicalIcon />
    </ToolbarButton>
  );
}
component: EquationElement,
inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
}),
],
});
import { MathRules } from 'platejs/math';
import {
  EquationPlugin,
  InlineEquationPlugin,
} from 'platejs/math/react';
import { createEditor } from 'platejs/react';
 
import {
  EquationElement,
  InlineEquationElement,
} from '@/components/editor/math';
 
export const editor = createEditor({
  plugins: [
    InlineEquationPlugin.configure({
      component: InlineEquationElement,
      inputRules: [MathRules.markdown({ variant: '$' })],
    }),
    EquationPlugin.configure({
      component: EquationElement,
      inputRules: [MathRules.markdown({ on: 'break', variant: '$$' })],
    }),
  ],
});
const html = katex.renderToString(element.latex, {
displayMode: true,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
});
return (
<EditorElement className="my-1" {...props}>
<div
className={cn(
'group flex select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
element.latex.length === 0 ? 'bg-muted p-3 pe-9' : 'px-2 py-1'
)}
>
{element.latex.length > 0 ? (
<span
dir="ltr"
// oxlint-disable-next-line react/no-danger -- [P0 behavior-boundary] KaTeX generates this HTML with trust disabled from the adjacent equation source.
dangerouslySetInnerHTML={{
__html: html,
}}
/>
) : (
<div className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
<RadicalIcon className="size-6 text-muted-foreground/80" />
<div>Add a Tex equation</div>
</div>
)}
</div>
{props.children}
</EditorElement>
);
}
export function InlineEquationElementStatic(
props: EditorElementProps<typeof BaseInlineEquationPlugin>
) {
const html = katex.renderToString(props.element.latex, {
displayMode: false,
errorColor: '#cc0000',
fleqn: false,
leqno: false,
macros: { '\\f': '#1f(#2)' },
output: 'htmlAndMathml',
strict: 'warn',
throwOnError: false,
trust: false,
});
return (
<EditorElement {...props} className="inline-block rounded-sm select-none">
<div
className={cn(
'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
'h-6',
props.element.latex.length === 0 &&
'text-muted-foreground after:bg-muted-foreground/10'
)}
>
<span
className={cn(
props.element.latex.length === 0 && 'hidden',
'font-mono leading-none'
)}
dir="ltr"
// oxlint-disable-next-line react/no-danger -- [P0 behavior-boundary] KaTeX generates this HTML with trust disabled from the adjacent equation source.
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
{props.children}
</EditorElement>
);
}
export const BaseMathKit = [
BaseInlineEquationPlugin.configure({
component: InlineEquationElementStatic,
}),
BaseEquationPlugin.configure({
component: EquationElementStatic,
}),
] as const;
import { cn } from 'cn';
 
import 'katex/dist/katex.min.css';
import katex from 'katex';
import { RadicalIcon } from 'lucide-react';
import { BaseEquationPlugin, BaseInlineEquationPlugin } from 'platejs/math';
import { type EditorElementProps, EditorElement } from 'platejs/static';
import * as React from 'react';
 
export function EquationElementStatic(
  props: EditorElementProps<typeof BaseEquationPlugin>
) {
  const { element } = props;
 
  const html = katex.renderToString(element.latex, {
    displayMode: true,
    errorColor: '#cc0000',
    fleqn: false,
    leqno: false,
    macros: { '\\f': '#1f(#2)' },
    output: 'htmlAndMathml',
    strict: 'warn',
    throwOnError: false,
    trust: false,
  });
 
  return (
    <EditorElement className="my-1" {...props}>
      <div
        className={cn(
          'group flex select-none items-center justify-center rounded-sm hover:bg-editor-primary/10 data-[selected=true]:bg-editor-primary/10',
          element.latex.length === 0 ? 'bg-muted p-3 pe-9' : 'px-2 py-1'
        )}
      >
        {element.latex.length > 0 ? (
          <span
            dir="ltr"
            // oxlint-disable-next-line react/no-danger -- [P0 behavior-boundary] KaTeX generates this HTML with trust disabled from the adjacent equation source.
            dangerouslySetInnerHTML={{
              __html: html,
            }}
          />
        ) : (
          <div className="flex h-7 w-full items-center gap-2 text-sm whitespace-nowrap text-muted-foreground">
            <RadicalIcon className="size-6 text-muted-foreground/80" />
            <div>Add a Tex equation</div>
          </div>
        )}
      </div>
      {props.children}
    </EditorElement>
  );
}
 
export function InlineEquationElementStatic(
  props: EditorElementProps<typeof BaseInlineEquationPlugin>
) {
  const html = katex.renderToString(props.element.latex, {
    displayMode: false,
    errorColor: '#cc0000',
    fleqn: false,
    leqno: false,
    macros: { '\\f': '#1f(#2)' },
    output: 'htmlAndMathml',
    strict: 'warn',
    throwOnError: false,
    trust: false,
  });
 
  return (
    <EditorElement {...props} className="inline-block rounded-sm select-none">
      <div
        className={cn(
          'after:-top-0.5 after:-start-1 after:absolute after:inset-0 after:z-1 after:h-[calc(100%)+4px] after:w-[calc(100%+8px)] after:rounded-sm after:content-[""]',
          'h-6',
          props.element.latex.length === 0 &&
            'text-muted-foreground after:bg-muted-foreground/10'
        )}
      >
        <span
          className={cn(
            props.element.latex.length === 0 && 'hidden',
            'font-mono leading-none'
          )}
          dir="ltr"
          // oxlint-disable-next-line react/no-danger -- [P0 behavior-boundary] KaTeX generates this HTML with trust disabled from the adjacent equation source.
          dangerouslySetInnerHTML={{ __html: html }}
        />
      </div>
      {props.children}
    </EditorElement>
  );
}
 
export const BaseMathKit = [
  BaseInlineEquationPlugin.configure({
    component: InlineEquationElementStatic,
  }),
  BaseEquationPlugin.configure({
    component: EquationElementStatic,
  }),
] as const;
;
editor.plugin(BaseEquationPlugin).update.insert({}, { select: true });
editor
.plugin(BaseInlineEquationPlugin)
.update.insert({ latex: 'E = mc^2' }, { select: true });