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

Board

PreviousNext

A whiteboard block whose notes, shapes, pictures, arrows, frames and pen lines are blocks of the document.

Board Element
Loading…
Horizontal RuleCallout

On This Page

FeaturesKit usageInstallationAdd kitExamplesBoard pageStyle panelPasted textImagesPicture filesExportManual usageInstallationAdd pluginsKeyboard and pointerScreen readersInsert shapes from codeAdd your own shapeValue shapeCollaborationAdd the board to an app with Yjs roomsBump the schema versionMigrate the old room's documentSeed a new roomLimitsPluginsBoardPluginBoardNotePlugin, BoardGeoPlugin, BoardArrowPlugin, BoardFramePlugin, BoardStrokePluginBoardImagePluginAPI Reference
Build your editor
Production-ready AI template and reusable components.
Get all-access

Features

  • A void board block that owns its own list of shapes. Each shape is a top-level block of that list, so sync, suggestions, undo and copy and paste work per shape.
  • Six shape types: sticky notes and geo shapes that hold rich text, image shapes that hold a picture, arrows whose ends bind to shapes, frames that hold shapes, and pen lines.
  • Styles stored on each shape: fill, outline color, line style, outline width, opacity and text size, each with a default for its shape type. One pick restyles the selected shapes as one undo step, or the next shape while a drawing tool is picked.
  • Commands to insert, move, resize, restack and remove shapes. Undo never splits a call, and in Suggesting mode each call is one suggestion.
  • Copy, paste and duplicate with fresh shape ids. A copied arrow binds the copied shapes. The copies land on top, with frames still behind the other shapes. They land at the pointer when it is over the board, and step 24px down and right off any shape already at their place.
  • Paste text or a link, and it lands as a selected note at the pointer.
  • Paste an image link or a picture copied from a web page, and it lands as an image shape at the pointer, at the picture's proportions. With UploadPlugin installed, picture files that you paste, drop or pick from the toolbar land as image shapes too, and each uploads in its own shape.
  • Export or copy the board, or its selected shapes, as a PNG or an SVG that holds the shapes off screen too.
  • A camera, a tool, a tool lock and a next style for each mounted view, which the document never stores.
  • Tab and Mod with an arrow move between shapes, Shift+Enter reaches the toolbar, and keys zoom, pan and fit. Enter places a note, shape or frame, and connects two shapes with an arrow. A screen reader hears the selected shape, the picked tool, the zoom, each removal and each step of a connect, in words your app passes.
  • Only the shapes near the camera mount, so the work each keystroke does stays the same as the board grows.
Report an issue

Kit usage

Installation

BoardKit installs BoardPlugin and the five shape plugins with the copied board UI: the board surface with its toolbar and a renderer for each of those five shape types.

'use client';
 
import { cn } from 'cn';
import {
  ArrowDownToLineIcon,
  BanIcon,
  CircleIcon,
  DiamondIcon,
  EraserIcon,
  FrameIcon,
  HandIcon,
  ImageIcon,
  LockIcon,
  LockOpenIcon,
  MousePointer2Icon,
  MoveUpRightIcon,
  PaletteIcon,
  PencilIcon,
  ScanIcon,
  SquareIcon,
  StickyNoteIcon,
  TriangleIcon,
  UngroupIcon,
  ZoomInIcon,
  ZoomOutIcon,
} from 'lucide-react';
import { ElementApi } from 'platejs';
import {
  BoardArrowhead,
  BoardArrowLabel,
  BoardArrowPath,
  BoardArrowPlugin,
  type BoardCorner,
  BoardFramePlugin,
  BoardGeoPlugin,
  BoardImagePlugin,
  type BoardMessages,
  BoardNotePlugin,
  type BoardPickState,
  type BoardPicture,
  type BoardPictureWarning,
  BoardPlugin,
  BoardShape,
  type BoardShapeDescription,
  BoardStrokePlugin,
  type BoardStyle,
  BoardSurface,
  type BoardTool,
  useBoardActions,
  useBoardView,
  useStrokePath,
} from 'platejs/board/react';
import type { ImageElement } from 'platejs/media';
import { ImagePlugin } from 'platejs/media/react';
import {
  type EditorElementProps,
  useEditor,
  useEditorSelector,
  usePath,
} from 'platejs/react';
import * as React from 'react';
import { flushSync } from 'react-dom';
import { toast } from 'sonner';
import { useFilePicker } from 'use-file-picker';
 
import {
  ARROW_HEAD,
  BOARD_COLORS,
  COLORS,
  dashArray,
  geoOutline,
  paint,
  SHAPE_HEADINGS,
  STROKE_WIDTHS,
  TEXT_SIZES,
  tint,
} from '@/components/editor/board-styles';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import {
  Toolbar,
  ToolbarButton,
  ToolbarGroup,
} from '@/components/editor/toolbar';
 
const TOOLS: ReadonlyArray<
  Readonly<{
    icon: React.ReactNode;
    key: string;
    label: string;
    tool: BoardTool;
  }>
> = [
  { icon: <MousePointer2Icon />, key: 'V', label: 'Select', tool: 'select' },
  { icon: <HandIcon />, key: 'H', label: 'Hand', tool: 'hand' },
  { icon: <StickyNoteIcon />, key: 'N', label: 'Note', tool: 'note' },
  { icon: <SquareIcon />, key: 'R', label: 'Shape', tool: 'geo' },
  { icon: <MoveUpRightIcon />, key: 'A', label: 'Arrow', tool: 'arrow' },
  { icon: <FrameIcon />, key: 'F', label: 'Frame', tool: 'frame' },
  { icon: <PencilIcon />, key: 'P', label: 'Pen', tool: 'pen' },
  { icon: <EraserIcon />, key: 'E', label: 'Eraser', tool: 'eraser' },
];
 
const GEOS: ReadonlyArray<
  Readonly<{
    geo: NonNullable<BoardStyle['geo']>;
    icon: React.ReactNode;
    label: string;
  }>
> = [
  { geo: 'rectangle', icon: <SquareIcon />, label: 'Rectangle' },
  { geo: 'ellipse', icon: <CircleIcon />, label: 'Ellipse' },
  { geo: 'diamond', icon: <DiamondIcon />, label: 'Diamond' },
  { geo: 'triangle', icon: <TriangleIcon />, label: 'Triangle' },
];
 
type BoardStyleOption<TValue> = Readonly<{
  icon: React.ReactNode;
  label: string;
  value: TValue;
}>;
 
const FILL_OPTIONS: ReadonlyArray<BoardStyleOption<string>> = [
  { icon: <BanIcon />, label: 'None', value: 'none' },
  ...COLORS.map(({ color, label }) => ({
    icon: (
      <span
        className="size-4 rounded-full border border-foreground/20"
        style={{ backgroundColor: paint(color) }}
      />
    ),
    label,
    value: color,
  })),
];
 
const OUTLINE_OPTIONS: ReadonlyArray<BoardStyleOption<string>> = [
  {
    icon: <span className="size-4 rounded-full border-[3px] border-current" />,
    label: 'Default',
    value: 'currentColor',
  },
  ...COLORS.map(({ color, label }) => ({
    icon: (
      <span
        className="size-4 rounded-full border-[3px]"
        style={{ borderColor: paint(color) }}
      />
    ),
    label,
    value: color,
  })),
];
 
const line = (props: React.SVGProps<SVGLineElement>) => (
  <svg aria-hidden viewBox="0 0 16 16">
    <line
      stroke="currentColor"
      strokeLinecap="round"
      x1={2}
      x2={14}
      y1={8}
      y2={8}
      {...props}
    />
  </svg>
);
 
const DASH_OPTIONS: ReadonlyArray<
  BoardStyleOption<NonNullable<BoardStyle['dash']>>
> = [
  { icon: line({ strokeWidth: 2 }), label: 'Solid', value: 'solid' },
  {
    icon: line({
      strokeDasharray: '4 3',
      strokeLinecap: 'butt',
      strokeWidth: 2,
    }),
    label: 'Dashed',
    value: 'dashed',
  },
  {
    icon: line({ strokeDasharray: '0 4', strokeWidth: 2 }),
    label: 'Dotted',
    value: 'dotted',
  },
];
 
const SIZE_LABELS = [
  ['s', 'Small', 'S'],
  ['m', 'Medium', 'M'],
  ['l', 'Large', 'L'],
  ['xl', 'Extra large', 'XL'],
] as const;
 
const WIDTH_OPTIONS: ReadonlyArray<
  BoardStyleOption<NonNullable<BoardStyle['strokeWidth']>>
> = SIZE_LABELS.map(([value, label]) => ({
  icon: line({ strokeWidth: STROKE_WIDTHS[value] }),
  label,
  value,
}));
 
const TEXT_OPTIONS: ReadonlyArray<
  BoardStyleOption<NonNullable<BoardStyle['textSize']>>
> = SIZE_LABELS.map(([value, label, short]) => ({
  icon: <span className="text-xs font-medium">{short}</span>,
  label,
  value,
}));
 
const GEO_OPTIONS: ReadonlyArray<
  BoardStyleOption<NonNullable<BoardStyle['geo']>>
> = GEOS.map(({ geo, icon, label }) => ({
  icon,
  label,
  value: geo,
}));
 
const KINDS: Readonly<Record<BoardShapeDescription['kind'], string>> = {
  arrow: 'Arrow',
  frame: 'Frame',
  geo: 'Shape',
  note: 'Note',
  shape: 'Shape',
  stroke: 'Line',
};
 
const TOOL_NAMES: Readonly<Record<BoardTool, string>> = {
  arrow: 'Arrow tool',
  eraser: 'Eraser tool',
  frame: 'Frame tool',
  geo: 'Shape tool',
  hand: 'Hand tool',
  note: 'Note tool',
  pen: 'Pen tool',
  select: 'Select tool',
};
 
const CORNERS: Readonly<Record<BoardCorner, string>> = {
  bottomLeft: 'bottom left',
  bottomRight: 'bottom right',
  topLeft: 'top left',
  topRight: 'top right',
};
 
const nameOf = (shape: BoardShapeDescription): string => {
  if (shape.kind === 'arrow') {
    const end = (side: BoardShapeDescription | null) =>
      side ? nameOf(side) : 'nothing';
 
    const ends = `Arrow from ${end(shape.ends.start)} to ${end(shape.ends.end)}`;
 
    return shape.text ? `${shape.text}, ${ends}` : ends;
  }
 
  return shape.text ? `${shape.text}, ${KINDS[shape.kind]}` : KINDS[shape.kind];
};
 
const pickOf = (
  shape: BoardShapeDescription,
  { count, position, selected, total }: BoardPickState
) =>
  `${nameOf(shape)}, ${selected ? 'selected' : 'not selected'}. ${position} of ${total}. ${count} selected`;
 
const boardMessages: BoardMessages = {
  label: 'Board',
  instructions:
    'Enter selects the first shape. Tab moves between shapes and leaves them after the last. Command with an arrow on a Mac, or Control with an arrow elsewhere, picks the nearest shape. With the note, shape or frame tool, Enter places one, and with the arrow tool and one shape selected that is not an arrow, Enter connects it to another, whose end the arrow keys then move. With the arrow tool and nothing selected, Enter starts an arrow whose start the arrow keys move until a second Enter keeps it. With one shape selected that is not an arrow, S resizes it: Tab picks a corner, the arrow keys move it and Enter keeps the new size. Space starts picking shapes: Tab moves, Space adds or removes the shape and Enter keeps the selection. Q keeps the drawing tool picked after each shape until a second Q, and Command+D on a Mac, or Control+D elsewhere, copies the selected shapes. Shift+Enter reaches the toolbar.',
  aim: (shape, { anchor, position, side, total }) =>
    `${side === 'start' ? 'From' : 'To'} ${nameOf(shape)}${anchor.across === 50 && anchor.down === 50 ? '' : `, ${anchor.across}% across, ${anchor.down}% down`}. ${position} of ${total}`,
  connecting: (from) =>
    `Connecting ${from ? nameOf(from) : 'a free point'}. Tab picks a shape, arrow keys move the end, Enter draws the arrow and Escape stops.`,
  free: ({ x, y }, { side }) =>
    `${side === 'start' ? 'Start' : 'End'} free at ${x}, ${y}`,
  starting: ({ x, y }, { from }) =>
    `Drawing an arrow from ${from ? nameOf(from) : `${x}, ${y}`}. Arrow keys move its start, Tab picks a shape, Enter keeps the start and Escape stops.`,
  resizing: (shape, { corner, height, width }) =>
    `Resizing ${nameOf(shape)} from its ${CORNERS[corner]} corner, ${width} by ${height}. Tab picks a corner, arrow keys resize, Enter keeps it and Escape stops.`,
  resize: ({ corner, height, width }) =>
    `${CORNERS[corner]}, ${width} by ${height}`,
  picking: (shape, state) =>
    `Picking shapes. ${pickOf(shape, state)}. Tab moves, Space adds or removes, Enter finishes.`,
  pick: (shape, state) => pickOf(shape, state),
  shape: (shape, { position, total }) =>
    `${nameOf(shape)}. ${position} of ${total}`,
  shapes: (count) =>
    count === 0 ? 'No shapes selected' : `${count} shapes selected`,
  tool: (tool) => TOOL_NAMES[tool],
  toolLock: (locked) => (locked ? 'Tool lock on' : 'Tool lock off'),
  zoom: (percent) => `Zoom ${percent}%`,
  removed: (count) =>
    count === 1 ? 'Shape deleted' : `${count} shapes deleted`,
};
 
function BoardShapeMenu({ pressed }: { pressed: boolean }) {
  const geo = useBoardView((view) => view.nextStyle.geo ?? 'rectangle');
  const { setStyle, setTool } = useBoardActions();
  const icon = GEOS.find((item) => item.geo === geo)?.icon ?? GEOS[0].icon;
 
  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger>
        <ToolbarButton isDropdown pressed={pressed} tooltip="Shape (R)">
          {icon}
        </ToolbarButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent side="top">
        <DropdownMenuRadioGroup
          value={geo}
          onValueChange={(value) => {
            const picked = GEOS.find((item) => item.geo === value);
 
            if (!picked) return;
            setTool('geo');
            setStyle({ geo: picked.geo });
          }}
        >
          {GEOS.map(({ geo: itemGeo, icon: itemIcon, label }) => (
            <DropdownMenuRadioItem key={itemGeo} value={itemGeo}>
              {itemIcon}
              {label}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
 
function BoardPictureButton() {
  const takesPictureFiles = useBoardView((view) => view.takesPictureFiles);
  const { upload } = useBoardActions();
  const { openFilePicker } = useFilePicker({
    accept: ['image/*'],
    multiple: true,
    readFilesContent: false,
    onFilesSelected: ({ plainFiles }) => upload(plainFiles),
  });
 
  return (
    <ToolbarButton
      className="px-1.5"
      disabled={!takesPictureFiles}
      tooltip="Image"
      onClick={() => openFilePicker()}
    >
      <ImageIcon />
    </ToolbarButton>
  );
}
 
const PICTURE_WARNINGS: Readonly<Record<BoardPictureWarning['code'], string>> =
  {
    'content-undrawn': 'Some content could not be drawn.',
    downscaled: 'The PNG was made smaller to fit the size limit.',
    'font-missing': 'A font could not be read, so its text uses another font.',
    'image-unreadable':
      'Some images could not be read, so they show as gray boxes or links.',
    'shape-undrawn': 'Some shapes could not be drawn and show as gray boxes.',
  };
 
const downloadBlob = (blob: Blob, filename: string) => {
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
 
  link.href = url;
  link.download = filename;
  document.body.append(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
};
 
const loadPictureKit = () =>
  import('@/components/editor/board-static').then(
    ({ BoardPictureKit }) => BoardPictureKit
  );
 
const warnAbout = ({ warnings }: BoardPicture) => {
  if (warnings.length === 0) return;
 
  toast.warning(
    [...new Set(warnings.map(({ code }) => PICTURE_WARNINGS[code]))].join(' ')
  );
};
 
function BoardExportMenu() {
  const { exportPicture } = useBoardActions();
  const mounted = React.useRef(false);
 
  React.useEffect(() => {
    mounted.current = true;
 
    return () => {
      mounted.current = false;
    };
  }, []);
 
  const save = async (format: 'png' | 'svg') => {
    try {
      const picture = await exportPicture({ format, kit: loadPictureKit() });
 
      if (!picture) {
        toast('There is nothing to export.');
        return;
      }
 
      downloadBlob(picture.blob, `board.${format}`);
      warnAbout(picture);
    } catch (error) {
      if (!mounted.current) return;
      console.error('Could not export the board.', error);
      toast.error('The board could not be exported.');
    }
  };
 
  const copy = async (format: 'png' | 'svg') => {
    // Firefox and Safari cannot copy image/svg+xml, so the SVG goes as text.
    const type = format === 'png' ? 'image/png' : 'text/plain';
    const empty = new Error('There is nothing to copy.');
    const drawing = exportPicture({ format, kit: loadPictureKit() }).then(
      (picture) => picture ?? Promise.reject(empty)
    );
 
    try {
      // Safari and Firefox take a clipboard write only within the click's user
      // activation, so the write starts now with the picture still drawing.
      const [picture] = await Promise.all([
        drawing,
        navigator.clipboard.write([
          new ClipboardItem({
            [type]: drawing.then(({ blob }) => new Blob([blob], { type })),
          }),
        ]),
      ]);
 
      toast.success(
        `Copied the board as ${format === 'png' ? 'a PNG' : 'an SVG'}.`
      );
      warnAbout(picture);
    } catch (error) {
      if (error === empty) {
        toast(empty.message);
        return;
      }
      if (!mounted.current) return;
      console.error('Could not copy the board.', error);
      toast.error('The board could not be copied.');
    }
  };
 
  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger>
        <ToolbarButton isDropdown tooltip="Export">
          <ArrowDownToLineIcon />
        </ToolbarButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent side="top">
        <DropdownMenuItem onSelect={() => save('png')}>
          Export as PNG
        </DropdownMenuItem>
        <DropdownMenuItem onSelect={() => save('svg')}>
          Export as SVG
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onSelect={() => copy('png')}>
          Copy as PNG
        </DropdownMenuItem>
        <DropdownMenuItem onSelect={() => copy('svg')}>
          Copy as SVG
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
 
function BoardToolLock() {
  const locked = useBoardView((view) => view.toolLocked);
  const { setToolLocked } = useBoardActions();
 
  return (
    <ToolbarButton
      className="px-1.5"
      pressed={locked}
      tooltip="Keep the tool after drawing (Q)"
      onClick={() => setToolLocked(!locked)}
    >
      {locked ? <LockIcon /> : <LockOpenIcon />}
    </ToolbarButton>
  );
}
 
function BoardZoomLevel() {
  const percent = useBoardView((view) => Math.round(view.camera.zoom * 100));
  const { resetZoom } = useBoardActions();
 
  return (
    <ToolbarButton
      className="w-10 px-0"
      aria-label={`Zoom ${percent}%, reset to 100%`}
      tooltip="Reset to 100% (Shift+0)"
      onClick={resetZoom}
    >
      <span className="text-xs tabular-nums">{percent}%</span>
    </ToolbarButton>
  );
}
 
function BoardToolbarGroup({ children }: { children: React.ReactNode }) {
  return (
    <ToolbarGroup>
      <div className="flex flex-wrap items-center justify-center gap-y-0.5">
        {children}
      </div>
    </ToolbarGroup>
  );
}
 
export function BoardToolbar() {
  const tool = useBoardView((view) => view.tool);
  const frame = useBoardView((view) => {
    const [only, ...rest] = view.selectedShapes;
 
    return view.writable && only?.kind === 'frame' && rest.length === 0
      ? only.id
      : null;
  });
  const { fit, removeFrame, setTool, zoomIn, zoomOut } = useBoardActions();
 
  return (
    <Toolbar className="absolute inset-x-0 bottom-2 z-10 mx-auto w-max max-w-[calc(100%-1rem)] flex-wrap justify-center gap-y-0.5 rounded-lg border bg-background p-1 shadow-sm">
      <BoardToolbarGroup>
        {TOOLS.map(({ icon, key, label, tool: itemTool }) =>
          itemTool === 'geo' ? (
            <BoardShapeMenu key={itemTool} pressed={tool === 'geo'} />
          ) : (
            <ToolbarButton
              key={itemTool}
              className="px-1.5"
              pressed={tool === itemTool}
              tooltip={`${label} (${key})`}
              onClick={() => setTool(itemTool)}
            >
              {icon}
            </ToolbarButton>
          )
        )}
        <BoardToolLock />
        <BoardPictureButton />
        <BoardExportMenu />
      </BoardToolbarGroup>
      <BoardToolbarGroup>
        <ToolbarButton
          className="px-1.5"
          tooltip="Zoom out (-)"
          onClick={zoomOut}
        >
          <ZoomOutIcon />
        </ToolbarButton>
        <BoardZoomLevel />
        <ToolbarButton
          className="px-1.5"
          tooltip="Zoom in (+)"
          onClick={zoomIn}
        >
          <ZoomInIcon />
        </ToolbarButton>
        <ToolbarButton
          className="px-1.5"
          tooltip="Fit every shape in view"
          onClick={fit}
        >
          <ScanIcon />
        </ToolbarButton>
        {frame && (
          <ToolbarButton
            className="px-1.5"
            tooltip="Remove the frame and keep its shapes"
            onClick={() => removeFrame(frame)}
          >
            <UngroupIcon />
          </ToolbarButton>
        )}
      </BoardToolbarGroup>
    </Toolbar>
  );
}
 
const ROW_KEYS: Readonly<Record<string, number>> = {
  ArrowDown: 1,
  ArrowLeft: -1,
  ArrowRight: 1,
  ArrowUp: -1,
};
 
function BoardStyleOptions<TValue extends string>({
  label,
  options,
  shown,
  onPick,
}: {
  label: string;
  options: ReadonlyArray<BoardStyleOption<TValue>>;
  shown: Readonly<{ mixed: false; value: TValue } | { mixed: true }>;
  onPick: (value: TValue) => void;
}) {
  const value = shown.mixed ? undefined : shown.value;
  const [focused, setFocused] = React.useState<number | null>(null);
  const stop =
    focused ??
    Math.max(
      0,
      options.findIndex((option) => option.value === value)
    );
 
  return (
    <div aria-label={label} className="grid grid-cols-4 gap-1" role="group">
      {options.map((option, index) => (
        <button
          key={option.value}
          className="flex size-7 items-center justify-center rounded-md outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-pressed:bg-accent [&_svg]:size-4"
          aria-label={option.label}
          aria-pressed={option.value === value}
          tabIndex={index === stop ? 0 : -1}
          title={option.label}
          type="button"
          onBlur={(event) => {
            if (
              !event.currentTarget.parentElement?.contains(event.relatedTarget)
            ) {
              setFocused(null);
            }
          }}
          onClick={() => onPick(option.value)}
          onFocus={() => setFocused(index)}
          onKeyDown={(event) => {
            const step = ROW_KEYS[event.key];
 
            if (!step) return;
            event.preventDefault();
            const row =
              event.currentTarget.parentElement?.querySelectorAll('button');
 
            row?.[(index + step + options.length) % options.length]?.focus();
          }}
        >
          {option.icon}
        </button>
      ))}
    </div>
  );
}
 
/**
 * Styles the selected shapes, or the next shape while a drawing tool is
 * active, with a row for each style they take other than opacity. On a board
 * narrower than 36rem it folds behind a Styles button.
 */
export function BoardStylePanel({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  const styles = useBoardView((view) => view.styles);
  const writable = useBoardView((view) => view.writable);
  const { setStyle } = useBoardActions();
  const [open, setOpen] = React.useState(false);
  const panel = React.useRef<HTMLDivElement>(null);
 
  if (!writable || Object.keys(styles).length === 0) return null;
 
  return (
    // oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- [P1 local-invariant] A press anywhere on the panel keeps focus where it is, so a shape being edited keeps its caret, and the narrow-board panel closes when focus leaves the button and the panel together.
    <div
      {...props}
      className={cn(
        'absolute top-2 end-2 z-10 flex max-h-[calc(100%-5.5rem)] flex-col items-end gap-1',
        className
      )}
      aria-label="Styles"
      data-board-dock="right"
      data-editor-root-chrome-ignore="true"
      role="group"
      onBlur={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
      }}
      onMouseDown={(event) => event.preventDefault()}
    >
      <button
        className="flex size-8 items-center justify-center rounded-lg border bg-background shadow-sm outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-expanded:bg-accent @min-[36rem]:hidden [&_svg]:size-4"
        aria-expanded={open}
        aria-label="Styles"
        title="Styles"
        type="button"
        onClick={(event) => {
          const button = event.currentTarget;
 
          flushSync(() => setOpen(!open));
          (open
            ? button
            : panel.current?.querySelector<HTMLElement>('[tabindex="0"]')
          )?.focus();
        }}
        onKeyDown={(event) => {
          if (event.key === 'Escape') setOpen(false);
        }}
      >
        <PaletteIcon />
      </button>
      <div
        className={cn(
          open ? 'flex' : 'hidden',
          'min-h-0 w-36 flex-col gap-2 overflow-y-auto overscroll-contain rounded-lg border bg-background p-2 shadow-sm @min-[36rem]:flex'
        )}
        ref={panel}
      >
        {styles.geo && (
          <BoardStyleOptions
            label="Shape"
            options={GEO_OPTIONS}
            shown={styles.geo}
            onPick={(geo) => setStyle({ geo })}
          />
        )}
        {styles.fill && (
          <BoardStyleOptions
            label="Fill"
            options={FILL_OPTIONS}
            shown={styles.fill}
            onPick={(fill) => setStyle({ fill })}
          />
        )}
        {styles.strokeColor && (
          <BoardStyleOptions
            label="Outline"
            options={OUTLINE_OPTIONS}
            shown={styles.strokeColor}
            onPick={(strokeColor) => setStyle({ strokeColor })}
          />
        )}
        {styles.dash && (
          <BoardStyleOptions
            label="Line"
            options={DASH_OPTIONS}
            shown={styles.dash}
            onPick={(dash) => setStyle({ dash })}
          />
        )}
        {styles.strokeWidth && (
          <BoardStyleOptions
            label="Width"
            options={WIDTH_OPTIONS}
            shown={styles.strokeWidth}
            onPick={(strokeWidth) => setStyle({ strokeWidth })}
          />
        )}
        {styles.textSize && (
          <BoardStyleOptions
            label="Text size"
            options={TEXT_OPTIONS}
            shown={styles.textSize}
            onPick={(textSize) => setStyle({ textSize })}
          />
        )}
      </div>
    </div>
  );
}
 
const BOARD_FOCUS_RING =
  'has-[[data-board-focus]:focus-visible]:not-has-[[data-board-shape][data-selected]]:ring-[3px] has-[[data-board-focus]:focus-visible]:not-has-[[data-board-shape][data-selected]]:ring-ring/50';
 
const BOARD_ERASING = '[&_[data-board-shape][data-erasing]]:opacity-30';
 
const CURSOR_RING =
  'data-board-cursor:after:pointer-events-none data-board-cursor:after:absolute data-board-cursor:after:-inset-1.5 data-board-cursor:after:rounded-md data-board-cursor:after:outline-2 data-board-cursor:after:outline-ring data-board-cursor:after:outline-dashed';
 
const BOARD_GRID =
  'bg-muted/40 bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-size-[16px_16px]';
 
const boardToolbar = (
  <>
    <BoardToolbar />
    <BoardStylePanel />
  </>
);
 
export function BoardElement(props: EditorElementProps<typeof BoardPlugin>) {
  return (
    <BoardSurface
      {...props}
      attributes={{
        ...props.attributes,
        className: cn(
          '@container my-4 rounded-lg border data-selected:ring-2 data-selected:ring-ring',
          BOARD_COLORS,
          BOARD_ERASING,
          BOARD_FOCUS_RING,
          BOARD_GRID
        ),
      }}
      messages={boardMessages}
      toolbar={boardToolbar}
    />
  );
}
 
export function BoardPageElement(
  props: EditorElementProps<typeof BoardPlugin>
) {
  return (
    <BoardSurface
      {...props}
      attributes={{
        ...props.attributes,
        className: cn(
          '@container ring-inset data-selected:ring-2 data-selected:ring-ring',
          BOARD_COLORS,
          BOARD_ERASING,
          BOARD_FOCUS_RING,
          BOARD_GRID
        ),
      }}
      height="100%"
      messages={boardMessages}
      toolbar={boardToolbar}
    />
  );
}
 
export function BoardNoteElement(
  props: EditorElementProps<typeof BoardNotePlugin>
) {
  const { element } = props;
 
  return (
    <BoardShape
      {...props}
      className={cn(
        CURSOR_RING,
        'rounded-sm p-3 leading-snug data-selected:outline-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
      )}
      style={{ fontSize: TEXT_SIZES[element.textSize] }}
    >
      <div
        className="absolute inset-0 rounded-sm shadow-md"
        contentEditable={false}
        data-board-note-paper=""
        style={{
          backgroundColor:
            element.fill === 'none' ? 'var(--background)' : tint(element.fill),
          opacity: element.opacity,
        }}
      />
      <div
        className={cn('relative', SHAPE_HEADINGS)}
        style={{ opacity: element.opacity }}
      >
        {props.children}
      </div>
    </BoardShape>
  );
}
 
export function BoardGeoElement(
  props: EditorElementProps<typeof BoardGeoPlugin>
) {
  const { element } = props;
  const width = STROKE_WIDTHS[element.strokeWidth];
 
  return (
    <BoardShape
      {...props}
      className={cn(
        CURSOR_RING,
        'flex flex-col justify-center p-3 text-center leading-snug data-selected:outline-2 data-selected:outline-offset-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-offset-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
      )}
      style={{ fontSize: TEXT_SIZES[element.textSize] }}
    >
      <div
        className="absolute inset-0"
        contentEditable={false}
        style={{ opacity: element.opacity }}
      >
        <svg
          aria-hidden
          className="pointer-events-none size-full overflow-visible"
          data-board-geo-outline={element.geo}
          preserveAspectRatio="none"
          strokeDasharray={dashArray(element.dash, width)}
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={width}
          style={{
            fill: element.fill === 'none' ? 'none' : tint(element.fill),
            stroke: paint(element.strokeColor),
          }}
          viewBox="0 0 100 100"
        >
          {geoOutline(element.geo, {
            height: 100,
            vectorEffect: 'non-scaling-stroke',
            width: 100,
          })}
        </svg>
      </div>
      <div
        className={cn('relative', SHAPE_HEADINGS)}
        style={{ opacity: element.opacity }}
      >
        {props.children}
      </div>
    </BoardShape>
  );
}
 
export function BoardFrameElement(
  props: EditorElementProps<typeof BoardFramePlugin>
) {
  return (
    <BoardShape
      {...props}
      className={cn(
        CURSOR_RING,
        'rounded-sm border-2 border-foreground/50 data-selected:border-ring data-[editor-authored-change]:border-dashed data-[editor-authored-change]:border-emerald-600'
      )}
    >
      <div
        className="absolute bottom-full [left:0] max-w-full cursor-default truncate pb-1 text-xs text-muted-foreground select-none"
        contentEditable={false}
        data-board-frame-name=""
      >
        {props.element.name || 'Frame'}
      </div>
      {props.children}
    </BoardShape>
  );
}
 
// A suggested arrow or pen line keeps the suggestion's color over its own.
const SUGGESTED_INK =
  'data-[editor-authored-change]:text-emerald-600 [&[data-editor-authored-change]_[data-board-ink]]:text-emerald-600!';
 
export function BoardArrowElement(
  props: EditorElementProps<typeof BoardArrowPlugin>
) {
  const { element } = props;
  const width = STROKE_WIDTHS[element.strokeWidth];
  const hitWidth = Math.max(14, width + 10);
 
  return (
    <BoardShape
      {...props}
      className={cn(
        'text-foreground [&[data-board-cursor]_[data-board-arrow-halo]]:inline [&[data-selected]_[data-board-arrow-halo]]:inline',
        SUGGESTED_INK
      )}
      style={{ fontSize: TEXT_SIZES[element.textSize] }}
    >
      <div className="absolute top-0 [left:0]" contentEditable={false}>
        <svg
          aria-hidden
          className="pointer-events-none overflow-visible"
          height={1}
          width={1}
        >
          <BoardArrowPath
            pointerEvents="stroke"
            stroke="transparent"
            strokeWidth={hitWidth}
          />
          <BoardArrowPath
            className="hidden stroke-ring/50"
            data-board-arrow-halo=""
            fill="none"
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={width + 8}
          />
          <g
            data-board-ink=""
            opacity={element.opacity}
            style={{ color: paint(element.strokeColor) }}
          >
            <BoardArrowPath
              data-board-arrow-path=""
              fill="none"
              stroke="currentColor"
              strokeDasharray={dashArray(element.dash, width)}
              strokeLinecap="round"
              strokeWidth={width}
            />
            <BoardArrowhead>
              <polygon fill="currentColor" points={ARROW_HEAD} />
            </BoardArrowhead>
          </g>
        </svg>
      </div>
      <BoardArrowLabel
        className="min-w-4 rounded-sm px-1 text-center leading-snug whitespace-nowrap has-[[data-editor-string]]:bg-background"
        style={{ opacity: element.opacity }}
      >
        {props.children}
      </BoardArrowLabel>
    </BoardShape>
  );
}
 
export function BoardStrokeElement(
  props: EditorElementProps<typeof BoardStrokePlugin>
) {
  const { element } = props;
  const drawn = useStrokePath(element);
 
  return (
    <BoardShape
      {...props}
      className={cn(
        CURSOR_RING,
        SUGGESTED_INK,
        'text-foreground data-selected:outline-1 data-selected:outline-ring data-selected:outline-dashed'
      )}
    >
      {drawn && (
        <div
          className="absolute inset-0"
          contentEditable={false}
          data-board-ink=""
          style={{
            color: paint(element.strokeColor),
            opacity: element.opacity,
          }}
        >
          <svg
            aria-hidden
            className="pointer-events-none size-full overflow-visible"
            preserveAspectRatio="none"
            viewBox={`0 0 ${drawn.width} ${drawn.height}`}
          >
            <path
              d={drawn.path}
              data-board-stroke-path=""
              fill="currentColor"
            />
          </svg>
        </div>
      )}
      {props.children}
    </BoardShape>
  );
}
 
export function BoardImageElement(
  props: EditorElementProps<typeof BoardImagePlugin>
) {
  const { element, slots } = props;
  const editor = useEditor();
  const path = usePath();
  const image = editor.plugin(ImagePlugin);
  const [stored] = element.children;
  const childKey = stored ? editor.key(stored) : undefined;
  const child = useEditorSelector(
    (current) => current.read.nodes.get([...path, 0])?.[0],
    {
      shouldUpdate: (change) =>
        !change ||
        (!!childKey &&
          change.changed.hasNodeKey(childKey, 'node', editor.read.view.root())),
    }
  );
  const picture =
    image.installed &&
    ElementApi.isElement(child) &&
    child.type === image.schema.type
      ? (child as ImageElement)
      : undefined;
 
  return (
    <BoardShape
      {...props}
      className={cn(
        CURSOR_RING,
        'data-selected:outline-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
      )}
    >
      {picture
        ? slots.contentBoundary({
            children: (
              // oxlint-disable-next-line nextjs/no-img-element -- [P1 local-invariant] The shape draws the document-owned runtime URL across its box, outside any Next loader.
              <img
                alt={picture.alt}
                className="absolute inset-0 size-full object-contain select-none"
                decoding="async"
                draggable={false}
                src={picture.url}
              />
            ),
            copyPolicy: 'model',
            mounted: false,
            reason: 'app-hidden',
            scope: { from: 0, type: 'children' },
            selectionPolicy: 'skip',
          })
        : props.children}
    </BoardShape>
  );
}
 
const BoardShapeKit = [
  BoardNotePlugin.configure({ component: BoardNoteElement }),
  BoardGeoPlugin.configure({ component: BoardGeoElement }),
  BoardArrowPlugin.configure({ component: BoardArrowElement }),
  BoardFramePlugin.configure({ component: BoardFrameElement }),
  BoardStrokePlugin.configure({ component: BoardStrokeElement }),
];
 
export const BoardKit = [
  BoardPlugin.configure({ component: BoardElement }),
  ...BoardShapeKit,
];
 
export const BoardPageKit = [
  BoardPlugin.configure({ component: BoardPageElement }),
  ...BoardShapeKit,
];
 
export const BoardImageKit = [
  BoardImagePlugin.configure({ component: BoardImageElement }),
];
'use client';
 
import { cn } from 'cn';
import {
  ArrowDownToLineIcon,
  BanIcon,
  CircleIcon,
  DiamondIcon,
  EraserIcon,
  FrameIcon,
  HandIcon,
  ImageIcon,
  LockIcon,
  LockOpenIcon,
  MousePointer2Icon,
  MoveUpRightIcon,
  PaletteIcon,
  PencilIcon,
  ScanIcon,
  SquareIcon,
  StickyNoteIcon,
  TriangleIcon,
  UngroupIcon,
  ZoomInIcon,
  ZoomOutIcon,
} from 'lucide-react';
import { ElementApi } from 'platejs';





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































  • BoardElement: renders the board surface and its toolbar.
  • BoardPageElement: renders a board that fills its container. BoardPageKit installs it in place of BoardElement.
  • BoardNoteElement, BoardGeoElement, BoardArrowElement, BoardFrameElement and BoardStrokeElement: render each shape type.
  • BoardImageElement: renders an image shape. BoardImageKit installs it apart from BoardKit, as Images shows.
  • BoardToolbar: picks the select, hand, note, shape, arrow, frame, pen or eraser tool, and its shape menu picks a rectangle, ellipse, diamond or triangle for the next shape. The lock button after them turns the tool lock on or off, as Q does, and shows pressed while the lock is on. The Image button after the lock opens a file picker and lands the picked pictures, as Picture files describes, and is disabled on a board that takes no picture files. The Export menu after the Image button saves or copies the board as a PNG or an SVG, as describes. Zoom out and zoom in move one zoom step, the zoom level between them shows the zoom as a percentage and goes back to 100% when clicked, and the fit button brings every shape into view. With a frame selected, an icon button removes the frame and keeps the frame's shapes.

Add kit

import { createEditor } from 'platejs/react';
 
import { BoardKit } from '@/components/editor/board';
 
const editor = createEditor({
  plugins: [
    // ...otherPlugins,
    ...BoardKit,
  ],
});
import { createEditor } from 'platejs/react';
 
import { BoardKit } from '@/components/editor/board';
 
const editor




Examples

Board page

In this example the board is the page's only block, like a whiteboard app. It fills its frame here and the whole window on its own page. A drag on empty board draws a selection box. Pan with the wheel, or drag with the hand, with Space held or with the middle button. Zoom with Mod and the wheel.

Loading…

BoardPageKit draws the board with BoardPageElement, which passes height="100%" to BoardSurface. That height replaces the board's stored height in this view and never changes the document, so the board takes the height of the editor around it. Give the editor a height, as the example does with <Editor className="h-full" variant="none" /> inside a container of set height. Leave out kits that wrap each block or add a paragraph after the last one, such as the drag handles and the trailing block of EditorKit. The example installs ImagePlugin and BoardImageKit, so a pasted image link or web picture lands on its board as Images describes. It installs no UploadPlugin, so its board takes no picture files and its Image button is disabled.

Style panel

Select shapes, or pick a drawing tool, and the panel at the board's top right shows a row for each style they take: Shape, which turns a geo shape into a rectangle, ellipse, diamond or triangle, then Fill, Outline, Line, Width and Text size. A pick writes every selected shape that takes the style, and the shape you are typing in, as one undo step that teammates in a shared room see. With a drawing tool picked, a pick styles only the next shape. The panel hides while no shape it targets takes a style, and in a read-only view. It has no opacity row, and a shape keeps the opacity it stores. On a board narrower than 36rem the panel folds behind a Styles button. A pick keeps the caret in the shape you are typing in, except in that folded panel, whose Styles button moves focus into the panel.

The copied board.tsx renders the panel in the surface's toolbar, next to BoardToolbar, and defines the class constants it uses, such as BOARD_COLORS:

const boardToolbar = (
  <>
    <BoardToolbar />
    <BoardStylePanel />
  </>
);
 
export function BoardElement(props: EditorElementProps<typeof BoardPlugin>) {
  return (
    <BoardSurface
      {...props}
      attributes={{
        ...props.attributes,
        className: cn(
          '@container my-4 rounded-lg border data-selected:ring-2 data-selected:ring-ring',
          BOARD_COLORS,
          BOARD_ERASING,
          BOARD_FOCUS_RING,
          BOARD_GRID
        ),
      }}
      messages={boardMessages}
      toolbar={boardToolbar}
    />
  );
}
const boardToolbar = (
  <>
    <BoardToolbar />
    <BoardStylePanel />
  </>
);
 
export function BoardElement(props: EditorElementProps<typeof BoardPlugin>) {
  return (
    <BoardSurface
      {...props}
      attributes={{
        ...props.attributes,
        className: cn(
          '@container my-4 rounded-lg border data-selected:ring-2 data-selected:ring-ring',
          BOARD_COLORS,
          BOARD_ERASING,
          BOARD_FOCUS_RING,
          BOARD_GRID






The panel needs two of those classes. Without @container it stays folded behind the Styles button at every width, and without BOARD_COLORS its named swatches show no color.

BoardStylePanel places itself at the board's top right and marks its root with data-board-dock="right". The mark tells fit and Shift+1 which side the panel covers, so they fit shapes into the room beside it. When that room cannot hold the shapes at 10 percent zoom, they use the board's whole width. The mark moves nothing, so place a panel of your own at a side and mark it with "left" or "right". Every other top-level element of toolbar counts as a row at the board's top or bottom.

To build your own row, render it inside toolbar, read its style from styles and write it with setStyle. A style that no target takes has no entry in styles, so the row hides. Prevent the default of a press on the row, so a shape being edited keeps its caret:

import { useBoardActions, useBoardView } from 'platejs/board/react';
 
const SIZES = ['s', 'm', 'l', 'xl'] as const;
 
function TextSizeRow() {
  const textSize = useBoardView((view) => view.styles.textSize);
  const { setStyle } = useBoardActions();
 
  if (!textSize) return null;
 
  return (
    <div aria-label="Text size" role="group">
      {SIZES.map((size) => (
        <button
          key={size}
          aria-pressed={!textSize.mixed && textSize.value === size}
          type="button"
          onClick={() => setStyle({ textSize: size })}
          onMouseDown={(event) => event.preventDefault()}
        >
          {size.toUpperCase()}
        </button>
      ))}
    </div>
  );
}
import { useBoardActions, useBoardView } from 'platejs/board/react';
 
const SIZES = ['s', 'm', 'l', 'xl'] as const;
 
function TextSizeRow() {
  const textSize = useBoardView((view) => view.styles.textSize);
  const { setStyle } = useBoardActions();
 
  if (!textSize) return null;
 
  return (
    <div aria-label="Text size" role="group">
      {












Pasted text

Paste text or a link while the board has focus, such as after a click on its empty space, and a new note holds it. With the caret in the page's text, the page takes the paste at the caret, even while the pointer is over the board.

  • The note lands centered on the pointer, or on the view's center when the pointer is off the board, at the note tool's 200 by 200 size and in the next style. It lands as one undo step, and the board selects it.
  • The note's text takes the paste as a paste into a note's text does, so the paste plugins your editor installs apply. With LinkPlugin, a pasted URL becomes a link.
  • With a shape selected, pasted text still lands as a new note, and the selected shape keeps its text.
  • Blank text, or a paste on a read-only board, lands nothing. An image link lands as an image shape, as Images says.
  • While a shape's text is being edited, a paste goes into that text.

Images

BoardImageKit adds the image shape, a box that holds one picture. Its one child is the document's own image element, so ImagePlugin keeps the picture's link, alt text, HTML and Markdown. Install the kit in an editor that installs ImagePlugin, such as one with the media kit. The demo at the top of this page gets it from EditorKit.

import { createEditor } from 'platejs/react';
 
import { BoardImageKit, BoardKit } from '@/components/editor/board';
import { MediaKit } from '@/components/editor/media';
 
const editor = createEditor({
  plugins: [
    // ...otherPlugins,
    ...MediaKit,
    ...BoardKit,
    ...BoardImageKit,
  ],
});
import { createEditor } from 'platejs/react';
 
import { BoardImageKit, BoardKit } from '@/components/editor/board';
import { MediaKit } from '@/components/editor/media';
 
const editor = createEditor({
  plugins: [
    // ...otherPlugins,
    ...MediaKit,
    ...BoardKit,
    ...BoardImageKit,
  ],
});

Paste an image link, or a picture copied from a web page, while the board has focus, such as after a click on its empty space. With the caret in the page's text, the page takes the paste at the caret, even while the pointer is over the board. A link counts as an image link when ImagePlugin would embed it, such as one whose path ends in .png or .jpg. Pasted HTML counts when every block in it that is not empty is a picture.

  • The pictures of one paste land as image shapes in a row 16px apart, centered on the pointer, or on the view's center when the pointer is off the board. They land as one undo step, and the board selects them.
  • Each shape keeps its picture's proportions, shrunk so its longest side is at most 480px and never enlarged. A picture that fails to load lands at 320 by 240.
  • The paste waits for each picture to load. Any of these drops a waiting paste: a key or a press on the board, another paste, focus leaving the board, an edit or selection change such as an undo, or the view turning read-only.
  • While a shape's text is being edited, a paste goes into that text, and no image shape appears.

Every resize of an image shape keeps its proportions, with or without Shift. A shrink stops when the short edge reaches 8px, and a shape whose short edge is already under 8px can only grow. An image shape has no text to edit, so Enter and a double-click keep it selected. It takes no style, so the style panel hides while the select tool is picked and only image shapes are selected. With a drawing tool picked, the panel targets the next shape that tool draws instead, as Style panel says. The copied BoardImageElement fits the picture to the shape's box and draws no caption.

To add a picture from code, pass the image element as the shape's one child. The shape is 320 by 240 unless width and height say otherwise.

import { BaseBoardImagePlugin } from 'platejs/board';
 
editor.update((tx) => {
  tx.plugin(BaseBoardImagePlugin).insert(
    {
      children: [
        {
          children: [{ text: '' }],
          type: 'image',
          url: 'https://example.com/plan.png',
        },
      ],
      height: 320,
      width: 480,
      x: 300,
      y: 40,
    },
    { board }
  );
});
import { BaseBoardImagePlugin } from 'platejs/board';
 
editor.update((tx) => {
  tx.plugin(BaseBoardImagePlugin).insert(
    {
      children: [
        {
          children: [{ text: '' }],
          type: 'image',
          url: 'https://example.com/plan.png',
        },
      ],
      height: 320,
      width: 480,
      x: 300,
      y: 40,
    },
    { board }
  );
});

Picture files

Install UploadPlugin beside ImagePlugin, and the board takes picture files. Each file lands in its own image shape, which holds an upload draft until the file finishes uploading and holds the picture after that. Upload Files sets up the plugin, its client and its rules. EditorKit holds both plugins, so the demo at the top of this page takes files. That demo keeps each upload in the browser tab.

import { createEditor } from 'platejs/react';
 
import { BoardImageKit, BoardKit } from '@/components/editor/board';
import { MediaKit } from '@/components/editor/media';
import { UploadKit } from '@/components/editor/upload';
 
const editor = createEditor({
  plugins: [
    // ...otherPlugins,
    ...MediaKit,
    ...UploadKit,
    ...BoardKit,
    ...BoardImageKit,
  ],
});
import { createEditor } from 'platejs/react';
 
import { BoardImageKit, BoardKit } from '@/components/editor/board';
import { MediaKit } from '@/components/editor/media';
import { UploadKit } from '@/components/editor/upload';
 
const editor = createEditor({
  plugins: [
    // ...otherPlugins,
    ...MediaKit,
    ...UploadKit,
    ...BoardKit,
    ...BoardImageKit,
  ],
});
GestureWhere the pictures land
Paste copied files while the board has focusCentered on the pointer, or on the view's center when the pointer is off the board.
Drop files on the boardCentered on the drop point.
Click the toolbar's Image button and pick filesCentered on the view.
  • The files of one paste, drop or pick land as image shapes in a row, in file order and 16px apart. They land as one undo step, and the board selects them.
  • The board measures each file before it lands, and sizes its shape as it sizes a pasted link's shape. A file that does not load as a picture lands at 320 by 240.
  • The landing waits for each file to load. It drops the files when another landing starts, when a key or pointer is pressed on the board, when another paste arrives, when focus leaves the board, when the document or the selection changes, or when the view stops being able to write.
  • While a file uploads, its shape draws your upload element. The copied UploadElement shows the picture with its progress and a Cancel button. After a failed upload it shows the file's name and "Upload failed. Try again.", and a click on it opens a file picker.
  • Cancel stops the upload and keeps the shape. The shape then shows the upload element's Add an image button. Its file picker takes one file, which uploads in the same shape. Delete removes the shape.
  • One undo removes the shapes of a paste, drop or pick and stops their uploads. An upload that finishes after the undo changes nothing. Redo brings back the pictures of uploads that had finished. For the other shapes it brings back empty drafts, which upload nothing until you pick a file.
  • A file that is not a picture, such as a PDF, lands no shape. UploadPlugin passes it to onError as unsupported-file-type, which the copied UploadKit shows as a toast. The pictures beside it still land.
  • UploadPlugin checks the pictures of one paste, drop or pick as one batch against its rules and maxFiles. A batch it refuses lands no shape, and onError gets the reason.
  • A picture copied from a web page can carry both its link and its file. The board lands the link, and uploads the file only when the link does not load.
  • While a shape's text is being edited, the board leaves pasted and dropped files to the page. A file pasted into a note's text lands no shape, and UploadPlugin reports that it does not fit there.

The board takes picture files only in a view that can write, in an editor that installs both UploadPlugin and ImagePlugin. On any other board, the Image button is disabled and a pasted or dropped file lands no shape. The copied button reads that check as takesPictureFiles from useBoardView, and lands its files with upload(files) from useBoardActions.

Export

The copied toolbar's Export menu saves the board as board.png or board.svg. Its Copy as PNG and Copy as SVG items put the same picture on the clipboard. The SVG goes on the clipboard as text, because Firefox and Safari cannot copy an SVG image.

  • The picture holds the selected shapes and every shape of a selected frame, or the whole board when nothing is selected. Shapes off screen are included.
  • It draws the board's background in the current light or dark theme, without the dot grid.
  • The file holds the fonts its text uses and the board's images, so it looks the same on another computer.
  • The PNG is twice the board's size. A board too large for the browser's canvas draws smaller, and the menu says so.
  • An image that cannot be read draws as a gray box in the PNG and stays a web link in the SVG. A shape type with no static component draws as a gray box. Note content whose plugin BoardPictureKit lacks shows as plain text, and a font that cannot be read leaves its text in another font. The menu shows a warning for each.
  • A note's text is HTML inside the SVG. Browsers draw it, but a design tool that opens the SVG shows the shapes without the note text.
  • On an empty board, the menu says there is nothing to export or copy.
  • When the browser refuses a copy, the menu says the board could not be copied. Export as PNG and Export as SVG still save it.

When you export, the menu loads BoardPictureKit from the copied board-static.tsx and passes it to exportPicture from useBoardActions. A control of your own inside the surface's toolbar can do the same:

const { exportPicture } = useBoardActions();
 
const picture = await exportPicture({
  format: 'svg',
  kit: import('@/components/editor/board-static').then(
    ({ BoardPictureKit }) => BoardPictureKit
  ),
});
const { exportPicture } = useBoardActions();
 
const picture = await exportPicture({
  format: 'svg',
  kit: import('@/components/editor/board-static').then(
    ({ BoardPictureKit }) => BoardPictureKit
  ),
});

picture is null when there is nothing to draw. Otherwise it holds the file's blob, its width and height in pixels, and its warnings.

To copy the picture, start the clipboard write before you await it. Safari and Firefox refuse a clipboard write that starts too long after the click, and drawing the picture can take longer:

const empty = new Error('There is nothing to copy.');
const picture = exportPicture({
  format: 'png',
  kit: import('@/components/editor/board-static').then(
    ({ BoardPictureKit }) => BoardPictureKit
  ),
}).then((drawn) => drawn ?? Promise.reject(empty));
 
await Promise.all([
  picture,
  navigator.clipboard.write([
    new ClipboardItem({ 'image/png': picture.then(({ blob }) => blob) }),
  ]),
]);
const empty = new Error('There is nothing to copy.');
const picture = exportPicture({
  format: 'png',
  kit: import('@/components/editor/board-static').then(
    ({ BoardPictureKit }) => BoardPictureKit
  ),
}).then((drawn) => drawn ?? Promise.reject(empty));
 
await Promise.all([
  picture,
  navigator.clipboard.write([
    new ClipboardItem({ 'image/png': picture.then(({ blob

On an empty board, the await rejects with empty and the clipboard keeps what it held. Any other rejection means the browser refused the copy or the picture could not be drawn.

Manual usage

Installation

pnpm add platejs
pnpm add platejs

Add plugins

Install the board and each shape type it holds. Configure each plugin with the component that draws it.

import {
  BoardArrowPlugin,
  BoardFramePlugin,
  BoardGeoPlugin,
  BoardNotePlugin,
  BoardPlugin,
  BoardStrokePlugin,
} from 'platejs/board/react';
import { createEditor } from 'platejs/react';
 
import {
  BoardArrowElement,
  BoardElement,
  BoardFrameElement,
  BoardGeoElement,
  BoardNoteElement,
  BoardStrokeElement,
} from '@/components/editor/board';
 
const editor = createEditor({
  plugins: [
    BoardPlugin.configure({ component: BoardElement }),
    BoardNotePlugin.configure({ component: BoardNoteElement }),
    BoardGeoPlugin.configure({ component: BoardGeoElement }),




import {
  BoardArrowPlugin,
  BoardFramePlugin,
  BoardGeoPlugin,
  BoardNotePlugin,
  BoardPlugin,
  BoardStrokePlugin,
} from 'platejs/board/react';
import { createEditor } from 'platejs/react';
 
import {
  BoardArrowElement,
  BoardElement,
  BoardFrameElement,
  BoardGeoElement,
  BoardNoteElement,
  BoardStrokeElement,
} from '@/components/editor/board';
 
const editor = createEditor({
  plugins: [
    BoardPlugin.configure({ component: BoardElement }),
    BoardNotePlugin.configure({ component: BoardNoteElement }),





For pictures, also install ImagePlugin and BoardImagePlugin.configure({ component: BoardImageElement }). For picture files, install UploadPlugin too.

Keyboard and pointer

Mod is Command on a Mac and Control elsewhere. The board has one Tab stop, its focus target, which holds focus while you move between shapes.

InputResult
A press on a shape with the select toolSelects it. Shift adds it to the selection.
A click with the note, shape or frame toolPlaces that shape at its default size, centered on the click, over empty board or over another shape. It selects the new shape and picks the select tool, or keeps the tool while the tool lock is on.
A drag with the note, shape or frame toolDraws that shape over the dragged box, over empty board or over another shape, and shows the picked outline while you drag. Shift keeps a square, and Alt centers the box where the drag started. It selects the new shape and picks the select tool, or keeps the tool while the tool lock is on.
A drag on a selected shape's corner handle, which shows only with the select toolResizes the shape once the pointer has gone 8 px, down to 8 a side, with the opposite corner in place. Shift keeps its proportions, and Alt resizes it around its center. An image shape keeps its proportions with or without Shift. A resize that keeps proportions stops when the short edge reaches 8, and a shape whose short edge is already under 8 can only grow. Each edge the drag moves lines up with the nearest edge or center of another shape or frame in view within 8 screen px, and a line shows each edge that lines up. The shape never lines up with arrows or pen lines. Hold Control or Command to resize it freely.
Enter on the selected board, or on the focused board with nothing selected and any tool but the note, shape, frame and arrow toolsSelects its first shape. On an empty selected board, it focuses the board, so the tool letters work.
Tab and Shift+TabMove between shapes in the order the board stores them, and leave the board after the last one. A shape outside the view comes into it.
Mod with an arrowSelects the nearest shape in that direction and brings it into view. With nothing selected, it starts from the view's center. With no shape that way, the selection stays and the board says it again.
Double click with the select tool, or Enter on one selected note, shape or arrow with any tool but the note, shape, frame and arrow tools, or on one selected arrow with the arrow toolEdits its text. An image shape has no text, so both keep it selected.
EscapeEnds a drag, a connect, a resize or picking in flight and keeps the tool. Otherwise it climbs from the text to its shape. On the focused board or its selected shapes, it then picks the select tool when another tool is picked, or climbs to the board when the select tool is picked.
Shift+Enter on the focused board or its selected shapesMoves focus to the toolbar. Escape or Shift+Tab moves it back.
V, H, N, R, A, F, P, EPick the select, hand, note, shape, arrow, frame, pen and eraser tools.
Q on the focused board or its selected shapesTurns the tool lock on or off. While it is on, the note, shape, frame and arrow tools stay picked after each shape they add, so you can add several in a row. Escape and the tool letters change the tool and keep the lock. A held Q turns it once, and Q in a shape's text types a q.
Enter with the note or shape tool, on the focused board or its selected shapesPlaces a note or shape of the default size 24 px to the right of the selection, or at the view's center with nothing selected. It selects the new shape and picks the select tool, so the next Enter edits its text. While the tool lock is on, it keeps the tool, so the next Enter places another one beside it. When another shape that is not an arrow has its top-left corner where the new shape's top-left corner would go, it tries 24 px down and right, then 48 px, and so on. When no point it tries is free, or a coordinate it would store is not a finite number, Enter places nothing and says the selection again.
Enter with the frame tool, on the focused board or its selected shapesPlaces a frame around the selected shapes, padded by 24 px. The frame takes in each shape wholly inside it that no frame holds yet and no suggestion removes. It never takes in an arrow or a frame. With nothing selected, Enter places a frame of the default size at the view's center. It selects the new frame and picks the select tool, or keeps the frame tool while the tool lock is on. When a coordinate the frame would store is not a finite number, or a frame around the selection would take in no shape, Enter places nothing and says the selection again.
Enter with the arrow tool and one shape selected that is not an arrowStarts connecting that shape. Tab and Shift+Tab aim the arrow's end at the middle of the other shapes that are not arrows, wrapping at either end, and Mod with an arrow aims it at the nearest one that way from the end. The arrow keys move the end by 1, or 10 with Shift. It binds where it sits in the frontmost shape under it that is not an arrow or the start, counting a frame only on its edge and a pen line only on its line, and stays free off every such shape. Enter draws the arrow from the start's middle to the end, selects it and picks the select tool, or keeps the arrow tool while the tool lock is on. Escape, a left or middle press on the board, another tool, an undo or redo, Mod+D, removing the shape it started from, the view turning read-only, or focus leaving the board ends the connect without drawing.
Enter with the arrow tool and nothing selectedStarts an arrow at the view's center. The arrow keys move its start by 1, or 10 with Shift. At the center and after each move, the start binds where it sits in the frontmost shape under it that is not an arrow, counting a frame only on its edge and a pen line only on its line, and stays free off every such shape. Tab, Shift+Tab and Mod with an arrow aim it at a shape's middle. Enter keeps the start and connects from there, as the row above does from a selected shape, and the end can bind to any shape but the start's. The same keys and events end it without drawing, and removing the shape the start binds to ends it too.
Enter with the arrow tool and several shapes selectedSays the selection again through shapes and draws nothing.
S with one shape selected that is not an arrowStarts resizing the shape from its bottom-right corner. Tab moves to the next corner clockwise and Shift+Tab to the one before. The arrow keys move the corner by 1, or 10 with Shift, down to 8 a side, and the opposite corner stays where it is. An image shape keeps its proportions, so it stops when the short edge reaches 8, and one whose short edge is already under 8 can only grow. Each key shows the new box, with the arrows bound to the shape following it, and writes nothing. Enter writes the box as one undo step when it changed. Escape, a pointer press, the view turning read-only, removing the shape or focus leaving the board puts the box back and writes nothing, and so does any other key, which then does what it does.
Space on the focused boardStarts picking shapes. The cursor starts on the first selected shape in stored order, or on the first shape with nothing selected, and the copied board rings it with a dashed line. Tab and Shift+Tab move the cursor through every shape in stored order and wrap, and Mod with an arrow moves it to the nearest shape that way. Neither changes the selection. Space adds the cursor's shape to the selection or takes it out. Enter or Escape keeps the selection and ends picking. A pointer press, focus leaving the board or removing the cursor's shape ends it too, and so does any other key, which then does what it does. The board acts when Space comes up, and only for a press that went down on the focused board with no modifier and met no other key or pointer press before it came up, so a drag with Space held still pans. During a resize, Space only ends it, as any other key does. During a connect or a pointer gesture, or on a board with no shapes, Space does nothing.
Arrow keysNudge the selected shapes by 1 point, or 10 with Shift. During a connect they move the end being placed instead. For an arrow begun with nothing selected, that is the start until Enter keeps it, then the end. During a resize they move its corner.
] and [Bring the selected shapes forward or send them backward one step.
Mod+Shift+Up and Mod+Shift+DownBring the selected shapes to the front or send them to the back.
Delete or BackspaceRemoves the selected shapes. A frame goes with the shapes in it.
Mod+A with a shape selectedSelects every shape of the board.
Mod+D on the focused board or its selected shapesCopies the selected shapes, with the shapes in a selected frame, as one undo step, and selects the copies. As with a paste, the copies land 24 px down and right of their sources, or further while another shape sits at their place. A held Mod+D copies once. With nothing selected, a writable board says the selection again. A read-only board copies nothing and says nothing, as with the other keys that write. With shapes selected in a writable view, Mod+D first ends a drag or a connect in flight. In a shape's text, the board leaves Mod+D to the text.
Mod+Z, and Mod+Shift+Z or Control+YUndo and redo. Control+Y redoes only off a Mac. Focus follows the shapes the undo selects.
= or +, and -Zoom in or out to the next of 10, 25, 50, 100, 200, 400 and 800 percent.
Shift+0Zooms to 100 percent.
Shift+1Fits every shape in the view.
PageDown and PageUpPan down or up by 80 percent of the view, or right and left with Shift.
A drag on a shape with the select toolMoves the selected shapes, and the shapes in a selected frame, once the pointer has gone 8 px, so a click moves nothing. On each axis the selected shapes line up with the nearest edge or center of another shape or frame in view within 8 screen px, and a line shows each edge or center they share. They never line up with arrows or pen lines. They also space evenly with the nearest shapes beside them, within the same 8 screen px: halfway between two, or at the gap the next two already have. A line with a tick at each end marks each equal gap. Hold Control or Command to move them freely. The move is one undo step.
A drag with the select tool and Alt heldCopies the dragged shapes, lined up as a move lines them up. A copy that lands at another shape's place moves 24 px down and right, as with a paste.
A click or drag with the eraserMarks every note, shape, arrow and pen line it passes over, and removes them on release as one undo step. A shape with no fill and no label is marked only where the path passes near its outline, so a pen line inside an empty rectangle goes alone. A frame is never marked; select it and press Delete to remove it. Escape or another tool picked mid-drag removes nothing.
A drag on the empty board with the select toolDraws a selection box and selects every shape wholly inside it. Shift keeps the shapes already selected. A touch drag pans instead.
A drag with the handPans, from any point and over shapes and the text being edited too. It selects, moves and edits nothing. While the hand is picked, the pointer is an open hand, except over an element with its own cursor.
Wheel, or a drag with Space held or with the middle buttonPans, from any point and over shapes too. Mod with the wheel zooms.

On a read-only board, the keys that change nothing still work: Tab and Shift+Tab, Mod with an arrow, Mod+A, Enter on the board, Space picking, Escape, Shift+Enter, the tool letters, Q, and the zoom, fit and pan keys. The keys that write do nothing and say nothing. With the note, shape, frame or arrow tool, Enter does what it does with the select tool. After the last shape, Tab clears the selection and the browser moves focus out of the board.

Backspace at the start of the block after a board, or Delete at the end of the block before it, selects the board. The next Backspace or Delete removes it with every shape, and one undo puts it back.

Screen readers

The board says what happens through the editor's one status region, in the words your copied board passes as messages. The prop is required, and the package ships no English word. Only the view that holds focus says anything, so a second view of the same board stays silent. A member that returns an empty string says nothing. Moves, restacks and pans say nothing.

MemberUse
labelThe board's name, on its focus target and on the region of its shapes.
instructionsThe focus target's description, which a screen reader says when the board takes focus.
aim(shape, { anchor, position, side, total })Said when the arrow end the keys move binds to shape: when Tab, Shift+Tab or Mod with an arrow aims it at the shape's middle, when an arrow key moves it into or within the shape, and again when Mod with an arrow finds no shape that way. anchor is where the end sits in the shape in whole percents, across from its left edge and down from its top, so the middle is 50 and 50. side is 'start' while the keys place the start of an arrow begun with nothing selected, and 'end' while they move its end. position and total give the shape's place in stored order among all shapes.
connecting(from)Said when Enter with the arrow tool starts connecting from, the one selected shape, and when Enter keeps the start of an arrow begun with nothing selected, with from as the shape that start binds to, or null for a start on no shape. While the keys place the end and the connect has none, before an arrow key or an aim key places one and after the shape it binds to is removed, Enter and an aim key that finds no shape say it again. Enter also says it again, and draws no arrow, when the arrow would have no length, as with the end back at the start's point.
free(place, { side })Said when an arrow key moves the arrow end the keys move onto no shape it can bind to, with the board point it sits at in whole units, and again when Tab, Shift+Tab or Mod with an arrow finds no shape. side is that end, as in aim.
starting(place, { from })Said when Enter with the arrow tool and nothing selected starts an arrow at place, the view's center in whole units. The start binds to the shape under that point as an arrow key move binds it, and sits free where that move would bind it to no shape. from is the shape the start binds to, or null for a free start.
resizing(shape, { corner, width, height })Said when S starts resizing shape from corner, its bottom-right corner, with its size in whole units. When Enter, Escape or any other end that says nothing of its own ends the resize, the board says the shape again through shape. A pointer press ends it without saying anything, so the board says only what the press itself does.
resize({ corner, width, height })Said when Tab or Shift+Tab moves a resize to another corner, and when an arrow key moves the corner, with the box's size in whole units.
picking(shape, { count, position, selected, total })Said when Space starts picking, with shape under the cursor. selected says whether that shape is selected, count how many shapes are selected, and position and total give the shape's place in stored order among all shapes. When Enter, Escape or any other end that says nothing of its own ends picking, the board says the selection again through shape or shapes. A pointer press ends it without saying anything, so the board says only what the press itself does.
pick(shape, { count, position, selected, total })Said when Tab, Shift+Tab or Mod with an arrow moves the cursor to shape, again when Mod with an arrow finds no shape that way, and when Space adds the cursor's shape to the selection or takes it out, with the same state as picking.
shape(shape, { position, total })Said when the selection becomes one shape, with its place in stored order, such as Ship it, Shape. 3 of 5.
shapes(count)Said when the selection becomes several shapes, and with 0 when the board says the selection again while no shape is selected, such as after Mod with an arrow on a board with no shapes.
tool(tool)Said when a letter or the toolbar picks a tool.
toolLock(locked)Said when Q or setToolLocked turns the tool lock on or off, with whether it is now on.
zoom(percent)Said when a zoom key, zoomIn, zoomOut, resetZoom or fit changes the zoom. A wheel zoom says nothing.
removed(count)Said when a removal lands, with the number of shapes it took off the board, a removed frame's shapes included.

shape, aim, connecting, starting, resizing, picking and pick get a BoardShapeDescription. Its kind is note, geo, arrow, frame, stroke, or shape for an image shape or a shape your app defines, and its text is the shape's text or a frame's name. An arrow's ends describe the shapes its ends attach to, or null for a free end. A resize's corner is a BoardCorner, one of topLeft, topRight, bottomRight and bottomLeft, and picking and pick also get a BoardPickState. The copied board passes:

const boardMessages: BoardMessages = {
  label: 'Board',
  instructions:
    'Enter selects the first shape. Tab moves between shapes and leaves them after the last. Command with an arrow on a Mac, or Control with an arrow elsewhere, picks the nearest shape. With the note, shape or frame tool, Enter places one, and with the arrow tool and one shape selected that is not an arrow, Enter connects it to another, whose end the arrow keys then move. With the arrow tool and nothing selected, Enter starts an arrow whose start the arrow keys move until a second Enter keeps it. With one shape selected that is not an arrow, S resizes it: Tab picks a corner, the arrow keys move it and Enter keeps the new size. Space starts picking shapes: Tab moves, Space adds or removes the shape and Enter keeps the selection. Q keeps the drawing tool picked after each shape until a second Q, and Command+D on a Mac, or Control+D elsewhere, copies the selected shapes. Shift+Enter reaches the toolbar.',
  aim: (shape, { anchor, position, side, total }) =>
    `${side === 'start' ? 'From' : 'To'} ${nameOf(shape)}${anchor.across === 50 && anchor.down === 50 ? '' : `, ${anchor.across}% across, ${anchor.down}% down`}. ${position} of ${total}`,
  connecting: (from) =>
    `Connecting ${from ? nameOf(from) : 'a free point'}. Tab picks a shape, arrow keys move the end, Enter draws the arrow and Escape stops.`,
  free: ({ x, y }, { side }) =>
    `${side === 'start' ? 'Start' : 'End'} free at ${x}, ${y}`,
  starting: ({ x, y }, { from }) =>
    `Drawing an arrow from ${from ? nameOf(from) : `${x}, ${y}`}. Arrow keys move its start, Tab picks a shape, Enter keeps the start and Escape stops.`,
  resizing: (shape, { corner, height, width }) =>
    `Resizing ${nameOf(shape)} from its ${CORNERS[corner]} corner, ${width} by ${height}. Tab picks a corner, arrow keys resize, Enter keeps it and Escape stops.`,
  resize: ({ corner, height, width }) =>
    `${CORNERS[corner]}, ${width} by ${height}`,
  picking: (shape, state) =>
    `Picking shapes. ${pickOf(shape, state)}. Tab moves, Space adds or removes, Enter finishes.`,
  pick: (shape, state) => pickOf(shape, state),
  shape: (shape, { position, total }) =>
    `${nameOf(shape)}. ${position} of ${total}`,
  shapes: (count) =>
    count === 0 ? 'No shapes selected' : `${count} shapes selected`,
  tool: (tool) => TOOL_NAMES[tool],
  toolLock: (locked) => (locked ? 'Tool lock on' : 'Tool lock off'),
  zoom: (percent) => `Zoom ${percent}%`,
  removed: (count) =>
    count === 1 ? 'Shape deleted' : `${count} shapes deleted`,
};
const boardMessages: BoardMessages = {
  label: 'Board',
  instructions:
    'Enter selects the first shape. Tab moves between shapes and leaves them after the last. Command with an arrow on a Mac, or Control with an arrow elsewhere, picks the nearest shape. With the note, shape or frame tool, Enter places one, and with the arrow tool and one shape selected that is not an arrow, Enter connects it to another, whose end the arrow keys then move. With the arrow tool and nothing selected, Enter starts an arrow whose start the arrow keys move until a second Enter keeps it. With one shape selected that is not an arrow, S resizes it: Tab picks a corner, the arrow keys move it and Enter keeps the new size. Space starts picking shapes: Tab moves, Space adds or removes the shape and Enter keeps the selection. Q keeps the drawing tool picked after each shape until a second Q, and Command+D on a Mac, or Control+D elsewhere, copies the selected shapes. Shift+Enter reaches the toolbar.',
  aim: (shape, { anchor, position, side, total }) =>
    `${side === 'start' ? 'From' : 'To'} ${nameOf(shape)}${anchor.across === 50 &&






















Insert shapes from code

Every board command runs inside editor.update with no selection, so a Node agent on the same Yjs document uses the same calls as the toolbar. A board insert returns the board's key, and a shape insert names its board and returns the new shape's id. Shape ids are unique in the whole document, so later commands name a shape by its id alone.

import {
  BaseBoardArrowPlugin,
  BaseBoardGeoPlugin,
  BaseBoardNotePlugin,
  BaseBoardPlugin,
} from 'platejs/board';
 
editor.update((tx) => {
  const board = tx.plugin(BaseBoardPlugin).insert({ height: 480 }, { at: [1] });
 
  if (!board) return;
 
  const note = tx.plugin(BaseBoardNotePlugin).insert(
    {
      children: [{ children: [{ text: 'Launch' }], type: 'paragraph' }],
      x: 120,
      y: 80,
    },
    { board }
  );
  const rect = tx
    .plugin(BaseBoardGeoPlugin)
    .insert({ geo: 'rectangle', x: 480, y: 80 }, { board });
 
  if (note && rect) {
    tx.plugin(BaseBoardArrowPlugin).insert({ end: rect, start: note });
  }
});
import {
  BaseBoardArrowPlugin,
  BaseBoardGeoPlugin,
  BaseBoardNotePlugin,
  BaseBoardPlugin,
} from 'platejs/board';
 
editor.update((tx) => {
  const board = tx.plugin(BaseBoardPlugin).insert({ height: 480 }, { at: [1] });
 
  if (!board) return;
 
  const note = tx.plugin(BaseBoardNotePlugin).insert(
    {
      children: [{ children: [{ text: 'Launch' }], type: 'paragraph' }],
      x: 120,











Move, resize, restack and remove shapes by id:

editor.update((tx) => {
  const boards = tx.plugin(BaseBoardPlugin);
 
  boards.move([noteId], { x: 40, y: 0 });
  boards.resize(noteId, { height: 240, width: 240, x: 160, y: 80 });
  boards.restack([noteId], 'front');
  boards.remove([rectId]);
});
editor.update((tx) => {
  const boards = tx.plugin(BaseBoardPlugin);
 
  boards.move([noteId], { x: 40, y: 0 });
  boards.resize(noteId, { height: 240, width: 240, x: 160, y: 80 });
  boards.restack([noteId], 'front');
  boards.remove([rectId]);
});

A style change is a plain property write on the shape's key, with a style its shape type takes, as Value shape lists:

editor.update((tx) => {
  const shape = tx.plugin(BaseBoardPlugin).shape(rectId);
 
  if (shape) {
    tx.nodes.set({ fill: 'blue', strokeWidth: 'l' }, { at: shape.key });
  }
});
editor.update((tx) => {
  const shape = tx.plugin(BaseBoardPlugin).shape(rectId);
 
  if (shape) {
    tx.nodes.set({ fill: 'blue', strokeWidth: 'l' }, { at: shape.key });
  }
});

In a toolbar, setStyle writes the selected shapes, as Style panel shows.

Add your own shape

defineBoardShape defines a shape that holds text, with its own properties and default size. List it in the board's targetPlugins, beside the shape types you keep. The shape then gets its id, place and size, stacking, frames, arrow ends, copy and paste, suggestions and sync from the board.

import { property } from 'platejs';
import {
  BaseBoardGeoPlugin,
  BaseBoardNotePlugin,
  BaseBoardPlugin,
  defineBoardShape,
} from 'platejs/board';
 
const BaseCardPlugin = defineBoardShape('card', {
  properties: { status: property.enum(['todo', 'doing', 'done'], { default: 'todo' }) },
  size: { height: 160, width: 240 },
  styles: { fill: 'blue', opacity: 1, textSize: 'm' },
});
 
const plugins = [
  BaseBoardPlugin.configure({
    targetPlugins: [BaseBoardNotePlugin, BaseBoardGeoPlugin, BaseCardPlugin],
  }),
  BaseBoardNotePlugin,
  BaseBoardGeoPlugin,
  BaseCardPlugin,
];
import { property } from 'platejs';
import {
  BaseBoardGeoPlugin,
  BaseBoardNotePlugin,
  BaseBoardPlugin,
  defineBoardShape,
} from 'platejs/board';
 
const BaseCardPlugin = defineBoardShape('card', {
  properties: { status: property.enum(['todo', 'doing', 'done'], { default: 'todo' }) },
  size: { height: 160, width: 240 },
  styles: { fill: 'blue', opacity: 1, textSize: 'm' },
});
 
const plugins = [
  BaseBoardPlugin.configure





tx.plugin(BaseCardPlugin).insert({ status: 'doing', x: 0, y: 0 }, { board }) adds a card. HTML serialize refuses a board that holds your own shape, so persist the Plate value for such a board.

Value shape

A board block sits in its document like any other block and holds one empty text. Its shapes sit in the content root that childRoots.shapes names, as that root's top-level blocks. The board's insert creates the block and its root in one change and names the root, so app code never names a root.

const value = {
  children: [
    {
      childRoots: { shapes: 'board:k3f9' },
      children: [{ text: '' }],
      height: 480,
      type: 'board',
    },
  ],
  roots: {
    'board:k3f9': [
      {
        children: [{ children: [{ text: 'Launch' }], type: 'paragraph' }],
        place: { x: 40, y: 30 },
        shapeId: 'n1',
        size: { height: 160, width: 200 },
        type: 'boardNote',
        zIndex: 'a1',
      },
    ],
  },
};
const value = {
  children: [
    {
      childRoots: { shapes: 'board:k3f9' },
      children: [{ text: '' }],
      height: 480,
      type: 'board',
    },
  ],
  roots: {
    'board:k3f9': [
      {
        children: [{ children: [{ text: 'Launch' }], type: 'paragraph' }],
        place: { x: 40, y: 30 },
        shapeId: 'n1',
        size: { height: 160, width: 200 },
        type: 'boardNote',
        zIndex: 'a1',
      },


PropertyShapesNotes
shapeIdAllUnique in the whole document. Every paste, drop and duplicate gives its copy a fresh id.
zIndexAllA fractional key that sets the paint order. Frames paint behind the other shapes.
placeAll but arrows{ x, y }. Inside a frame it also holds frame and frameOrigin, and x and y are measured from the frame. A frame's own place holds its origin.
sizeAll but arrows{ width, height }.
start, endArrows{ shape, anchor, x, y } for an end bound to a shape, or { x, y } for a free end. x and y hold the point the end last drew at.
pointsPen linesFlat [x, y, pressure] triples, each a fraction of the line's box.
fillNotes and geo shapes'none', a color name or any CSS color. Defaults to 'yellow' on a note and 'none' on a geo shape.
strokeColorGeo shapes, arrows and pen linesA color name or any CSS color. Defaults to 'currentColor', the text color.
dashGeo shapes and arrows'solid', 'dashed' or 'dotted'. Defaults to 'solid'.
strokeWidthGeo shapes and arrows's', 'm', 'l' or 'xl'. Defaults to 'm'.
opacityAll but frames and image shapesA number from 0.1 to 1. Defaults to 1.
textSizeNotes, geo shapes and arrows's', 'm', 'l' or 'xl'. Defaults to 'm', or 's' on an arrow.
geoGeo shapesOne of 'rectangle', 'ellipse', 'diamond' or 'triangle'.
nameFramesShown above the frame.
childrenImage shapesAt most one image element, whose url and alt ImagePlugin keeps, or an upload draft when the editor installs UploadPlugin.

The copied board paints the color names blue, green, grey, orange, red, violet and yellow with a light and a dark value, and any other string as a CSS color. HTML keeps each style in a data-board- attribute, such as data-board-stroke-width.

The camera, the tool, the tool lock, the next style, the selection handles and a gesture in progress are never stored.

Collaboration

Each shape is a block of the document, so YjsPlugin syncs boards with no extra setup. When two people change different properties of one shape, such as a move and a recolor, both changes stay. A drag reaches teammates as one change when it is dropped.

Add the board to an app with Yjs rooms

Adding the board adds element types, so it changes the app's schema identity. A Yjs room keeps the schema identity it was created with, so an editor with the board refuses to join a room written before it. It throws a Yjs schema mismatch error, or Yjs derived schema mismatch when the app declares no schema. Move each room's document to a new room:

Bump the schema version

Add a migration step for the new version. A step that only adds element types returns the document unchanged. Register the version 3 fingerprint in sourceFingerprints from the migration scaffold, as document migrations shows.

src/editor.ts
import { defineDocumentMigrations } from 'platejs/migrations';
 
import { BoardKit } from '@/components/editor/board';
import { EditorKit } from '@/components/editor/plugins';
 
import { fingerprint as v3Fingerprint } from './migrations/v4-add-board/from';
 
export const EditorPlugins = [...EditorKit, ...BoardKit];
 
export const EditorSchema = { id: 'acme-document', version: 4 } as const;
 
export const EditorMigrations = defineDocumentMigrations({
  plugins: EditorPlugins,
  schema: EditorSchema,
  sourceFingerprints: { 3: v3Fingerprint },
  steps: { 4: ({ document }) => ({ document }) },
});
src/editor.ts
import { defineDocumentMigrations } from 'platejs/migrations';
 
import { BoardKit } from '@/components/editor/board';
import { EditorKit } from '@/components/editor/plugins';
 
import { fingerprint as v3Fingerprint } from './migrations/v4-add-board/from';
 
export const EditorPlugins = [...EditorKit, ...BoardKit];
 
export const EditorSchema = { id: 'acme-document', version: 4 } as const;
 
export const EditorMigrations = defineDocumentMigrations({
  plugins: EditorPlugins,
  schema: EditorSchema,
  sourceFingerprints: { 

Migrate the old room's document

Read the document and its schema identity from an editor bound to the old room, with the old plugins and schema, then migrate it.

import { migrateDocument } from 'platejs/migrations';
 
const current = migrateDocument(
  {
    document: oldEditor.read.value(),
    schema: oldEditor.read.schema.identity(),
  },
  { migrations: EditorMigrations }
).output;
import { migrateDocument } from 'platejs/migrations';
 
const current = migrateDocument(
  {
    document: oldEditor.read.



Seed a new room

Create the new room's editor from the migrated document. Give seed: true to one editor only, the one your app picked to fill the new empty room.

import { createEditor } from 'platejs/react';
import { YjsPlugin } from 'platejs/yjs/react';
 
const editor = createEditor({
  initialValue: current,
  plugins: [
    ...EditorPlugins,
    YjsPlugin.create({
      doc: newRoomDocument,
      initialReady: true,
      rootName: newRoomId,
      seed: true,
    }),
  ],
  schema: EditorSchema,
});

Every other peer joins the new room with the new plugins and schema, and without seed. See Yjs and document migrations.

Limits

  • Find searches only the page, not the text of notes. Word export leaves out a comment on note text and reports a comment-range warning.
  • With the caret in a note, the copied toolbars and the AI menu act on the note, as Toolbar describes. Insert and Turn into then disable the blocks a note cannot hold, such as tables, quotes and code blocks.
  • Typing / or a space in an empty note paragraph inserts the character and opens no menu.
  • Moving a paragraph inside a note is refused. Moving the whole shape keeps its text.
  • Undo of a move puts back your old place, even over a teammate's later move of the same shape.
  • A long note gets slower, because a note's lines sync as one unit.
  • Each keystroke does some work for every board in the document, so keep a document to 100 boards or fewer.
  • Markdown keeps the text and pictures of the shapes in stored order and reports what it drops, such as places and arrow ends. Persist the Plate value, or HTML when the board holds only built-in shape types, to keep a board whole.
  • Without UploadPlugin, a picture file pasted or dropped on a board lands no shape, the board reports nothing, and the copied toolbar's Image button is disabled. Paste the picture's link, or insert it from code.
  • A paste, drop or pick of more pictures than UploadPlugin takes in one batch lands none of them, and onError gets a too-many-files failure that holds the limit. The copied UploadKit takes three pictures in one batch.
  • A pasted note keeps the note tool's 200 by 200 size, so long text runs past its bottom edge.
  • A shape property named after a style mark's key, such as color, backgroundColor, fontSize or fontFamily, also styles the shape's text while that mark's plugin is installed. Give the property another name, the way the note uses fill.
  • A board inside a note, rotation and cropping a picture are not supported, and the copied board draws no caption under a picture.
  • Drawing with the pen needs a pointer. A keyboard resize keeps the proportions of an image shape only, and cannot resize around the center, which Shift and Alt do on a corner drag.
  • No key or pointer gesture moves a bound arrow end off its shape, or resizes several shapes at once. Moving a selected arrow moves its free ends, and each bound end stays on its shape.
  • An export of a selected frame holds the frame's shapes but not an arrow between them, because an arrow never belongs to a frame. Select the arrow too to include it.
  • On a board page, the board is still a block of the document. Delete or Backspace with the board selected removes it with its shapes, and Undo brings it back. With exit break installed, Mod+Enter with the caret on the board, where Mod+A can put it, adds a paragraph after the board, out of sight.

Plugins

BoardPlugin

The board block, a void element that owns a content root of shapes. targetPlugins lists the shape types the board holds, by default the six below.

BoardNotePlugin, BoardGeoPlugin, BoardArrowPlugin, BoardFramePlugin, BoardStrokePlugin

The shape types: boardNote, boardGeo, boardArrow, boardFrame and boardStroke. Frames and pen lines are voids; notes, geo shapes and arrows hold blocks.

BoardImagePlugin

The image shape, boardImage: an object block that holds at most one image element or upload draft. Install ImagePlugin with it, and UploadPlugin too for picture files. An editor that installs it with neither ImagePlugin nor UploadPlugin throws an error naming both.

API Reference

APIPackageUse
BaseBoardPlugin, BaseBoardNotePlugin, BaseBoardGeoPlugin, BaseBoardImagePlugin, BaseBoardArrowPlugin, BaseBoardFramePlugin, BaseBoardStrokePluginplatejs/boardHeadless board and shape plugins.
defineBoardShape(name, { properties, size, styles })platejs/boardDefines an app shape that holds text, with the default of each board style it takes.
tx.plugin(BaseBoardPlugin).insert(props?, options?)BaseBoardPluginAdds a board with an empty root at options.at or after the selected block, and returns its key.
tx.plugin(BaseBoardNotePlugin).insert(props, { board })Each shape pluginAdds a shape above every shape of board and returns its id. An arrow takes { start, end }, each a shape id, { shape, anchor } or a board point, and joins the board its bound ends name. An image shape takes { children: [image] } and is 320 by 240 unless width and height say otherwise.
move(ids, delta)BaseBoardPluginMoves shapes. A shape joins the frontmost frame under its middle or leaves its frame.
resize(id, { x, y, width, height })BaseBoardPluginSets a shape's place and size together. On an image shape the height follows width. A shrink stops at a short edge of 8, and one whose short edge is already under 8 can only grow.
restack(ids, direction)BaseBoardPlugin'front', 'back', 'forward' or 'backward', in paint order only.
remove(ids)BaseBoardPluginRemoves shapes, each frame with its shapes. An arrow bound to a removed shape keeps a loose end where it drew it.
removeFrame(id)BaseBoardPluginRemoves a frame and keeps its shapes where they are.
insertCopy(slice, { board, place? })BaseBoardPluginPastes a copy of the shapes in slice into board, with fresh ids, and returns the copies' ids.
shapes(board), shape(id), arrowEnds(id), strokePath(id), slice(ids)BaseBoardPluginRead the shapes of a board, one shape by id in any board, where an arrow draws its ends, a pen line's outline, and the slice a copy of shapes carries. strokePath returns null when the id names no pen line. Call them on tx.plugin(BaseBoardPlugin) inside an update, or on editor.read.board outside one, such as on a server with no mounted board.
BoardStrokePathplatejs/boardA pen line's outline: an SVG path over a box of width by height, the line's stored size, which you scale to the box shape(id) gives.
BoardSurface, BoardShapeplatejs/board/reactThe board's mounted view and a shape's positioned wrapper, for copied renderers. The surface's required messages holds every word the board says, as Screen readers lists. Its height sets its view's height and defaults to the board's stored height. A shape the eraser will remove shows data-erasing, which the copied board fades, and the shape under the picking cursor shows data-board-cursor, which the copied board rings. A plain wheel over a toolbar element that can still scroll in the wheel's main direction scrolls that element instead of panning the board.
data-board-dockplatejs/board/reactMarks an element at the top level of the surface's toolbar that sits at the board's "left" or "right" side. Every other top-level toolbar element counts as a row at the board's top or bottom. fit and Shift+1 fit the shapes into the room the toolbar leaves clear. Where that room's width or height cannot hold them at 10 percent, they use the board's whole width or height. Both zoom between 10 and 100 percent, so shapes the board cannot hold at 10 percent run past its edges.
BoardMessages, BoardShapeDescription, BoardCorner, BoardPickStateplatejs/board/reactThe type of messages, the shape that messages.shape describes, the corner a resize moves, and where picking stands when the board says picking or pick.
useBoardView(selector), useBoardActions()platejs/board/reactInside the surface's toolbar, read the view's tool, toolLocked, camera and nextStyle, its board's selected shapes as selectedShapes, each style a pick would set as styles, whether it can write as writable, and whether its board takes picture files as takesPictureFiles. A camera zoom of 1 is 100 percent. Call setTool, setToolLocked, setStyle, fit, , , , , , and . From any zoom, and go to the next step the or and keys use, and stop at 800 and 10 percent. zooms to 100 percent, as Shift+0 does. All three work in a read-only view too. says whether the note, shape, frame and arrow tools stay picked after they add a shape. It is off when the view mounts and is never stored, and turns it on or off, as Q does, without changing the tool or the selection. moves focus back to the board and keeps its selection, such as after a toolbar menu closes. A shape whose text is being edited ends its edit and stays selected. merges into the next style. With the select tool it also writes each style to every selected shape that takes it and to the shape whose text is being edited, as one undo step that keeps the caret. With a drawing tool it styles only the next shape. Each entry of is when its targets share a value and when they differ, and a style no target takes has no entry. A read-only view's changes nothing. lands picture files as image shapes in a row centered on the view, as describes. It changes nothing with an empty list or while is false. draws the selected shapes, or the whole board when nothing is selected, as a or picture with the static plugins in . can be a promise, such as a dynamic import, as shows. It reads the selection when it is called and loads its drawing code on the first call. It resolves when there is nothing to draw, and rejects when the surface is not on the page or leaves it before the picture is drawn. Both hooks throw outside a .
BoardPicture, BoardPictureOptions, BoardPictureWarningplatejs/board/reactWhat exportPicture resolves, what it takes, and each warning in the picture's warnings. A warning's code is content-undrawn, downscaled, font-missing, image-unreadable or shape-undrawn, and the last two also name the shapeId.
BoardArrowPath, BoardArrowhead, BoardArrowLabelplatejs/board/reactDraw an arrow inside its BoardShape. BoardArrowPath is an SVG path whose d runs between the arrow's ends. BoardArrowhead is an SVG g that draws its children at the arrow's end, turned so that the positive x axis points along the arrow. It sets its own transform and display, so style the head through its children. BoardArrowLabel is an absolutely positioned div that holds the arrow's text, centered on the arrow's middle. It sets its own left and top, and a can override its and the that centers it. All three follow a moved, dragged or resized shape without a render of the arrow. An arrow's is an empty box at the board's origin, and is in board coordinates. So draw the path and the head in a 1 by 1 , because Firefox draws nothing in an of zero size. Give that visible overflow and , and put it inside an element with . A press picks an arrow only when it lands on one of the arrow's elements, so give one path , such as a wide transparent . Until the arrow has a drawing, the path has no and the head and the label are hidden. Each throws outside an arrow's .
useStrokePath(element)platejs/board/reactThe drawn path of a pen line in a mounted board. It returns the BoardStrokePath that strokePath(id) reads, or undefined when the element is not a pen line of that board.
import {
BoardArrowhead,
BoardArrowLabel,
BoardArrowPath,
BoardArrowPlugin,
type BoardCorner,
BoardFramePlugin,
BoardGeoPlugin,
BoardImagePlugin,
type BoardMessages,
BoardNotePlugin,
type BoardPickState,
type BoardPicture,
type BoardPictureWarning,
BoardPlugin,
BoardShape,
type BoardShapeDescription,
BoardStrokePlugin,
type BoardStyle,
BoardSurface,
type BoardTool,
useBoardActions,
useBoardView,
useStrokePath,
} from 'platejs/board/react';
import type { ImageElement } from 'platejs/media';
import { ImagePlugin } from 'platejs/media/react';
import {
type EditorElementProps,
useEditor,
useEditorSelector,
usePath,
} from 'platejs/react';
import * as React from 'react';
import { flushSync } from 'react-dom';
import { toast } from 'sonner';
import { useFilePicker } from 'use-file-picker';
import {
ARROW_HEAD,
BOARD_COLORS,
COLORS,
dashArray,
geoOutline,
paint,
SHAPE_HEADINGS,
STROKE_WIDTHS,
TEXT_SIZES,
tint,
} from '@/components/editor/board-styles';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import {
Toolbar,
ToolbarButton,
ToolbarGroup,
} from '@/components/editor/toolbar';
const TOOLS: ReadonlyArray<
Readonly<{
icon: React.ReactNode;
key: string;
label: string;
tool: BoardTool;
}>
> = [
{ icon: <MousePointer2Icon />, key: 'V', label: 'Select', tool: 'select' },
{ icon: <HandIcon />, key: 'H', label: 'Hand', tool: 'hand' },
{ icon: <StickyNoteIcon />, key: 'N', label: 'Note', tool: 'note' },
{ icon: <SquareIcon />, key: 'R', label: 'Shape', tool: 'geo' },
{ icon: <MoveUpRightIcon />, key: 'A', label: 'Arrow', tool: 'arrow' },
{ icon: <FrameIcon />, key: 'F', label: 'Frame', tool: 'frame' },
{ icon: <PencilIcon />, key: 'P', label: 'Pen', tool: 'pen' },
{ icon: <EraserIcon />, key: 'E', label: 'Eraser', tool: 'eraser' },
];
const GEOS: ReadonlyArray<
Readonly<{
geo: NonNullable<BoardStyle['geo']>;
icon: React.ReactNode;
label: string;
}>
> = [
{ geo: 'rectangle', icon: <SquareIcon />, label: 'Rectangle' },
{ geo: 'ellipse', icon: <CircleIcon />, label: 'Ellipse' },
{ geo: 'diamond', icon: <DiamondIcon />, label: 'Diamond' },
{ geo: 'triangle', icon: <TriangleIcon />, label: 'Triangle' },
];
type BoardStyleOption<TValue> = Readonly<{
icon: React.ReactNode;
label: string;
value: TValue;
}>;
const FILL_OPTIONS: ReadonlyArray<BoardStyleOption<string>> = [
{ icon: <BanIcon />, label: 'None', value: 'none' },
...COLORS.map(({ color, label }) => ({
icon: (
<span
className="size-4 rounded-full border border-foreground/20"
style={{ backgroundColor: paint(color) }}
/>
),
label,
value: color,
})),
];
const OUTLINE_OPTIONS: ReadonlyArray<BoardStyleOption<string>> = [
{
icon: <span className="size-4 rounded-full border-[3px] border-current" />,
label: 'Default',
value: 'currentColor',
},
...COLORS.map(({ color, label }) => ({
icon: (
<span
className="size-4 rounded-full border-[3px]"
style={{ borderColor: paint(color) }}
/>
),
label,
value: color,
})),
];
const line = (props: React.SVGProps<SVGLineElement>) => (
<svg aria-hidden viewBox="0 0 16 16">
<line
stroke="currentColor"
strokeLinecap="round"
x1={2}
x2={14}
y1={8}
y2={8}
{...props}
/>
</svg>
);
const DASH_OPTIONS: ReadonlyArray<
BoardStyleOption<NonNullable<BoardStyle['dash']>>
> = [
{ icon: line({ strokeWidth: 2 }), label: 'Solid', value: 'solid' },
{
icon: line({
strokeDasharray: '4 3',
strokeLinecap: 'butt',
strokeWidth: 2,
}),
label: 'Dashed',
value: 'dashed',
},
{
icon: line({ strokeDasharray: '0 4', strokeWidth: 2 }),
label: 'Dotted',
value: 'dotted',
},
];
const SIZE_LABELS = [
['s', 'Small', 'S'],
['m', 'Medium', 'M'],
['l', 'Large', 'L'],
['xl', 'Extra large', 'XL'],
] as const;
const WIDTH_OPTIONS: ReadonlyArray<
BoardStyleOption<NonNullable<BoardStyle['strokeWidth']>>
> = SIZE_LABELS.map(([value, label]) => ({
icon: line({ strokeWidth: STROKE_WIDTHS[value] }),
label,
value,
}));
const TEXT_OPTIONS: ReadonlyArray<
BoardStyleOption<NonNullable<BoardStyle['textSize']>>
> = SIZE_LABELS.map(([value, label, short]) => ({
icon: <span className="text-xs font-medium">{short}</span>,
label,
value,
}));
const GEO_OPTIONS: ReadonlyArray<
BoardStyleOption<NonNullable<BoardStyle['geo']>>
> = GEOS.map(({ geo, icon, label }) => ({
icon,
label,
value: geo,
}));
const KINDS: Readonly<Record<BoardShapeDescription['kind'], string>> = {
arrow: 'Arrow',
frame: 'Frame',
geo: 'Shape',
note: 'Note',
shape: 'Shape',
stroke: 'Line',
};
const TOOL_NAMES: Readonly<Record<BoardTool, string>> = {
arrow: 'Arrow tool',
eraser: 'Eraser tool',
frame: 'Frame tool',
geo: 'Shape tool',
hand: 'Hand tool',
note: 'Note tool',
pen: 'Pen tool',
select: 'Select tool',
};
const CORNERS: Readonly<Record<BoardCorner, string>> = {
bottomLeft: 'bottom left',
bottomRight: 'bottom right',
topLeft: 'top left',
topRight: 'top right',
};
const nameOf = (shape: BoardShapeDescription): string => {
if (shape.kind === 'arrow') {
const end = (side: BoardShapeDescription | null) =>
side ? nameOf(side) : 'nothing';
const ends = `Arrow from ${end(shape.ends.start)} to ${end(shape.ends.end)}`;
return shape.text ? `${shape.text}, ${ends}` : ends;
}
return shape.text ? `${shape.text}, ${KINDS[shape.kind]}` : KINDS[shape.kind];
};
const pickOf = (
shape: BoardShapeDescription,
{ count, position, selected, total }: BoardPickState
) =>
`${nameOf(shape)}, ${selected ? 'selected' : 'not selected'}. ${position} of ${total}. ${count} selected`;
const boardMessages: BoardMessages = {
label: 'Board',
instructions:
'Enter selects the first shape. Tab moves between shapes and leaves them after the last. Command with an arrow on a Mac, or Control with an arrow elsewhere, picks the nearest shape. With the note, shape or frame tool, Enter places one, and with the arrow tool and one shape selected that is not an arrow, Enter connects it to another, whose end the arrow keys then move. With the arrow tool and nothing selected, Enter starts an arrow whose start the arrow keys move until a second Enter keeps it. With one shape selected that is not an arrow, S resizes it: Tab picks a corner, the arrow keys move it and Enter keeps the new size. Space starts picking shapes: Tab moves, Space adds or removes the shape and Enter keeps the selection. Q keeps the drawing tool picked after each shape until a second Q, and Command+D on a Mac, or Control+D elsewhere, copies the selected shapes. Shift+Enter reaches the toolbar.',
aim: (shape, { anchor, position, side, total }) =>
`${side === 'start' ? 'From' : 'To'} ${nameOf(shape)}${anchor.across === 50 && anchor.down === 50 ? '' : `, ${anchor.across}% across, ${anchor.down}% down`}. ${position} of ${total}`,
connecting: (from) =>
`Connecting ${from ? nameOf(from) : 'a free point'}. Tab picks a shape, arrow keys move the end, Enter draws the arrow and Escape stops.`,
free: ({ x, y }, { side }) =>
`${side === 'start' ? 'Start' : 'End'} free at ${x}, ${y}`,
starting: ({ x, y }, { from }) =>
`Drawing an arrow from ${from ? nameOf(from) : `${x}, ${y}`}. Arrow keys move its start, Tab picks a shape, Enter keeps the start and Escape stops.`,
resizing: (shape, { corner, height, width }) =>
`Resizing ${nameOf(shape)} from its ${CORNERS[corner]} corner, ${width} by ${height}. Tab picks a corner, arrow keys resize, Enter keeps it and Escape stops.`,
resize: ({ corner, height, width }) =>
`${CORNERS[corner]}, ${width} by ${height}`,
picking: (shape, state) =>
`Picking shapes. ${pickOf(shape, state)}. Tab moves, Space adds or removes, Enter finishes.`,
pick: (shape, state) => pickOf(shape, state),
shape: (shape, { position, total }) =>
`${nameOf(shape)}. ${position} of ${total}`,
shapes: (count) =>
count === 0 ? 'No shapes selected' : `${count} shapes selected`,
tool: (tool) => TOOL_NAMES[tool],
toolLock: (locked) => (locked ? 'Tool lock on' : 'Tool lock off'),
zoom: (percent) => `Zoom ${percent}%`,
removed: (count) =>
count === 1 ? 'Shape deleted' : `${count} shapes deleted`,
};
function BoardShapeMenu({ pressed }: { pressed: boolean }) {
const geo = useBoardView((view) => view.nextStyle.geo ?? 'rectangle');
const { setStyle, setTool } = useBoardActions();
const icon = GEOS.find((item) => item.geo === geo)?.icon ?? GEOS[0].icon;
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger>
<ToolbarButton isDropdown pressed={pressed} tooltip="Shape (R)">
{icon}
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent side="top">
<DropdownMenuRadioGroup
value={geo}
onValueChange={(value) => {
const picked = GEOS.find((item) => item.geo === value);
if (!picked) return;
setTool('geo');
setStyle({ geo: picked.geo });
}}
>
{GEOS.map(({ geo: itemGeo, icon: itemIcon, label }) => (
<DropdownMenuRadioItem key={itemGeo} value={itemGeo}>
{itemIcon}
{label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
function BoardPictureButton() {
const takesPictureFiles = useBoardView((view) => view.takesPictureFiles);
const { upload } = useBoardActions();
const { openFilePicker } = useFilePicker({
accept: ['image/*'],
multiple: true,
readFilesContent: false,
onFilesSelected: ({ plainFiles }) => upload(plainFiles),
});
return (
<ToolbarButton
className="px-1.5"
disabled={!takesPictureFiles}
tooltip="Image"
onClick={() => openFilePicker()}
>
<ImageIcon />
</ToolbarButton>
);
}
const PICTURE_WARNINGS: Readonly<Record<BoardPictureWarning['code'], string>> =
{
'content-undrawn': 'Some content could not be drawn.',
downscaled: 'The PNG was made smaller to fit the size limit.',
'font-missing': 'A font could not be read, so its text uses another font.',
'image-unreadable':
'Some images could not be read, so they show as gray boxes or links.',
'shape-undrawn': 'Some shapes could not be drawn and show as gray boxes.',
};
const downloadBlob = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
};
const loadPictureKit = () =>
import('@/components/editor/board-static').then(
({ BoardPictureKit }) => BoardPictureKit
);
const warnAbout = ({ warnings }: BoardPicture) => {
if (warnings.length === 0) return;
toast.warning(
[...new Set(warnings.map(({ code }) => PICTURE_WARNINGS[code]))].join(' ')
);
};
function BoardExportMenu() {
const { exportPicture } = useBoardActions();
const mounted = React.useRef(false);
React.useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const save = async (format: 'png' | 'svg') => {
try {
const picture = await exportPicture({ format, kit: loadPictureKit() });
if (!picture) {
toast('There is nothing to export.');
return;
}
downloadBlob(picture.blob, `board.${format}`);
warnAbout(picture);
} catch (error) {
if (!mounted.current) return;
console.error('Could not export the board.', error);
toast.error('The board could not be exported.');
}
};
const copy = async (format: 'png' | 'svg') => {
// Firefox and Safari cannot copy image/svg+xml, so the SVG goes as text.
const type = format === 'png' ? 'image/png' : 'text/plain';
const empty = new Error('There is nothing to copy.');
const drawing = exportPicture({ format, kit: loadPictureKit() }).then(
(picture) => picture ?? Promise.reject(empty)
);
try {
// Safari and Firefox take a clipboard write only within the click's user
// activation, so the write starts now with the picture still drawing.
const [picture] = await Promise.all([
drawing,
navigator.clipboard.write([
new ClipboardItem({
[type]: drawing.then(({ blob }) => new Blob([blob], { type })),
}),
]),
]);
toast.success(
`Copied the board as ${format === 'png' ? 'a PNG' : 'an SVG'}.`
);
warnAbout(picture);
} catch (error) {
if (error === empty) {
toast(empty.message);
return;
}
if (!mounted.current) return;
console.error('Could not copy the board.', error);
toast.error('The board could not be copied.');
}
};
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger>
<ToolbarButton isDropdown tooltip="Export">
<ArrowDownToLineIcon />
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent side="top">
<DropdownMenuItem onSelect={() => save('png')}>
Export as PNG
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => save('svg')}>
Export as SVG
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => copy('png')}>
Copy as PNG
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => copy('svg')}>
Copy as SVG
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
function BoardToolLock() {
const locked = useBoardView((view) => view.toolLocked);
const { setToolLocked } = useBoardActions();
return (
<ToolbarButton
className="px-1.5"
pressed={locked}
tooltip="Keep the tool after drawing (Q)"
onClick={() => setToolLocked(!locked)}
>
{locked ? <LockIcon /> : <LockOpenIcon />}
</ToolbarButton>
);
}
function BoardZoomLevel() {
const percent = useBoardView((view) => Math.round(view.camera.zoom * 100));
const { resetZoom } = useBoardActions();
return (
<ToolbarButton
className="w-10 px-0"
aria-label={`Zoom ${percent}%, reset to 100%`}
tooltip="Reset to 100% (Shift+0)"
onClick={resetZoom}
>
<span className="text-xs tabular-nums">{percent}%</span>
</ToolbarButton>
);
}
function BoardToolbarGroup({ children }: { children: React.ReactNode }) {
return (
<ToolbarGroup>
<div className="flex flex-wrap items-center justify-center gap-y-0.5">
{children}
</div>
</ToolbarGroup>
);
}
export function BoardToolbar() {
const tool = useBoardView((view) => view.tool);
const frame = useBoardView((view) => {
const [only, ...rest] = view.selectedShapes;
return view.writable && only?.kind === 'frame' && rest.length === 0
? only.id
: null;
});
const { fit, removeFrame, setTool, zoomIn, zoomOut } = useBoardActions();
return (
<Toolbar className="absolute inset-x-0 bottom-2 z-10 mx-auto w-max max-w-[calc(100%-1rem)] flex-wrap justify-center gap-y-0.5 rounded-lg border bg-background p-1 shadow-sm">
<BoardToolbarGroup>
{TOOLS.map(({ icon, key, label, tool: itemTool }) =>
itemTool === 'geo' ? (
<BoardShapeMenu key={itemTool} pressed={tool === 'geo'} />
) : (
<ToolbarButton
key={itemTool}
className="px-1.5"
pressed={tool === itemTool}
tooltip={`${label} (${key})`}
onClick={() => setTool(itemTool)}
>
{icon}
</ToolbarButton>
)
)}
<BoardToolLock />
<BoardPictureButton />
<BoardExportMenu />
</BoardToolbarGroup>
<BoardToolbarGroup>
<ToolbarButton
className="px-1.5"
tooltip="Zoom out (-)"
onClick={zoomOut}
>
<ZoomOutIcon />
</ToolbarButton>
<BoardZoomLevel />
<ToolbarButton
className="px-1.5"
tooltip="Zoom in (+)"
onClick={zoomIn}
>
<ZoomInIcon />
</ToolbarButton>
<ToolbarButton
className="px-1.5"
tooltip="Fit every shape in view"
onClick={fit}
>
<ScanIcon />
</ToolbarButton>
{frame && (
<ToolbarButton
className="px-1.5"
tooltip="Remove the frame and keep its shapes"
onClick={() => removeFrame(frame)}
>
<UngroupIcon />
</ToolbarButton>
)}
</BoardToolbarGroup>
</Toolbar>
);
}
const ROW_KEYS: Readonly<Record<string, number>> = {
ArrowDown: 1,
ArrowLeft: -1,
ArrowRight: 1,
ArrowUp: -1,
};
function BoardStyleOptions<TValue extends string>({
label,
options,
shown,
onPick,
}: {
label: string;
options: ReadonlyArray<BoardStyleOption<TValue>>;
shown: Readonly<{ mixed: false; value: TValue } | { mixed: true }>;
onPick: (value: TValue) => void;
}) {
const value = shown.mixed ? undefined : shown.value;
const [focused, setFocused] = React.useState<number | null>(null);
const stop =
focused ??
Math.max(
0,
options.findIndex((option) => option.value === value)
);
return (
<div aria-label={label} className="grid grid-cols-4 gap-1" role="group">
{options.map((option, index) => (
<button
key={option.value}
className="flex size-7 items-center justify-center rounded-md outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-pressed:bg-accent [&_svg]:size-4"
aria-label={option.label}
aria-pressed={option.value === value}
tabIndex={index === stop ? 0 : -1}
title={option.label}
type="button"
onBlur={(event) => {
if (
!event.currentTarget.parentElement?.contains(event.relatedTarget)
) {
setFocused(null);
}
}}
onClick={() => onPick(option.value)}
onFocus={() => setFocused(index)}
onKeyDown={(event) => {
const step = ROW_KEYS[event.key];
if (!step) return;
event.preventDefault();
const row =
event.currentTarget.parentElement?.querySelectorAll('button');
row?.[(index + step + options.length) % options.length]?.focus();
}}
>
{option.icon}
</button>
))}
</div>
);
}
/**
* Styles the selected shapes, or the next shape while a drawing tool is
* active, with a row for each style they take other than opacity. On a board
* narrower than 36rem it folds behind a Styles button.
*/
export function BoardStylePanel({
className,
...props
}: React.ComponentProps<'div'>) {
const styles = useBoardView((view) => view.styles);
const writable = useBoardView((view) => view.writable);
const { setStyle } = useBoardActions();
const [open, setOpen] = React.useState(false);
const panel = React.useRef<HTMLDivElement>(null);
if (!writable || Object.keys(styles).length === 0) return null;
return (
// oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- [P1 local-invariant] A press anywhere on the panel keeps focus where it is, so a shape being edited keeps its caret, and the narrow-board panel closes when focus leaves the button and the panel together.
<div
{...props}
className={cn(
'absolute top-2 end-2 z-10 flex max-h-[calc(100%-5.5rem)] flex-col items-end gap-1',
className
)}
aria-label="Styles"
data-board-dock="right"
data-editor-root-chrome-ignore="true"
role="group"
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
}}
onMouseDown={(event) => event.preventDefault()}
>
<button
className="flex size-8 items-center justify-center rounded-lg border bg-background shadow-sm outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-expanded:bg-accent @min-[36rem]:hidden [&_svg]:size-4"
aria-expanded={open}
aria-label="Styles"
title="Styles"
type="button"
onClick={(event) => {
const button = event.currentTarget;
flushSync(() => setOpen(!open));
(open
? button
: panel.current?.querySelector<HTMLElement>('[tabindex="0"]')
)?.focus();
}}
onKeyDown={(event) => {
if (event.key === 'Escape') setOpen(false);
}}
>
<PaletteIcon />
</button>
<div
className={cn(
open ? 'flex' : 'hidden',
'min-h-0 w-36 flex-col gap-2 overflow-y-auto overscroll-contain rounded-lg border bg-background p-2 shadow-sm @min-[36rem]:flex'
)}
ref={panel}
>
{styles.geo && (
<BoardStyleOptions
label="Shape"
options={GEO_OPTIONS}
shown={styles.geo}
onPick={(geo) => setStyle({ geo })}
/>
)}
{styles.fill && (
<BoardStyleOptions
label="Fill"
options={FILL_OPTIONS}
shown={styles.fill}
onPick={(fill) => setStyle({ fill })}
/>
)}
{styles.strokeColor && (
<BoardStyleOptions
label="Outline"
options={OUTLINE_OPTIONS}
shown={styles.strokeColor}
onPick={(strokeColor) => setStyle({ strokeColor })}
/>
)}
{styles.dash && (
<BoardStyleOptions
label="Line"
options={DASH_OPTIONS}
shown={styles.dash}
onPick={(dash) => setStyle({ dash })}
/>
)}
{styles.strokeWidth && (
<BoardStyleOptions
label="Width"
options={WIDTH_OPTIONS}
shown={styles.strokeWidth}
onPick={(strokeWidth) => setStyle({ strokeWidth })}
/>
)}
{styles.textSize && (
<BoardStyleOptions
label="Text size"
options={TEXT_OPTIONS}
shown={styles.textSize}
onPick={(textSize) => setStyle({ textSize })}
/>
)}
</div>
</div>
);
}
const BOARD_FOCUS_RING =
'has-[[data-board-focus]:focus-visible]:not-has-[[data-board-shape][data-selected]]:ring-[3px] has-[[data-board-focus]:focus-visible]:not-has-[[data-board-shape][data-selected]]:ring-ring/50';
const BOARD_ERASING = '[&_[data-board-shape][data-erasing]]:opacity-30';
const CURSOR_RING =
'data-board-cursor:after:pointer-events-none data-board-cursor:after:absolute data-board-cursor:after:-inset-1.5 data-board-cursor:after:rounded-md data-board-cursor:after:outline-2 data-board-cursor:after:outline-ring data-board-cursor:after:outline-dashed';
const BOARD_GRID =
'bg-muted/40 bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-size-[16px_16px]';
const boardToolbar = (
<>
<BoardToolbar />
<BoardStylePanel />
</>
);
export function BoardElement(props: EditorElementProps<typeof BoardPlugin>) {
return (
<BoardSurface
{...props}
attributes={{
...props.attributes,
className: cn(
'@container my-4 rounded-lg border data-selected:ring-2 data-selected:ring-ring',
BOARD_COLORS,
BOARD_ERASING,
BOARD_FOCUS_RING,
BOARD_GRID
),
}}
messages={boardMessages}
toolbar={boardToolbar}
/>
);
}
export function BoardPageElement(
props: EditorElementProps<typeof BoardPlugin>
) {
return (
<BoardSurface
{...props}
attributes={{
...props.attributes,
className: cn(
'@container ring-inset data-selected:ring-2 data-selected:ring-ring',
BOARD_COLORS,
BOARD_ERASING,
BOARD_FOCUS_RING,
BOARD_GRID
),
}}
height="100%"
messages={boardMessages}
toolbar={boardToolbar}
/>
);
}
export function BoardNoteElement(
props: EditorElementProps<typeof BoardNotePlugin>
) {
const { element } = props;
return (
<BoardShape
{...props}
className={cn(
CURSOR_RING,
'rounded-sm p-3 leading-snug data-selected:outline-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
)}
style={{ fontSize: TEXT_SIZES[element.textSize] }}
>
<div
className="absolute inset-0 rounded-sm shadow-md"
contentEditable={false}
data-board-note-paper=""
style={{
backgroundColor:
element.fill === 'none' ? 'var(--background)' : tint(element.fill),
opacity: element.opacity,
}}
/>
<div
className={cn('relative', SHAPE_HEADINGS)}
style={{ opacity: element.opacity }}
>
{props.children}
</div>
</BoardShape>
);
}
export function BoardGeoElement(
props: EditorElementProps<typeof BoardGeoPlugin>
) {
const { element } = props;
const width = STROKE_WIDTHS[element.strokeWidth];
return (
<BoardShape
{...props}
className={cn(
CURSOR_RING,
'flex flex-col justify-center p-3 text-center leading-snug data-selected:outline-2 data-selected:outline-offset-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-offset-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
)}
style={{ fontSize: TEXT_SIZES[element.textSize] }}
>
<div
className="absolute inset-0"
contentEditable={false}
style={{ opacity: element.opacity }}
>
<svg
aria-hidden
className="pointer-events-none size-full overflow-visible"
data-board-geo-outline={element.geo}
preserveAspectRatio="none"
strokeDasharray={dashArray(element.dash, width)}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={width}
style={{
fill: element.fill === 'none' ? 'none' : tint(element.fill),
stroke: paint(element.strokeColor),
}}
viewBox="0 0 100 100"
>
{geoOutline(element.geo, {
height: 100,
vectorEffect: 'non-scaling-stroke',
width: 100,
})}
</svg>
</div>
<div
className={cn('relative', SHAPE_HEADINGS)}
style={{ opacity: element.opacity }}
>
{props.children}
</div>
</BoardShape>
);
}
export function BoardFrameElement(
props: EditorElementProps<typeof BoardFramePlugin>
) {
return (
<BoardShape
{...props}
className={cn(
CURSOR_RING,
'rounded-sm border-2 border-foreground/50 data-selected:border-ring data-[editor-authored-change]:border-dashed data-[editor-authored-change]:border-emerald-600'
)}
>
<div
className="absolute bottom-full [left:0] max-w-full cursor-default truncate pb-1 text-xs text-muted-foreground select-none"
contentEditable={false}
data-board-frame-name=""
>
{props.element.name || 'Frame'}
</div>
{props.children}
</BoardShape>
);
}
// A suggested arrow or pen line keeps the suggestion's color over its own.
const SUGGESTED_INK =
'data-[editor-authored-change]:text-emerald-600 [&[data-editor-authored-change]_[data-board-ink]]:text-emerald-600!';
export function BoardArrowElement(
props: EditorElementProps<typeof BoardArrowPlugin>
) {
const { element } = props;
const width = STROKE_WIDTHS[element.strokeWidth];
const hitWidth = Math.max(14, width + 10);
return (
<BoardShape
{...props}
className={cn(
'text-foreground [&[data-board-cursor]_[data-board-arrow-halo]]:inline [&[data-selected]_[data-board-arrow-halo]]:inline',
SUGGESTED_INK
)}
style={{ fontSize: TEXT_SIZES[element.textSize] }}
>
<div className="absolute top-0 [left:0]" contentEditable={false}>
<svg
aria-hidden
className="pointer-events-none overflow-visible"
height={1}
width={1}
>
<BoardArrowPath
pointerEvents="stroke"
stroke="transparent"
strokeWidth={hitWidth}
/>
<BoardArrowPath
className="hidden stroke-ring/50"
data-board-arrow-halo=""
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={width + 8}
/>
<g
data-board-ink=""
opacity={element.opacity}
style={{ color: paint(element.strokeColor) }}
>
<BoardArrowPath
data-board-arrow-path=""
fill="none"
stroke="currentColor"
strokeDasharray={dashArray(element.dash, width)}
strokeLinecap="round"
strokeWidth={width}
/>
<BoardArrowhead>
<polygon fill="currentColor" points={ARROW_HEAD} />
</BoardArrowhead>
</g>
</svg>
</div>
<BoardArrowLabel
className="min-w-4 rounded-sm px-1 text-center leading-snug whitespace-nowrap has-[[data-editor-string]]:bg-background"
style={{ opacity: element.opacity }}
>
{props.children}
</BoardArrowLabel>
</BoardShape>
);
}
export function BoardStrokeElement(
props: EditorElementProps<typeof BoardStrokePlugin>
) {
const { element } = props;
const drawn = useStrokePath(element);
return (
<BoardShape
{...props}
className={cn(
CURSOR_RING,
SUGGESTED_INK,
'text-foreground data-selected:outline-1 data-selected:outline-ring data-selected:outline-dashed'
)}
>
{drawn && (
<div
className="absolute inset-0"
contentEditable={false}
data-board-ink=""
style={{
color: paint(element.strokeColor),
opacity: element.opacity,
}}
>
<svg
aria-hidden
className="pointer-events-none size-full overflow-visible"
preserveAspectRatio="none"
viewBox={`0 0 ${drawn.width} ${drawn.height}`}
>
<path
d={drawn.path}
data-board-stroke-path=""
fill="currentColor"
/>
</svg>
</div>
)}
{props.children}
</BoardShape>
);
}
export function BoardImageElement(
props: EditorElementProps<typeof BoardImagePlugin>
) {
const { element, slots } = props;
const editor = useEditor();
const path = usePath();
const image = editor.plugin(ImagePlugin);
const [stored] = element.children;
const childKey = stored ? editor.key(stored) : undefined;
const child = useEditorSelector(
(current) => current.read.nodes.get([...path, 0])?.[0],
{
shouldUpdate: (change) =>
!change ||
(!!childKey &&
change.changed.hasNodeKey(childKey, 'node', editor.read.view.root())),
}
);
const picture =
image.installed &&
ElementApi.isElement(child) &&
child.type === image.schema.type
? (child as ImageElement)
: undefined;
return (
<BoardShape
{...props}
className={cn(
CURSOR_RING,
'data-selected:outline-2 data-selected:outline-ring data-[editor-authored-change]:outline-2 data-[editor-authored-change]:outline-emerald-600 data-[editor-authored-change]:outline-dashed'
)}
>
{picture
? slots.contentBoundary({
children: (
// oxlint-disable-next-line nextjs/no-img-element -- [P1 local-invariant] The shape draws the document-owned runtime URL across its box, outside any Next loader.
<img
alt={picture.alt}
className="absolute inset-0 size-full object-contain select-none"
decoding="async"
draggable={false}
src={picture.url}
/>
),
copyPolicy: 'model',
mounted: false,
reason: 'app-hidden',
scope: { from: 0, type: 'children' },
selectionPolicy: 'skip',
})
: props.children}
</BoardShape>
);
}
const BoardShapeKit = [
BoardNotePlugin.configure({ component: BoardNoteElement }),
BoardGeoPlugin.configure({ component: BoardGeoElement }),
BoardArrowPlugin.configure({ component: BoardArrowElement }),
BoardFramePlugin.configure({ component: BoardFrameElement }),
BoardStrokePlugin.configure({ component: BoardStrokeElement }),
];
export const BoardKit = [
BoardPlugin.configure({ component: BoardElement }),
...BoardShapeKit,
];
export const BoardPageKit = [
BoardPlugin.configure({ component: BoardPageElement }),
...BoardShapeKit,
];
export const BoardImageKit = [
BoardImagePlugin.configure({ component: BoardImageElement }),
];
Export
  • BoardStylePanel: docks at the board's top right and styles the selected shapes, or the next shape while a drawing tool is picked, as Style panel shows.
  • =
    createEditor
    ({
    plugins: [
    // ...otherPlugins,
    ...BoardKit,
    ],
    });
    ),
    }}
    messages={boardMessages}
    toolbar={boardToolbar}
    />
    );
    }
    SIZES
    .
    map
    ((
    size
    )
    =>
    (
    <button
    key={size}
    aria-pressed={!textSize.mixed && textSize.value === size}
    type="button"
    onClick={() => setStyle({ textSize: size })}
    onMouseDown={(event) => event.preventDefault()}
    >
    {size.toUpperCase()}
    </button>
    ))}
    </div>
    );
    }
    })
    =>
    blob) }),
    ]),
    ]);
    BoardArrowPlugin.configure({ component: BoardArrowElement }),
    BoardFramePlugin.configure({ component: BoardFrameElement }),
    BoardStrokePlugin.configure({ component: BoardStrokeElement }),
    ],
    });
    BoardGeoPlugin.configure({ component: BoardGeoElement }),
    BoardArrowPlugin.configure({ component: BoardArrowElement }),
    BoardFramePlugin.configure({ component: BoardFrameElement }),
    BoardStrokePlugin.configure({ component: BoardStrokeElement }),
    ],
    });
    anchor
    .
    down
    ===
    50
    ?
    ''
    :
    `, ${
    anchor
    .
    across
    }% across, ${
    anchor
    .
    down
    }% down`}. ${
    position
    } of ${
    total
    }`
    ,
    connecting: (from) =>
    `Connecting ${from ? nameOf(from) : 'a free point'}. Tab picks a shape, arrow keys move the end, Enter draws the arrow and Escape stops.`,
    free: ({ x, y }, { side }) =>
    `${side === 'start' ? 'Start' : 'End'} free at ${x}, ${y}`,
    starting: ({ x, y }, { from }) =>
    `Drawing an arrow from ${from ? nameOf(from) : `${x}, ${y}`}. Arrow keys move its start, Tab picks a shape, Enter keeps the start and Escape stops.`,
    resizing: (shape, { corner, height, width }) =>
    `Resizing ${nameOf(shape)} from its ${CORNERS[corner]} corner, ${width} by ${height}. Tab picks a corner, arrow keys resize, Enter keeps it and Escape stops.`,
    resize: ({ corner, height, width }) =>
    `${CORNERS[corner]}, ${width} by ${height}`,
    picking: (shape, state) =>
    `Picking shapes. ${pickOf(shape, state)}. Tab moves, Space adds or removes, Enter finishes.`,
    pick: (shape, state) => pickOf(shape, state),
    shape: (shape, { position, total }) =>
    `${nameOf(shape)}. ${position} of ${total}`,
    shapes: (count) =>
    count === 0 ? 'No shapes selected' : `${count} shapes selected`,
    tool: (tool) => TOOL_NAMES[tool],
    toolLock: (locked) => (locked ? 'Tool lock on' : 'Tool lock off'),
    zoom: (percent) => `Zoom ${percent}%`,
    removed: (count) =>
    count === 1 ? 'Shape deleted' : `${count} shapes deleted`,
    };
    y:
    80
    ,
    },
    { board }
    );
    const rect = tx
    .plugin(BaseBoardGeoPlugin)
    .insert({ geo: 'rectangle', x: 480, y: 80 }, { board });
    if (note && rect) {
    tx.plugin(BaseBoardArrowPlugin).insert({ end: rect, start: note });
    }
    });
    ({
    targetPlugins: [BaseBoardNotePlugin, BaseBoardGeoPlugin, BaseCardPlugin],
    }),
    BaseBoardNotePlugin,
    BaseBoardGeoPlugin,
    BaseCardPlugin,
    ];
    ],
    },
    };
    3
    : v3Fingerprint },
    steps: { 4: ({ document }) => ({ document }) },
    });
    value
    (),
    schema: oldEditor.read.schema.identity(),
    },
    { migrations: EditorMigrations }
    ).output;
    import { createEditor } from 'platejs/react'; import { YjsPlugin } from 'platejs/yjs/react'; const editor = createEditor({ initialValue: current, plugins: [ ...EditorPlugins, YjsPlugin.create({ doc: newRoomDocument, initialReady: true, rootName: newRoomId, seed: true, }), ], schema: EditorSchema, });
    zoomIn
    zoomOut
    resetZoom
    removeFrame
    focus
    upload
    exportPicture
    zoomIn
    zoomOut
    =
    +
    -
    resetZoom
    toolLocked
    setToolLocked
    focus
    setStyle
    styles
    { mixed: false, value }
    { mixed: true }
    setStyle
    upload(files)
    Picture files
    takesPictureFiles
    exportPicture({ format, kit })
    'png'
    'svg'
    kit
    kit
    Export
    null
    BoardSurface
    style
    position
    translate
    BoardShape
    d
    svg
    svg
    svg
    pointer-events: none
    contentEditable={false}
    pointerEvents="stroke"
    BoardArrowPath
    d
    BoardShape