The fastest way to add toolbar functionality is with the FixedToolbarKit and FloatingToolbarKit, which include pre-configured toolbar plugins along with their Plate UI components.
'use client';
import { cn } from 'cn';
import {
BaselineIcon,
BoldIcon,
Code2Icon,
HighlighterIcon,
ItalicIcon,
PaintBucketIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import {
BaseAudioPlugin,
BaseFilePlugin,
BaseImagePlugin,
BaseVideoPlugin,
} from 'platejs/media';
import {
BoldPlugin,
CodePlugin,
HighlightPlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
FontBackgroundColorPlugin,
FontColorPlugin,
useEditor,
useEditorReadOnly,
useEditorViewState,
definePlugin,
} from 'platejs/react';
import * as React from 'react';
import { ToolbarGroup, Toolbar } from '@/components/editor/toolbar';
import { AIToolbarButton } from './ai-toolbar-button';
import { AlignToolbarButton } from './align-toolbar-button';
import { ClearFormattingToolbarButton } from './clear-formatting-toolbar-button';
import {
AllCommentsButton,
CommentToolbarButton,
} from './comment-toolbar-button';
import { DetailsToolbarButton } from './details-toolbar-button';
import { EmojiToolbarButton } from './emoji-toolbar-button';
import {
DEFAULT_COLORS,
FontColorToolbarButton,
} from './font-color-toolbar-button';
import { FontSizeToolbarButton } from './font-size-toolbar-button';
import { FormatPainterToolbarButton } from './format-painter-toolbar-button';
import { RedoToolbarButton, UndoToolbarButton } from './history-toolbar-button';
import {
IndentToolbarButton,
OutdentToolbarButton,
} from './indent-toolbar-button';
import { InsertToolbarButton } from './insert-toolbar-button';
import { LineHeightToolbarButton } from './line-height-toolbar-button';
import { LinkToolbarButton } from './link-toolbar-button';
import {
BulletedListToolbarButton,
NumberedListToolbarButton,
TodoListToolbarButton,
} from './list-toolbar-button';
import { MarkToolbarButton } from './mark-toolbar-button';
import { MediaToolbarButton } from './media-toolbar-button';
import { ModeToolbarButton } from './mode-toolbar-button';
import { MoreToolbarButton } from './more-toolbar-button';
import { TableToolbarButton } from './table-toolbar-button';
import { TurnIntoToolbarButton } from './turn-into-toolbar-button';
export function FixedToolbarButtons({
children,
}: {
children?: React.ReactNode;
} = {}) {
const editor = useEditor();
const viewing = useEditorViewState(editor, (view) => view.isViewing());
const readOnly = useEditorReadOnly();
return (
<div className="flex w-full">
{!viewing && (
<ToolbarGroup>
<UndoToolbarButton />
<RedoToolbarButton />
</ToolbarGroup>
)}
{!readOnly && (
<>
<ToolbarGroup>
<AIToolbarButton tooltip="AI commands">
<WandSparklesIcon />
</AIToolbarButton>
</ToolbarGroup>
{children}
<ToolbarGroup>
<InsertToolbarButton />
<TurnIntoToolbarButton />
<FontSizeToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={ItalicPlugin} tooltip="Italic">
<ItalicIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={UnderlinePlugin} tooltip="Underline">
<UnderlineIcon />
</MarkToolbarButton>
<MarkToolbarButton
plugin={StrikethroughPlugin}
tooltip="Strikethrough"
>
<StrikethroughIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={CodePlugin} tooltip="Code">
<Code2Icon />
</MarkToolbarButton>
<FontColorToolbarButton
colors={DEFAULT_COLORS}
plugin={FontColorPlugin}
tooltip="Text color"
>
<BaselineIcon />
</FontColorToolbarButton>
<FontColorToolbarButton
colors={DEFAULT_COLORS}
plugin={FontBackgroundColorPlugin}
tooltip="Background color"
>
<PaintBucketIcon />
</FontColorToolbarButton>
</ToolbarGroup>
<ToolbarGroup>
<AlignToolbarButton />
<ClearFormattingToolbarButton />
<FormatPainterToolbarButton />
<NumberedListToolbarButton />
<BulletedListToolbarButton />
<TodoListToolbarButton />
<DetailsToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<LinkToolbarButton />
<TableToolbarButton />
<EmojiToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MediaToolbarButton plugin={BaseImagePlugin} />
<MediaToolbarButton plugin={BaseVideoPlugin} />
<MediaToolbarButton plugin={BaseAudioPlugin} />
<MediaToolbarButton plugin={BaseFilePlugin} />
</ToolbarGroup>
<ToolbarGroup>
<LineHeightToolbarButton />
<OutdentToolbarButton />
<IndentToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MoreToolbarButton />
</ToolbarGroup>
</>
)}
<div className="grow" />
<ToolbarGroup>
<MarkToolbarButton plugin={HighlightPlugin} tooltip="Highlight">
<HighlighterIcon />
</MarkToolbarButton>
<CommentToolbarButton />
<AllCommentsButton />
</ToolbarGroup>
<ToolbarGroup>
<ModeToolbarButton />
</ToolbarGroup>
</div>
);
}
export function FixedToolbar({
className,
ref,
...props
}: React.ComponentProps<typeof Toolbar>) {
return (
<Toolbar
{...props}
ref={ref}
className={cn(
'scrollbar-hide z-50 w-full shrink-0 justify-between overflow-x-auto rounded-t-lg border-b border-b-border bg-background/95 p-1 backdrop-blur-sm supports-backdrop-blur:bg-background/60',
className
)}
data-slot="fixed-toolbar"
/>
);
}
export const FixedToolbarPlugin = definePlugin('fixedToolbar', {
slots: {
beforeContainer: () => (
<FixedToolbar>
<FixedToolbarButtons />
</FixedToolbar>
),
},
});
export const FixedToolbarKit = [FixedToolbarPlugin] as const;'use client';
import { cn } from 'cn';
import {
BaselineIcon,
BoldIcon,
Code2Icon,
HighlighterIcon,
ItalicIcon,
PaintBucketIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import {
BaseAudioPlugin,
BaseFilePlugin,
BaseImagePlugin,
BaseVideoPlugin,
} from 'platejs/media';
import {
BoldPlugin,
CodePlugin,
HighlightPlugin,
ItalicPlugin,
StrikethroughPlugin,
'use client';
import {
flip,
offset,
shift,
useDismiss,
useInteractions,
} from '@floating-ui/react';
import {
BoldIcon,
Code2Icon,
ItalicIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import { AIChatPlugin } from 'platejs/ai/react';
import {
BoldPlugin,
CodePlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
definePlugin,
useComposedRef,
FixedToolbar: Renders a persistent toolbar above the editorFixedToolbarButtons: Pre-configured button set for the fixed toolbarFloatingToolbar: Renders a contextual toolbar on text selectionFloatingToolbarButtons: Pre-configured button set for the floating toolbarimport { createEditor } from 'platejs/react';
import { FixedToolbarKit } from '@/components/editor/fixed-toolbar';
import { FloatingToolbarKit } from '@/components/editor/floating-toolbar';
const editor = createEditor({
plugins: [
// ...otherPlugins,
...FixedToolbarKit,
...FloatingToolbarKit,
],
});import { createEditor } from 'platejs/react'
import { definePlugin } from 'platejs/react';
import { FixedToolbar } from '@/components/editor/fixed-toolbar';
import { FixedToolbarButtons } from '@/components/editor/fixed-toolbar';
import { FloatingToolbar } from '@/components/editor/floating-toolbar';
const fixedToolbarPlugin = definePlugin('fixedToolbar', {
slots: {
beforeContainer: () => (
<FixedToolbar>
<FixedToolbarButtons />
</FixedToolbar>
),
},
});
const floatingToolbarPlugin = definePlugin('floatingToolbar', {
slots: {
caret: () => <FloatingToolbar />,
},
});
const editor = createEditor({
plugins: [
// ...otherPlugins,
fixedToolbarPlugin,
floatingToolbarPlugin,
],
});import { definePlugin } from 'platejs/react';
import { FixedToolbar } from '@/components/editor/fixed-toolbar';
import { FixedToolbarButtons } from '@/components/editor/fixed-toolbar';
import { FloatingToolbar } from '@/components/editor/floating-toolbar';
const fixedToolbarPlugin = definePlugin('fixedToolbar', {
slots: {
beforeContainer: () => (
<FixedToolbar>
<FixedToolbarButtons />
</FixedToolbar>
),
},
});
const floatingToolbarPlugin = definePlugin('floatingToolbar'
slots.beforeContainer: Renders FixedToolbar before the editor scroll containerslots.caret: Renders FloatingToolbar as an overlay after the editor, on the view that holds the caretPlace the editor container in an EditorFrame. The fixed toolbar and scroll
container then occupy separate rows inside the same bounded layout.
<EditorFrame className="h-[650px]">
<EditorContainer>
<Editor />
</EditorContainer>
</EditorFrame><EditorFrame className="h-[650px]">
<EditorContainer>
<Editor />
</EditorContainer>
</EditorFrame>The floating toolbar hides when its text scrolls out of view in the window or in a scroll area that clips the toolbar, and shows again when the text scrolls back. A scroll area that does not clip the toolbar does not hide it, such as a wide code block or a static scroll panel when the toolbar is positioned against an element outside the panel.
On a touch screen, the floating toolbar docks as a bar along the bottom of the
visible page, above the on-screen keyboard, and shows while the editor has
focus. A phone opens its own Copy and Paste menu above the selection, and a page
cannot move that menu, so a toolbar at the selection and that menu would cover
each other. When the bar would cover the caret, it scrolls the caret above itself. A
screen counts as touch when its primary pointer is coarse, as the
(pointer: coarse) media query reports; a mouse or trackpad screen keeps the
floating toolbar at any width.
The FixedToolbarButtons component contains the default set of buttons for the fixed toolbar.
'use client';
import { cn } from 'cn';
import {
BaselineIcon,
BoldIcon,
Code2Icon,
HighlighterIcon,
ItalicIcon,
PaintBucketIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import {
BaseAudioPlugin,
BaseFilePlugin,
BaseImagePlugin,
BaseVideoPlugin,
} from 'platejs/media';
import {
BoldPlugin,
CodePlugin,
HighlightPlugin,
ItalicPlugin,
StrikethroughPlugin,
To customize it, you can edit components/editor/fixed-toolbar.tsx.
Similarly, you can customize the floating toolbar by editing components/editor/floating-toolbar.tsx.
'use client';
import {
flip,
offset,
shift,
useDismiss,
useInteractions,
} from '@floating-ui/react';
import {
BoldIcon,
Code2Icon,
ItalicIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import { AIChatPlugin } from 'platejs/ai/react';
import {
BoldPlugin,
CodePlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
definePlugin,
useComposedRef,
A nested view, such as the text of a board note, is an Editable of its own inside the page's Editable. Where a toolbar renders decides the view it acts on:
beforeContainer where the fixed
toolbar renders, useEditor() returns the editor of the root that holds the
caret. With the caret in a note, the copied fixed toolbar's mark buttons
change the note.caret slot renders after the Editable and follows the caret into
the views mounted inside its editing area. The copied floating toolbar, link
toolbar and AI menu render there, so they open beside selected note text.afterEditable, keeps that
area's view.import { definePlugin } from 'platejs/react';
const FloatingToolbarPlugin = definePlugin('floatingToolbar', {
slots: { caret: () => <FloatingToolbar /> },
});import { definePlugin } from 'platejs/react';
const FloatingToolbarPlugin = definePlugin('floatingToolbar', {
slots: { caret: () => <FloatingToolbar /> },
});In the caret slot, useEditor(), useEditableRef(), useEditorFocused()
and useFocusedLast() answer for the view that holds the caret while that view
is mounted inside the slot's editing area, and for the slot's own view
otherwise. So a header EditorContent's floating toolbar stays on the header
while the caret is in the body.
This example shows a button that inserts custom text into the editor.
import { useEditor } from 'platejs/react';
import { CustomIcon } from 'lucide-react';
import { ToolbarButton } from '@/components/editor/toolbar';
export function CustomToolbarButton() {
const editor = useEditor();
return (
<ToolbarButton
onClick={() => {
// Custom action
editor.update((tx) => {
tx.text.insert('Custom text');
});
}}
tooltip="Custom Action"
For toggling marks like bold or italic, you can use the MarkToolbarButton component. It simplifies the process by handling the toggle state and action automatically.
This example creates a "Bold" button.
import { BoldIcon } from 'lucide-react';
import { BoldPlugin } from 'platejs/react';
import { MarkToolbarButton } from '@/components/editor/mark-toolbar-button';
export function BoldToolbarButton() {
return (
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
);
}plugin: Specifies the mark plugin to toggle (for example, BoldPlugin).tooltip: Provides a helpful tooltip for the button.MarkToolbarButton adds the plugin's own shortcut to the tooltip, such as
Bold (⌘B) on a Mac and Bold (Ctrl+B) elsewhere, and sets
aria-keyshortcuts from it. A rebound shortcut shows its new keys.MarkToolbarButton reads mark state and handles toggling directly in the component.The TurnIntoToolbarButton provides a dropdown menu for leaf formats and structural block actions.
'use client';
import {
ChevronRightIcon,
Columns3Icon,
FileCodeIcon,
Heading1Icon,
Heading2Icon,
Heading3Icon,
Heading4Icon,
Heading5Icon,
Heading6Icon,
ListIcon,
ListOrderedIcon,
PilcrowIcon,
QuoteIcon,
SquareIcon,
} from 'lucide-react';
import {
BaseBlockquotePlugin,
BaseCodeBlockPlugin,
BaseHeadingPlugin,
BaseListPlugin,
defineCommand,
ElementApi,
PathApi,
SelectionApi,
type Element,
Each item calls its feature directly. Keep mutually exclusive text, heading, and list formats in the radio group. Render wrappers and layouts as separate actions with their own selection checks.
const quote = editor.plugin(BaseBlockquotePlugin);
if (quote.installed) {
editor.update((tx) => {
tx.plugin(BaseBlockquotePlugin).toggle();
});
}const quote = editor.plugin(BaseBlockquotePlugin);
if (quote.installed) {
editor.update((tx) => {
tx.plugin
The InsertToolbarButton provides a dropdown menu to insert various elements (blocks, lists, media, inline elements).
'use client';
import {
CalendarIcon,
ChevronRightIcon,
Columns3Icon,
FileCodeIcon,
FilmIcon,
Heading1Icon,
Heading2Icon,
Heading3Icon,
ImageIcon,
Link2Icon,
ListIcon,
ListOrderedIcon,
MinusIcon,
PenToolIcon,
PilcrowIcon,
PlusIcon,
QuoteIcon,
RadicalIcon,
SquareIcon,
SuperscriptIcon,
TableIcon,
TableOfContentsIcon,
} from 'lucide-react';
import {
BaseBlockquotePlugin,
BaseCodeBlockPlugin,
To add an insertable item, define its typed operation in getGroups. The local value identifies the menu item; it does not dispatch the edit.
{
icon: <Heading2Icon />,
label: 'Heading 2',
value: 'heading-2',
onSelect: () => {
const heading = editor.plugin(BaseHeadingPlugin);
if (!heading.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
insertBlock(tx, {
matches: (block) =>
!block.listType &&
block.type === heading.schema.type &&
Plugin that renders a fixed toolbar before the editor scroll container.
Plugin that renders a floating toolbar that appears on text selection, or a bar above the keyboard on touch screens.
'use client';
import {
flip,
offset,
shift,
useDismiss,
useInteractions,
} from '@floating-ui/react';
import {
BoldIcon,
Code2Icon,
ItalicIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import { AIChatPlugin } from 'platejs/ai/react';
import {
BoldPlugin,
CodePlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
definePlugin,
useComposedRef,
useEditableRef,
useEditorFocused,
useEditorReadOnly,
useEditorSelector,
usePluginStore,
useSelectionGeometry,
} from 'platejs/react';
import * as React from 'react';
import { createPortal } from 'react-dom';
import { ToolbarGroup, Toolbar } from '@/components/editor/toolbar';
import { useFloatingRect } from '@/hooks/use-floating-rect';
import { AIToolbarButton } from './ai-toolbar-button';
import { CommentToolbarButton } from './comment-toolbar-button';
import { InlineEquationToolbarButton } from './equation-toolbar-button';
import { linkPlugin } from './link';
import { LinkToolbarButton } from './link-toolbar-button';
import { MarkToolbarButton } from './mark-toolbar-button';
import { MoreToolbarButton } from './more-toolbar-button';
import { SuggestionToolbarButton } from './suggestion-toolbar-button';
import { TurnIntoToolbarButton } from './turn-into-toolbar-button';
export function FloatingToolbarButtons() {
const readOnly = useEditorReadOnly();
return (
<>
{!readOnly && (
<ToolbarGroup>
<AIToolbarButton tooltip="AI commands">
<WandSparklesIcon />
Ask AI
</AIToolbarButton>
</ToolbarGroup>
)}
{!readOnly && (
<ToolbarGroup>
<TurnIntoToolbarButton />
<StyleButtons />
<InlineEquationToolbarButton />
<LinkToolbarButton />
</ToolbarGroup>
)}
<ToolbarGroup>
<CommentToolbarButton />
<SuggestionToolbarButton />
{!readOnly && <MoreToolbarButton />}
</ToolbarGroup>
</>
);
}
function StyleButtons() {
return (
<>
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={ItalicPlugin} tooltip="Italic">
<ItalicIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={UnderlinePlugin} tooltip="Underline">
<UnderlineIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={StrikethroughPlugin} tooltip="Strikethrough">
<StrikethroughIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={CodePlugin} tooltip="Code">
<Code2Icon />
</MarkToolbarButton>
</>
);
}
export function FloatingToolbar({ children }: { children?: React.ReactNode }) {
const hasNodeSelection = useEditorSelector(
(editor) => editor.read.selection.nodes().length > 0
);
const touch = useCoarsePointer();
if (hasNodeSelection) return null;
const buttons =
children === undefined ? <FloatingToolbarButtons /> : children;
return touch ? (
<KeyboardToolbar>{buttons}</KeyboardToolbar>
) : (
<TextFloatingToolbar>{buttons}</TextFloatingToolbar>
);
}
const COARSE_POINTER_QUERY = '(pointer: coarse)';
const CARET_GAP = 8;
function subscribeCoarsePointer(onChange: () => void) {
const query = window.matchMedia(COARSE_POINTER_QUERY);
query.addEventListener('change', onChange);
return () => query.removeEventListener('change', onChange);
}
function useCoarsePointer() {
return React.useSyncExternalStore(
subscribeCoarsePointer,
() => window.matchMedia(COARSE_POINTER_QUERY).matches,
() => false
);
}
function subscribeViewport(onChange: () => void) {
const viewport = window.visualViewport;
const resized = viewport ?? window;
resized.addEventListener('resize', onChange);
viewport?.addEventListener('scroll', onChange);
return () => {
resized.removeEventListener('resize', onChange);
viewport?.removeEventListener('scroll', onChange);
};
}
function readViewportBottom() {
const viewport = window.visualViewport;
return viewport ? viewport.offsetTop + viewport.height : window.innerHeight;
}
// A page cannot move the phone's own selection menu, which opens above the selection, and iOS gives it no way to hide it, so touch screens dock the toolbar above the keyboard.
function KeyboardToolbar({ children }: { children: React.ReactNode }) {
const editableRef = useEditableRef();
const editorFocused = useEditorFocused();
const readOnly = useEditorReadOnly();
const isFloatingLinkOpen = !!usePluginStore(linkPlugin, 'mode');
const isAIChatOpen = usePluginStore(AIChatPlugin, 'open');
const [ownedOverlayOpen, setOwnedOverlayOpen] = React.useState(false);
const viewportBottom = React.useSyncExternalStore(
subscribeViewport,
readViewportBottom,
() => 0
);
const barRef = React.useRef<HTMLDivElement>(null);
const open =
!isFloatingLinkOpen &&
!isAIChatOpen &&
!readOnly &&
(editorFocused || ownedOverlayOpen);
React.useEffect(() => {
const document = editableRef.current?.ownerDocument;
const view = document?.defaultView;
if (!open || !document || !view) return undefined;
let frame = 0;
const revealCaret = () => {
view.cancelAnimationFrame(frame);
frame = view.requestAnimationFrame(() => {
const selection = document.getSelection();
const node = selection?.focusNode;
const element = node instanceof Element ? node : node?.parentElement;
const bar = barRef.current;
if (
!bar ||
!selection?.isCollapsed ||
!element ||
!editableRef.current?.contains(element)
) {
return;
}
const caret = selection.getRangeAt(0).getClientRects()[0];
let overlap =
(caret ?? element.getBoundingClientRect()).bottom +
CARET_GAP -
bar.getBoundingClientRect().top;
for (
let parent = element.parentElement;
parent && overlap > 0;
parent = parent.parentElement
) {
if (!/auto|scroll/.test(view.getComputedStyle(parent).overflowY)) {
continue;
}
const before = parent.scrollTop;
parent.scrollTop += overlap;
overlap -= parent.scrollTop - before;
}
if (overlap > 0) view.scrollBy(0, overlap);
});
};
document.addEventListener('selectionchange', revealCaret);
view.visualViewport?.addEventListener('resize', revealCaret);
revealCaret();
return () => {
view.cancelAnimationFrame(frame);
document.removeEventListener('selectionchange', revealCaret);
view.visualViewport?.removeEventListener('resize', revealCaret);
};
}, [editableRef, open]);
if (!open) return null;
return createPortal(
<Toolbar
ref={barRef}
data-slot="keyboard-toolbar"
onOverlayOpenChange={setOwnedOverlayOpen}
style={{ top: viewportBottom }}
className="fixed inset-x-0 z-50 scrollbar-hide -translate-y-full overflow-x-auto border-t bg-popover p-1 whitespace-nowrap print:hidden"
>
{children}
</Toolbar>,
document.body
);
}
function TextFloatingToolbar({ children }: { children: React.ReactNode }) {
const editableRef = useEditableRef();
const editorFocused = useEditorFocused();
const isFloatingLinkOpen = !!usePluginStore(linkPlugin, 'mode');
const isAIChatOpen = usePluginStore(AIChatPlugin, 'open');
const [selectionRange, setSelectionRange] = React.useState<Range | null>(
null
);
const readOnly = useEditorReadOnly();
const [dismissedSelection, setDismissedSelection] =
React.useState<typeof selectionRange>(null);
const [mouseDownOpen, setMouseDownOpen] = React.useState<boolean | null>(
null
);
const [ownedOverlayOpen, setOwnedOverlayOpen] = React.useState(false);
// WebKit clears the DOM selection when an owned overlay takes focus, so the overlay alone holds the toolbar.
const open =
!isFloatingLinkOpen &&
!isAIChatOpen &&
!readOnly &&
mouseDownOpen !== false &&
(ownedOverlayOpen ||
(selectionRange !== null &&
editorFocused &&
dismissedSelection !== selectionRange));
const openStateRef = React.useRef(open);
React.useEffect(() => {
openStateRef.current = open;
}, [open]);
React.useEffect(() => {
const document = editableRef.current?.ownerDocument;
if (!document) return undefined;
const readSelection = () => {
const editable = editableRef.current;
const root = editable?.getRootNode() as Document | ShadowRoot | undefined;
const selection =
root && 'getSelection' in root
? root.getSelection()
: document.getSelection();
const range = selection?.rangeCount ? selection.getRangeAt(0) : null;
const next =
range &&
!range.collapsed &&
selection?.toString() &&
editable?.contains(range.startContainer) &&
editable.contains(range.endContainer)
? range
: null;
setSelectionRange((previous) => {
if (!next) return null;
if (
previous &&
previous.startContainer === next.startContainer &&
previous.startOffset === next.startOffset &&
previous.endContainer === next.endContainer &&
previous.endOffset === next.endOffset
) {
return previous;
}
return next.cloneRange();
});
};
const onMouseUp = () => {
readSelection();
setMouseDownOpen(null);
};
const onMouseDown = () => {
setMouseDownOpen(openStateRef.current);
};
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('mousedown', onMouseDown);
document.addEventListener('selectionchange', readSelection);
readSelection();
return () => {
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('selectionchange', readSelection);
};
}, [editableRef]);
if (!open) return null;
return (
<PositionedFloatingToolbar
onOpenChange={(nextOpen) => {
setDismissedSelection(nextOpen ? null : selectionRange);
}}
onOverlayOpenChange={setOwnedOverlayOpen}
>
{children}
</PositionedFloatingToolbar>
);
}
function PositionedFloatingToolbar({
children,
onOpenChange,
onOverlayOpenChange,
}: {
children: React.ReactNode;
onOpenChange: (open: boolean) => void;
onOverlayOpenChange: (open: boolean) => void;
}) {
const editableRef = useEditableRef();
const geometry = useSelectionGeometry({ editableRef });
const floating = useFloatingRect(geometry, {
open: true,
middleware: [
offset(12),
flip({
fallbackPlacements: [
'top-start',
'top-end',
'bottom-start',
'bottom-end',
],
padding: 12,
}),
shift({ padding: 8 }),
],
placement: 'top',
onOpenChange,
});
const dismiss = useDismiss(floating.context, {
escapeKey: false,
outsidePress: (event) => {
const Element =
floating.elements.floating?.ownerDocument.defaultView?.Element;
return (
!Element ||
!(event.target instanceof Element) ||
!event.target.closest('[class~="ignore-click-outside/toolbar"]')
);
},
});
const { getFloatingProps } = useInteractions([dismiss]);
const ref = useComposedRef(floating.refs.setFloating);
return (
<Toolbar
{...getFloatingProps()}
ref={ref}
onOverlayOpenChange={onOverlayOpenChange}
style={floating.style}
className="absolute z-50 scrollbar-hide max-w-[80vw] overflow-x-auto rounded-md border bg-popover p-1 whitespace-nowrap opacity-100 shadow-md print:hidden"
>
{children}
</Toolbar>
);
}
export const FloatingToolbarPlugin = definePlugin('floatingToolbar', {
slots: {
caret: () => <FloatingToolbar />,
},
});
export const FloatingToolbarKit = [FloatingToolbarPlugin] as const;'use client';
import { cn } from 'cn';
import {
BaselineIcon,
BoldIcon,
Code2Icon,
HighlighterIcon,
ItalicIcon,
PaintBucketIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import {
BaseAudioPlugin,
BaseFilePlugin,
BaseImagePlugin,
BaseVideoPlugin,
} from 'platejs/media';
import {
BoldPlugin,
CodePlugin,
HighlightPlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
FontBackgroundColorPlugin,
FontColorPlugin,
useEditor,
useEditorReadOnly,
useEditorViewState,
definePlugin,
} from 'platejs/react';
import * as React from 'react';
import { ToolbarGroup, Toolbar } from '@/components/editor/toolbar';
import { AIToolbarButton } from './ai-toolbar-button';
import { AlignToolbarButton } from './align-toolbar-button';
import { ClearFormattingToolbarButton } from './clear-formatting-toolbar-button';
import {
AllCommentsButton,
CommentToolbarButton,
} from './comment-toolbar-button';
import { DetailsToolbarButton } from './details-toolbar-button';
import { EmojiToolbarButton } from './emoji-toolbar-button';
import {
DEFAULT_COLORS,
FontColorToolbarButton,
} from './font-color-toolbar-button';
import { FontSizeToolbarButton } from './font-size-toolbar-button';
import { FormatPainterToolbarButton } from './format-painter-toolbar-button';
import { RedoToolbarButton, UndoToolbarButton } from './history-toolbar-button';
import {
IndentToolbarButton,
OutdentToolbarButton,
} from './indent-toolbar-button';
import { InsertToolbarButton } from './insert-toolbar-button';
import { LineHeightToolbarButton } from './line-height-toolbar-button';
import { LinkToolbarButton } from './link-toolbar-button';
import {
BulletedListToolbarButton,
NumberedListToolbarButton,
TodoListToolbarButton,
} from './list-toolbar-button';
import { MarkToolbarButton } from './mark-toolbar-button';
import { MediaToolbarButton } from './media-toolbar-button';
import { ModeToolbarButton } from './mode-toolbar-button';
import { MoreToolbarButton } from './more-toolbar-button';
import { TableToolbarButton } from './table-toolbar-button';
import { TurnIntoToolbarButton } from './turn-into-toolbar-button';
export function FixedToolbarButtons({
children,
}: {
children?: React.ReactNode;
} = {}) {
const editor = useEditor();
const viewing = useEditorViewState(editor, (view) => view.isViewing());
const readOnly = useEditorReadOnly();
return (
<div className="flex w-full">
{!viewing && (
<ToolbarGroup>
<UndoToolbarButton />
<RedoToolbarButton />
</ToolbarGroup>
)}
{!readOnly && (
<>
<ToolbarGroup>
<AIToolbarButton tooltip="AI commands">
<WandSparklesIcon />
</AIToolbarButton>
</ToolbarGroup>
{children}
<ToolbarGroup>
<InsertToolbarButton />
<TurnIntoToolbarButton />
<FontSizeToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={ItalicPlugin} tooltip="Italic">
<ItalicIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={UnderlinePlugin} tooltip="Underline">
<UnderlineIcon />
</MarkToolbarButton>
<MarkToolbarButton
plugin={StrikethroughPlugin}
tooltip="Strikethrough"
>
<StrikethroughIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={CodePlugin} tooltip="Code">
<Code2Icon />
</MarkToolbarButton>
<FontColorToolbarButton
colors={DEFAULT_COLORS}
plugin={FontColorPlugin}
tooltip="Text color"
>
<BaselineIcon />
</FontColorToolbarButton>
<FontColorToolbarButton
colors={DEFAULT_COLORS}
plugin={FontBackgroundColorPlugin}
tooltip="Background color"
>
<PaintBucketIcon />
</FontColorToolbarButton>
</ToolbarGroup>
<ToolbarGroup>
<AlignToolbarButton />
<ClearFormattingToolbarButton />
<FormatPainterToolbarButton />
<NumberedListToolbarButton />
<BulletedListToolbarButton />
<TodoListToolbarButton />
<DetailsToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<LinkToolbarButton />
<TableToolbarButton />
<EmojiToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MediaToolbarButton plugin={BaseImagePlugin} />
<MediaToolbarButton plugin={BaseVideoPlugin} />
<MediaToolbarButton plugin={BaseAudioPlugin} />
<MediaToolbarButton plugin={BaseFilePlugin} />
</ToolbarGroup>
<ToolbarGroup>
<LineHeightToolbarButton />
<OutdentToolbarButton />
<IndentToolbarButton />
</ToolbarGroup>
<ToolbarGroup>
<MoreToolbarButton />
</ToolbarGroup>
</>
)}
<div className="grow" />
<ToolbarGroup>
<MarkToolbarButton plugin={HighlightPlugin} tooltip="Highlight">
<HighlighterIcon />
</MarkToolbarButton>
<CommentToolbarButton />
<AllCommentsButton />
</ToolbarGroup>
<ToolbarGroup>
<ModeToolbarButton />
</ToolbarGroup>
</div>
);
}
export function FixedToolbar({
className,
ref,
...props
}: React.ComponentProps<typeof Toolbar>) {
return (
<Toolbar
{...props}
ref={ref}
className={cn(
'scrollbar-hide z-50 w-full shrink-0 justify-between overflow-x-auto rounded-t-lg border-b border-b-border bg-background/95 p-1 backdrop-blur-sm supports-backdrop-blur:bg-background/60',
className
)}
data-slot="fixed-toolbar"
/>
);
}
export const FixedToolbarPlugin = definePlugin('fixedToolbar', {
slots: {
beforeContainer: () => (
<FixedToolbar>
<FixedToolbarButtons />
</FixedToolbar>
),
},
});
export const FixedToolbarKit = [FixedToolbarPlugin] as const;'use client';
import {
flip,
offset,
shift,
useDismiss,
useInteractions,
} from '@floating-ui/react';
import {
BoldIcon,
Code2Icon,
ItalicIcon,
StrikethroughIcon,
UnderlineIcon,
WandSparklesIcon,
} from 'lucide-react';
import { AIChatPlugin } from 'platejs/ai/react';
import {
BoldPlugin,
CodePlugin,
ItalicPlugin,
StrikethroughPlugin,
UnderlinePlugin,
definePlugin,
useComposedRef,
useEditableRef,
useEditorFocused,
useEditorReadOnly,
useEditorSelector,
usePluginStore,
useSelectionGeometry,
} from 'platejs/react';
import * as React from 'react';
import { createPortal } from 'react-dom';
import { ToolbarGroup, Toolbar } from '@/components/editor/toolbar';
import { useFloatingRect } from '@/hooks/use-floating-rect';
import { AIToolbarButton } from './ai-toolbar-button';
import { CommentToolbarButton } from './comment-toolbar-button';
import { InlineEquationToolbarButton } from './equation-toolbar-button';
import { linkPlugin } from './link';
import { LinkToolbarButton } from './link-toolbar-button';
import { MarkToolbarButton } from './mark-toolbar-button';
import { MoreToolbarButton } from './more-toolbar-button';
import { SuggestionToolbarButton } from './suggestion-toolbar-button';
import { TurnIntoToolbarButton } from './turn-into-toolbar-button';
export function FloatingToolbarButtons() {
const readOnly = useEditorReadOnly();
return (
<>
{!readOnly && (
<ToolbarGroup>
<AIToolbarButton tooltip="AI commands">
<WandSparklesIcon />
Ask AI
</AIToolbarButton>
</ToolbarGroup>
)}
{!readOnly && (
<ToolbarGroup>
<TurnIntoToolbarButton />
<StyleButtons />
<InlineEquationToolbarButton />
<LinkToolbarButton />
</ToolbarGroup>
)}
<ToolbarGroup>
<CommentToolbarButton />
<SuggestionToolbarButton />
{!readOnly && <MoreToolbarButton />}
</ToolbarGroup>
</>
);
}
function StyleButtons() {
return (
<>
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={ItalicPlugin} tooltip="Italic">
<ItalicIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={UnderlinePlugin} tooltip="Underline">
<UnderlineIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={StrikethroughPlugin} tooltip="Strikethrough">
<StrikethroughIcon />
</MarkToolbarButton>
<MarkToolbarButton plugin={CodePlugin} tooltip="Code">
<Code2Icon />
</MarkToolbarButton>
</>
);
}
export function FloatingToolbar({ children }: { children?: React.ReactNode }) {
const hasNodeSelection = useEditorSelector(
(editor) => editor.read.selection.nodes().length > 0
);
const touch = useCoarsePointer();
if (hasNodeSelection) return null;
const buttons =
children === undefined ? <FloatingToolbarButtons /> : children;
return touch ? (
<KeyboardToolbar>{buttons}</KeyboardToolbar>
) : (
<TextFloatingToolbar>{buttons}</TextFloatingToolbar>
);
}
const COARSE_POINTER_QUERY = '(pointer: coarse)';
const CARET_GAP = 8;
function subscribeCoarsePointer(onChange: () => void) {
const query = window.matchMedia(COARSE_POINTER_QUERY);
query.addEventListener('change', onChange);
return () => query.removeEventListener('change', onChange);
}
function useCoarsePointer() {
return React.useSyncExternalStore(
subscribeCoarsePointer,
() => window.matchMedia(COARSE_POINTER_QUERY).matches,
() => false
);
}
function subscribeViewport(onChange: () => void) {
const viewport = window.visualViewport;
const resized = viewport ?? window;
resized.addEventListener('resize', onChange);
viewport?.addEventListener('scroll', onChange);
return () => {
resized.removeEventListener('resize', onChange);
viewport?.removeEventListener('scroll', onChange);
};
}
function readViewportBottom() {
const viewport = window.visualViewport;
return viewport ? viewport.offsetTop + viewport.height : window.innerHeight;
}
// A page cannot move the phone's own selection menu, which opens above the selection, and iOS gives it no way to hide it, so touch screens dock the toolbar above the keyboard.
function KeyboardToolbar({ children }: { children: React.ReactNode }) {
const editableRef = useEditableRef();
const editorFocused = useEditorFocused();
const readOnly = useEditorReadOnly();
const isFloatingLinkOpen = !!usePluginStore(linkPlugin, 'mode');
const isAIChatOpen = usePluginStore(AIChatPlugin, 'open');
const [ownedOverlayOpen, setOwnedOverlayOpen] = React.useState(false);
const viewportBottom = React.useSyncExternalStore(
subscribeViewport,
readViewportBottom,
() => 0
);
const barRef = React.useRef<HTMLDivElement>(null);
const open =
!isFloatingLinkOpen &&
!isAIChatOpen &&
!readOnly &&
(editorFocused || ownedOverlayOpen);
React.useEffect(() => {
const document = editableRef.current?.ownerDocument;
const view = document?.defaultView;
if (!open || !document || !view) return undefined;
let frame = 0;
const revealCaret = () => {
view.cancelAnimationFrame(frame);
frame = view.requestAnimationFrame(() => {
const selection = document.getSelection();
const node = selection?.focusNode;
const element = node instanceof Element ? node : node?.parentElement;
const bar = barRef.current;
if (
!bar ||
!selection?.isCollapsed ||
!element ||
!editableRef.current?.contains(element)
) {
return;
}
const caret = selection.getRangeAt(0).getClientRects()[0];
let overlap =
(caret ?? element.getBoundingClientRect()).bottom +
CARET_GAP -
bar.getBoundingClientRect().top;
for (
let parent = element.parentElement;
parent && overlap > 0;
parent = parent.parentElement
) {
if (!/auto|scroll/.test(view.getComputedStyle(parent).overflowY)) {
continue;
}
const before = parent.scrollTop;
parent.scrollTop += overlap;
overlap -= parent.scrollTop - before;
}
if (overlap > 0) view.scrollBy(0, overlap);
});
};
document.addEventListener('selectionchange', revealCaret);
view.visualViewport?.addEventListener('resize', revealCaret);
revealCaret();
return () => {
view.cancelAnimationFrame(frame);
document.removeEventListener('selectionchange', revealCaret);
view.visualViewport?.removeEventListener('resize', revealCaret);
};
}, [editableRef, open]);
if (!open) return null;
return createPortal(
<Toolbar
ref={barRef}
data-slot="keyboard-toolbar"
onOverlayOpenChange={setOwnedOverlayOpen}
style={{ top: viewportBottom }}
className="fixed inset-x-0 z-50 scrollbar-hide -translate-y-full overflow-x-auto border-t bg-popover p-1 whitespace-nowrap print:hidden"
>
{children}
</Toolbar>,
document.body
);
}
function TextFloatingToolbar({ children }: { children: React.ReactNode }) {
const editableRef = useEditableRef();
const editorFocused = useEditorFocused();
const isFloatingLinkOpen = !!usePluginStore(linkPlugin, 'mode');
const isAIChatOpen = usePluginStore(AIChatPlugin, 'open');
const [selectionRange, setSelectionRange] = React.useState<Range | null>(
null
);
const readOnly = useEditorReadOnly();
const [dismissedSelection, setDismissedSelection] =
React.useState<typeof selectionRange>(null);
const [mouseDownOpen, setMouseDownOpen] = React.useState<boolean | null>(
null
);
const [ownedOverlayOpen, setOwnedOverlayOpen] = React.useState(false);
// WebKit clears the DOM selection when an owned overlay takes focus, so the overlay alone holds the toolbar.
const open =
!isFloatingLinkOpen &&
!isAIChatOpen &&
!readOnly &&
mouseDownOpen !== false &&
(ownedOverlayOpen ||
(selectionRange !== null &&
editorFocused &&
dismissedSelection !== selectionRange));
const openStateRef = React.useRef(open);
React.useEffect(() => {
openStateRef.current = open;
}, [open]);
React.useEffect(() => {
const document = editableRef.current?.ownerDocument;
if (!document) return undefined;
const readSelection = () => {
const editable = editableRef.current;
const root = editable?.getRootNode() as Document | ShadowRoot | undefined;
const selection =
root && 'getSelection' in root
? root.getSelection()
: document.getSelection();
const range = selection?.rangeCount ? selection.getRangeAt(0) : null;
const next =
range &&
!range.collapsed &&
selection?.toString() &&
editable?.contains(range.startContainer) &&
editable.contains(range.endContainer)
? range
: null;
setSelectionRange((previous) => {
if (!next) return null;
if (
previous &&
previous.startContainer === next.startContainer &&
previous.startOffset === next.startOffset &&
previous.endContainer === next.endContainer &&
previous.endOffset === next.endOffset
) {
return previous;
}
return next.cloneRange();
});
};
const onMouseUp = () => {
readSelection();
setMouseDownOpen(null);
};
const onMouseDown = () => {
setMouseDownOpen(openStateRef.current);
};
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('mousedown', onMouseDown);
document.addEventListener('selectionchange', readSelection);
readSelection();
return () => {
document.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('selectionchange', readSelection);
};
}, [editableRef]);
if (!open) return null;
return (
<PositionedFloatingToolbar
onOpenChange={(nextOpen) => {
setDismissedSelection(nextOpen ? null : selectionRange);
}}
onOverlayOpenChange={setOwnedOverlayOpen}
>
{children}
</PositionedFloatingToolbar>
);
}
function PositionedFloatingToolbar({
children,
onOpenChange,
onOverlayOpenChange,
}: {
children: React.ReactNode;
onOpenChange: (open: boolean) => void;
onOverlayOpenChange: (open: boolean) => void;
}) {
const editableRef = useEditableRef();
const geometry = useSelectionGeometry({ editableRef });
const floating = useFloatingRect(geometry, {
open: true,
middleware: [
offset(12),
flip({
fallbackPlacements: [
'top-start',
'top-end',
'bottom-start',
'bottom-end',
],
padding: 12,
}),
shift({ padding: 8 }),
],
placement: 'top',
onOpenChange,
});
const dismiss = useDismiss(floating.context, {
escapeKey: false,
outsidePress: (event) => {
const Element =
floating.elements.floating?.ownerDocument.defaultView?.Element;
return (
!Element ||
!(event.target instanceof Element) ||
!event.target.closest('[class~="ignore-click-outside/toolbar"]')
);
},
});
const { getFloatingProps } = useInteractions([dismiss]);
const ref = useComposedRef(floating.refs.setFloating);
return (
<Toolbar
{...getFloatingProps()}
ref={ref}
onOverlayOpenChange={onOverlayOpenChange}
style={floating.style}
className="absolute z-50 scrollbar-hide max-w-[80vw] overflow-x-auto rounded-md border bg-popover p-1 whitespace-nowrap opacity-100 shadow-md print:hidden"
>
{children}
</Toolbar>
);
}
export const FloatingToolbarPlugin = definePlugin('floatingToolbar', {
slots: {
caret: () => <FloatingToolbar />,
},
});
export const FloatingToolbarKit = [FloatingToolbarPlugin] as const;import { useEditor } from 'platejs/react';
import { CustomIcon } from 'lucide-react';
import { ToolbarButton } from '@/components/editor/toolbar';
export function CustomToolbarButton() {
const editor = useEditor();
return (
<ToolbarButton
onClick={() => {
// Custom action
editor.update((tx) => {
tx.text.insert('Custom text');
});
}}
tooltip="Custom Action"
>
<CustomIcon />
</ToolbarButton>
);
}import { BoldIcon } from 'lucide-react';
import { BoldPlugin } from 'platejs/react';
import { MarkToolbarButton } from '@/components/editor/mark-toolbar-button';
export function BoldToolbarButton() {
return (
<MarkToolbarButton plugin={BoldPlugin} tooltip="Bold">
<BoldIcon />
</MarkToolbarButton>
);
}'use client';
import {
ChevronRightIcon,
Columns3Icon,
FileCodeIcon,
Heading1Icon,
Heading2Icon,
Heading3Icon,
Heading4Icon,
Heading5Icon,
Heading6Icon,
ListIcon,
ListOrderedIcon,
PilcrowIcon,
QuoteIcon,
SquareIcon,
} from 'lucide-react';
import {
BaseBlockquotePlugin,
BaseCodeBlockPlugin,
BaseHeadingPlugin,
BaseListPlugin,
defineCommand,
ElementApi,
PathApi,
SelectionApi,
type Element,
} from 'platejs';
import { BaseDetailsPlugin, BaseDetailsSummaryPlugin } from 'platejs/details';
import { BaseColumnGroupPlugin } from 'platejs/layout';
import {
type Editor,
useEditor,
useEditorReadOnly,
useEditorSelector,
useSelectionFragmentProp,
} from 'platejs/react';
import * as React from 'react';
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import {
ToolbarButton,
ToolbarMenuGroup,
} from '@/components/editor/toolbar';
type LeafFormat =
| 'decimal'
| 'disc'
| 'heading-1'
| 'heading-2'
| 'heading-3'
| 'heading-4'
| 'heading-5'
| 'heading-6'
| 'text'
| 'todo';
type LeafItem = {
icon: React.ReactNode;
label: string;
onSelect: () => void;
value: LeafFormat;
};
type StructuralActionState = {
active: boolean;
eligible: boolean;
};
type StructuralState = {
code: StructuralActionState;
columns: StructuralActionState;
details: StructuralActionState;
quote: StructuralActionState;
};
const turnIntoList = defineCommand<
Readonly<{ type: 'bulleted' | 'numbered' | 'task' }>,
Editor
>('turn-into:list', {
build: ({ input: { type }, state }) => {
let applied = false;
const result = state.transaction((tx) => {
const selection = tx.selection();
if (!selection) return;
const root = SelectionApi.root(selection);
const [first, ...rest] = tx.nodes
.blocks({ mode: 'lowest' })
.map(([, path]) => path);
if (
first &&
!tx.blocks.reset({
at: SelectionApi.nodes([first, ...rest], {
mode: 'block',
...(root ? { root } : {}),
}),
unset: ['level'],
})
) {
return;
}
tx.plugin(BaseListPlugin).clear();
applied = tx.plugin(BaseListPlugin).toggle({ type });
});
return applied ? result : false;
},
locate: false,
});
const readBlocks = (
editor: Editor,
mode: 'highest' | 'lowest'
): ReturnType<Editor['read']['nodes']['blocks']> => {
const selection = editor.read.selection();
if (
!selection ||
(SelectionApi.isText(selection) &&
!editor.read.selection.isValid(selection))
) {
return [];
}
return editor.read.nodes.blocks({ mode });
};
const isContiguousSiblingRun = (
entries: ReturnType<Editor['read']['nodes']['blocks']>
) => {
if (entries.length === 0) return false;
const paths = entries.map(([, path]) => path).toSorted(PathApi.compare);
const parent = PathApi.parent(paths[0]);
const firstIndex = paths[0].at(-1);
return (
firstIndex !== undefined &&
paths.every(
(path, index) =>
PathApi.equals(PathApi.parent(path), parent) &&
path.at(-1) === firstIndex + index
)
);
};
const hasWrapper = (
editor: Editor,
entry: ReturnType<Editor['read']['nodes']['blocks']>[number],
plugin: typeof BaseBlockquotePlugin | typeof BaseDetailsPlugin
) => {
const portal = editor.plugin(plugin);
return (
portal.installed &&
(entry[0].type === portal.schema.type ||
!!editor.read.nodes.above({
at: editor.key(entry[0]),
type: portal.schema.type,
}))
);
};
const getStructuralState = (editor: Editor): StructuralState => {
const entries = readBlocks(editor, 'highest');
const leafEntries = readBlocks(editor, 'lowest');
const selectedEntries = editor.read.selection.nodes();
const hasSelection = entries.length > 0;
const hasContainerNodeSelection = selectedEntries.some(([, selectedPath]) =>
leafEntries.some(([, path]) => PathApi.isAncestor(selectedPath, path))
);
const quote = editor.plugin(BaseBlockquotePlugin);
const details = editor.plugin(BaseDetailsPlugin);
const code = editor.plugin(BaseCodeBlockPlugin);
const columns = editor.plugin(BaseColumnGroupPlugin);
const quoteActive =
quote.installed &&
hasSelection &&
entries.every((entry) => hasWrapper(editor, entry, BaseBlockquotePlugin));
const detailsMembership = details.installed
? entries.map((entry) => hasWrapper(editor, entry, BaseDetailsPlugin))
: [];
const detailsActive = hasSelection && detailsMembership.every(Boolean);
const detailsMixed = detailsMembership.some(Boolean) && !detailsActive;
const codeMembership = code.installed
? entries.map(([node]) => !node.listType && node.type === code.schema.type)
: [];
const codeActive = hasSelection && codeMembership.every(Boolean);
const codeMixed = codeMembership.some(Boolean) && !codeActive;
const summary = editor.plugin(BaseDetailsSummaryPlugin);
// codeBlock.toggle converts a Details title only on its own.
const holdsTitleAndMore =
summary.installed &&
leafEntries.length > 1 &&
leafEntries.some(([node]) => node.type === summary.schema.type);
const columnActive =
columns.installed &&
entries.length === 1 &&
(entries[0][0].type === columns.schema.type ||
!!editor.read.nodes.above({
at: entries[0][1],
type: BaseColumnGroupPlugin,
}));
return {
code: {
active: codeActive,
eligible:
code.installed &&
!codeMixed &&
!holdsTitleAndMore &&
(selectedEntries.length > 0 || isContiguousSiblingRun(entries)),
},
columns: {
active: columnActive,
eligible:
columns.installed &&
(columnActive || (!hasContainerNodeSelection && entries.length === 1)),
},
details: {
active: detailsActive,
eligible:
details.installed &&
!detailsMixed &&
(detailsActive ||
(!hasContainerNodeSelection && isContiguousSiblingRun(entries))),
},
quote: {
active: quoteActive,
eligible: quote.installed && hasSelection,
},
};
};
type RefusedItem = LeafFormat | keyof StructuralState;
const noRefusedItems: RefusedItem[] = [];
const getNoRefusedItems = () => noRefusedItems;
const getRefusedItems = (editor: Editor) => {
const [highest] = readBlocks(editor, 'highest');
const root = editor.read.view.root();
const heading = editor.plugin(BaseHeadingPlugin);
const refused: RefusedItem[] = [];
if (heading.installed) {
for (const level of [1, 2, 3, 4, 5, 6] as const) {
if (!heading.read.canSetLevel(level)) {
refused.push(`heading-${level}`);
}
}
}
for (const [value, plugin] of [
['quote', BaseBlockquotePlugin],
['details', BaseDetailsPlugin],
['code', BaseCodeBlockPlugin],
['columns', BaseColumnGroupPlugin],
] as const) {
const portal = editor.plugin(plugin);
if (
portal.installed &&
highest &&
!editor.read.schema.canPlace(
[{ children: highest[0].children, type: portal.schema.type }],
{ at: highest[1], replace: true, root }
)
) {
refused.push(value);
}
}
return refused;
};
const getLeafFormat = (editor: Editor, node: Element): LeafFormat => {
const list = editor.plugin(BaseListPlugin);
if (list.installed && node.listType) {
if (node.listType === 'numbered') return 'decimal';
if (node.listType === 'task') return 'todo';
return 'disc';
}
const heading = editor.plugin(BaseHeadingPlugin);
const level = heading.installed ? heading.read.level(node) : undefined;
return level === undefined ? 'text' : `heading-${level}`;
};
const isLeafFormatActive = (editor: Editor, value: LeafFormat) => {
const entries = readBlocks(editor, 'lowest');
return (
entries.length > 0 &&
entries.every(([node]) => getLeafFormat(editor, node) === value)
);
};
const getTurnIntoLabel = (value: LeafFormat | undefined) => {
switch (value) {
case 'disc': {
return 'Bulleted list';
}
case 'decimal': {
return 'Numbered list';
}
case 'todo': {
return 'To-do list';
}
case 'heading-1': {
return 'Heading 1';
}
case 'heading-2': {
return 'Heading 2';
}
case 'heading-3': {
return 'Heading 3';
}
case 'heading-4': {
return 'Heading 4';
}
case 'heading-5': {
return 'Heading 5';
}
case 'heading-6': {
return 'Heading 6';
}
case 'text': {
return 'Text';
}
default: {
return 'Mixed';
}
}
};
function TurnIntoLeafItem({
children,
disabled,
icon,
value,
}: React.PropsWithChildren<{
disabled: boolean;
icon: React.ReactNode;
value: LeafFormat;
}>) {
return (
<DropdownMenuRadioItem
className="min-w-[180px]"
disabled={disabled}
value={value}
>
{icon}
{children}
</DropdownMenuRadioItem>
);
}
export function TurnIntoToolbarButton() {
const editor = useEditor();
const readOnly = useEditorReadOnly();
const [open, setOpen] = React.useState(false);
const leafValue = useSelectionFragmentProp({
defaultValue: 'text',
getProp: (node) =>
ElementApi.isElement(node) ? getLeafFormat(editor, node) : undefined,
}) as LeafFormat | undefined;
const structural = useEditorSelector(getStructuralState);
const refused = useEditorSelector(open ? getRefusedItems : getNoRefusedItems);
const hasSelection = useEditorSelector(
(current) => readBlocks(current, 'highest').length > 0
);
const heading = editor.plugin(BaseHeadingPlugin);
const list = editor.plugin(BaseListPlugin);
const quote = editor.plugin(BaseBlockquotePlugin);
const details = editor.plugin(BaseDetailsPlugin);
const code = editor.plugin(BaseCodeBlockPlugin);
const columns = editor.plugin(BaseColumnGroupPlugin);
const triggerLabel =
code.installed && structural.code.active
? 'Code'
: getTurnIntoLabel(leafValue);
const leafItems: LeafItem[] = [
{
icon: <PilcrowIcon />,
label: 'Text',
value: 'text',
onSelect: () => {
if (
editor.read.view.isReadOnly() ||
(isLeafFormatActive(editor, 'text') &&
readBlocks(editor, 'lowest').every(
([node]) => node.level === undefined
))
) {
return;
}
editor.update((tx) => {
if (!tx.blocks.reset({ unset: ['level'] })) return;
if (editor.plugin(BaseListPlugin).installed) {
tx.plugin(BaseListPlugin).clear();
}
});
},
},
];
if (heading.installed) {
(
[
['heading-1', 'Heading 1', <Heading1Icon key="heading-1" />, 1],
['heading-2', 'Heading 2', <Heading2Icon key="heading-2" />, 2],
['heading-3', 'Heading 3', <Heading3Icon key="heading-3" />, 3],
['heading-4', 'Heading 4', <Heading4Icon key="heading-4" />, 4],
['heading-5', 'Heading 5', <Heading5Icon key="heading-5" />, 5],
['heading-6', 'Heading 6', <Heading6Icon key="heading-6" />, 6],
] as const
).forEach(([value, label, icon, level]) => {
leafItems.push({
icon,
label,
value,
onSelect: () => {
const current = editor.plugin(BaseHeadingPlugin);
if (
!current.installed ||
editor.read.view.isReadOnly() ||
isLeafFormatActive(editor, value)
) {
return;
}
editor.update((tx) => {
if (!tx.plugin(BaseHeadingPlugin).setLevel(level)) return;
if (editor.plugin(BaseListPlugin).installed) {
tx.plugin(BaseListPlugin).clear();
}
});
},
});
});
}
if (list.installed) {
(
[
[
'disc',
'Bulleted list',
<ListIcon key="disc" className="[&:dir(rtl)]:-scale-x-100" />,
'bulleted',
],
[
'decimal',
'Numbered list',
<ListOrderedIcon key="decimal" />,
'numbered',
],
['todo', 'To-do list', <SquareIcon key="todo" />, 'task'],
] as const
).forEach(([value, label, icon, type]) => {
leafItems.push({
icon,
label,
value,
onSelect: () => {
if (
!editor.plugin(BaseListPlugin).installed ||
editor.read.view.isReadOnly() ||
isLeafFormatActive(editor, value)
) {
return;
}
editor.update.command(turnIntoList, { type });
},
});
});
}
const structuralItems = [
...(quote.installed
? [
{
...structural.quote,
refused: refused.includes('quote'),
icon: <QuoteIcon />,
label: 'Quote',
onSelect: () => {
const current = getStructuralState(editor).quote;
if (!current.eligible || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
if (
tx.plugin(BaseBlockquotePlugin).toggle() &&
editor.plugin(BaseListPlugin).installed
) {
tx.plugin(BaseListPlugin).clear();
}
});
},
},
]
: []),
...(details.installed
? [
{
...structural.details,
refused: refused.includes('details'),
icon: <ChevronRightIcon className="[&:dir(rtl)]:rotate-180" />,
label: 'Details',
onSelect: () => {
const current = getStructuralState(editor).details;
if (!current.eligible || editor.read.view.isReadOnly()) return;
const portal = editor.plugin(BaseDetailsPlugin);
if (!portal.installed) return;
if (current.active) {
portal.update.unwrap();
} else {
portal.update.wrap();
}
},
},
]
: []),
...(code.installed
? [
{
...structural.code,
refused: refused.includes('code'),
icon: <FileCodeIcon />,
label: 'Code',
onSelect: () => {
const current = getStructuralState(editor).code;
const portal = editor.plugin(BaseCodeBlockPlugin);
if (
!portal.installed ||
!current.eligible ||
editor.read.view.isReadOnly()
) {
return;
}
portal.update.toggle();
},
},
]
: []),
...(columns.installed
? [
{
...structural.columns,
refused: refused.includes('columns'),
icon: <Columns3Icon />,
label: '3 columns',
onSelect: () => {
const current = getStructuralState(editor).columns;
const portal = editor.plugin(BaseColumnGroupPlugin);
if (
!portal.installed ||
!current.eligible ||
editor.read.view.isReadOnly()
) {
return;
}
portal.update.toggle({ columns: 3 });
},
},
]
: []),
];
return (
<DropdownMenu open={open} onOpenChange={setOpen} modal={false}>
<DropdownMenuTrigger>
<ToolbarButton
aria-label={`Turn into: ${triggerLabel}`}
className="min-w-[125px]"
disabled={readOnly || !hasSelection}
pressed={open}
tooltip="Turn into"
isDropdown
>
{triggerLabel}
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="ignore-click-outside/toolbar min-w-0"
onFinalFocus={(event) => {
event.preventDefault();
editor.api.dom.focus();
}}
align="start"
>
<DropdownMenuRadioGroup
value={leafValue ?? ''}
onValueChange={(value) => {
const item = leafItems.find(
(candidate) => candidate.value === value
);
item?.onSelect();
}}
>
<ToolbarMenuGroup label="Turn into">
{leafItems.map((item) => (
<TurnIntoLeafItem
key={item.value}
disabled={refused.includes(item.value)}
icon={item.icon}
value={item.value}
>
{item.label}
</TurnIntoLeafItem>
))}
</ToolbarMenuGroup>
</DropdownMenuRadioGroup>
{structuralItems.length > 0 && (
<ToolbarMenuGroup label="Structure">
{structuralItems.map((item) => (
<DropdownMenuCheckboxItem
key={item.label}
checked={item.active}
className="min-w-[180px]"
disabled={!item.eligible || item.refused}
onSelect={item.onSelect}
>
{item.icon}
{item.label}
</DropdownMenuCheckboxItem>
))}
</ToolbarMenuGroup>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}'use client';
import {
CalendarIcon,
ChevronRightIcon,
Columns3Icon,
FileCodeIcon,
FilmIcon,
Heading1Icon,
Heading2Icon,
Heading3Icon,
ImageIcon,
Link2Icon,
ListIcon,
ListOrderedIcon,
MinusIcon,
PenToolIcon,
PilcrowIcon,
PlusIcon,
QuoteIcon,
RadicalIcon,
SquareIcon,
SuperscriptIcon,
TableIcon,
TableOfContentsIcon,
} from 'lucide-react';
import {
BaseBlockquotePlugin,
BaseCodeBlockPlugin,
BaseHeadingPlugin,
BaseHorizontalRulePlugin,
BaseListPlugin,
BaseParagraphPlugin,
type Descendant,
PathApi,
PLUGINS,
} from 'platejs';
import { BaseDatePlugin } from 'platejs/date';
import { BaseDetailsPlugin } from 'platejs/details';
import { BaseExcalidrawPlugin } from 'platejs/excalidraw';
import { BaseFootnotePlugin } from 'platejs/footnote';
import { BaseColumnGroupPlugin } from 'platejs/layout';
import { BaseEquationPlugin, BaseInlineEquationPlugin } from 'platejs/math';
import { BaseImagePlugin, BaseMediaEmbedPlugin } from 'platejs/media';
import {
type Editor,
useEditor,
useEditorReadOnly,
useEditorSelector,
} from 'platejs/react';
import { BaseTablePlugin } from 'platejs/table';
import { BaseTocPlugin } from 'platejs/toc';
import * as React from 'react';
import { toast } from 'sonner';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import {
ToolbarButton,
ToolbarMenuGroup,
} from '@/components/editor/toolbar';
import { linkPlugin } from './link';
type Item = {
icon: React.ReactNode;
onSelect: () => void;
value: string;
block?: Descendant;
focusEditor?: boolean;
label?: string;
};
const blockOf = (
type: string,
properties: Readonly<Record<string, unknown>> = {}
): Descendant => ({ ...properties, children: [{ text: '' }], type });
type Group = {
group: string;
items: Item[];
};
const canRestoreFocus = (
editor: Editor,
ownerDocument: Document | undefined,
activeElement: Element | null | undefined
) => {
const editable = editor.api.dom.editable();
const currentActiveElement = ownerDocument?.activeElement;
return (
editable?.isConnected === true &&
!editor.read.view.isReadOnly() &&
(!currentActiveElement ||
currentActiveElement === ownerDocument?.body ||
currentActiveElement === activeElement)
);
};
function getGroups(editor: Editor): Group[] {
const groups: Group[] = [];
const basicBlocks: Item[] = [];
const lists: Item[] = [];
const media: Item[] = [];
const advancedBlocks: Item[] = [];
const inline: Item[] = [];
const paragraph = editor.plugin(BaseParagraphPlugin);
const heading = editor.plugin(BaseHeadingPlugin);
const list = editor.plugin(BaseListPlugin);
const table = editor.plugin(BaseTablePlugin);
const codeBlock = editor.plugin(BaseCodeBlockPlugin);
const blockquote = editor.plugin(BaseBlockquotePlugin);
const horizontalRule = editor.plugin(BaseHorizontalRulePlugin);
const details = editor.plugin(BaseDetailsPlugin);
const image = editor.plugin(BaseImagePlugin);
const mediaEmbed = editor.plugin(BaseMediaEmbedPlugin);
const toc = editor.plugin(BaseTocPlugin);
const column = editor.plugin(BaseColumnGroupPlugin);
const equation = editor.plugin(BaseEquationPlugin);
const excalidraw = editor.plugin(BaseExcalidrawPlugin);
const link = editor.plugin(linkPlugin);
const date = editor.plugin(BaseDatePlugin);
const footnote = editor.plugin(BaseFootnotePlugin);
const inlineEquation = editor.plugin(BaseInlineEquationPlugin);
if (paragraph.installed) {
basicBlocks.push({
icon: <PilcrowIcon />,
block: blockOf(paragraph.schema.type),
label: 'Paragraph',
value: PLUGINS.paragraph,
onSelect: () => {
const current = editor.plugin(BaseParagraphPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseParagraphPlugin).insert({}, { select: true });
});
},
});
}
if (heading.installed) {
(
[
['heading-1', 'Heading 1', <Heading1Icon key="heading-1" />, 1],
['heading-2', 'Heading 2', <Heading2Icon key="heading-2" />, 2],
['heading-3', 'Heading 3', <Heading3Icon key="heading-3" />, 3],
] as const
).forEach(([value, label, icon, level]) => {
basicBlocks.push({
block: blockOf(heading.schema.type, { level }),
icon,
label,
value,
onSelect: () => {
const current = editor.plugin(BaseHeadingPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseHeadingPlugin).insert({ level }, { select: true });
});
},
});
});
}
if (table.installed) {
basicBlocks.push({
icon: <TableIcon />,
block: blockOf(table.schema.type),
label: 'Table',
value: PLUGINS.table,
onSelect: () => {
const current = editor.plugin(BaseTablePlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseTablePlugin).insert({}, { select: true });
});
},
});
}
if (codeBlock.installed) {
basicBlocks.push({
icon: <FileCodeIcon />,
block: blockOf(codeBlock.schema.type),
label: 'Code',
value: PLUGINS.codeBlock,
onSelect: () => {
const current = editor.plugin(BaseCodeBlockPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseCodeBlockPlugin).insert({}, { select: true });
});
},
});
}
if (blockquote.installed) {
basicBlocks.push({
icon: <QuoteIcon />,
block: blockOf(blockquote.schema.type),
label: 'Quote',
value: PLUGINS.blockquote,
onSelect: () => {
const current = editor.plugin(BaseBlockquotePlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseBlockquotePlugin).insert({}, { select: true });
});
},
});
}
if (horizontalRule.installed) {
basicBlocks.push({
icon: <MinusIcon />,
block: blockOf(horizontalRule.schema.type),
label: 'Divider',
value: PLUGINS.horizontalRule,
onSelect: () => {
const current = editor.plugin(BaseHorizontalRulePlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseHorizontalRulePlugin).insert({}, { select: true });
});
},
});
}
if (list.installed) {
(
[
[
'disc',
'Bulleted list',
<ListIcon key="disc" className="[&:dir(rtl)]:-scale-x-100" />,
'bulleted',
],
[
'decimal',
'Numbered list',
<ListOrderedIcon key="decimal" />,
'numbered',
],
['todo', 'To-do list', <SquareIcon key="todo" />, 'task'],
] as const
).forEach(([value, label, icon, type]) => {
lists.push({
block: paragraph.installed
? blockOf(paragraph.schema.type, { indent: 1, listType: type })
: undefined,
icon,
label,
value,
onSelect: () => {
if (
!editor.plugin(BaseListPlugin).installed ||
editor.read.view.isReadOnly()
) {
return;
}
editor.update((tx) => {
tx.plugin(BaseListPlugin).insert({ type }, { select: true });
});
},
});
});
}
if (details.installed) {
lists.push({
icon: <ChevronRightIcon className="[&:dir(rtl)]:rotate-180" />,
block: blockOf(details.schema.type),
label: 'Details',
value: PLUGINS.details,
onSelect: () => {
const current = editor.plugin(BaseDetailsPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseDetailsPlugin).insert({}, { select: true });
});
},
});
}
if (image.installed) {
media.push({
focusEditor: false,
icon: <ImageIcon />,
block: blockOf(image.schema.type),
label: 'Image',
value: PLUGINS.image,
onSelect: () => {
const current = editor.plugin(BaseImagePlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
const editable = editor.api.dom.editable();
const ownerDocument = editable?.ownerDocument;
const activeElement = ownerDocument?.activeElement;
void current.api
.insertUrl(
// oxlint-disable-next-line no-alert -- This copied menu owns its URL input policy.
() => window.prompt('Enter the URL of the image'),
{ select: true }
)
.then((inserted) => {
if (
inserted &&
canRestoreFocus(editor, ownerDocument, activeElement)
) {
editor.api.dom.focus();
}
})
.catch((error: unknown) => {
console.error('Could not insert the image URL.', error);
});
},
});
}
if (mediaEmbed.installed) {
media.push({
focusEditor: false,
icon: <FilmIcon />,
block: blockOf(mediaEmbed.schema.type),
label: 'Embed',
value: PLUGINS.mediaEmbed,
onSelect: () => {
const current = editor.plugin(BaseMediaEmbedPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
const editable = editor.api.dom.editable();
const ownerDocument = editable?.ownerDocument;
const activeElement = ownerDocument?.activeElement;
void current.api
.insertUrl(
() => {
// oxlint-disable-next-line no-alert -- This copied menu owns its URL input policy.
const url = window.prompt('Enter the URL of the embed');
if (!url || current.api.normalizeUrl(url)?.provider) return url;
toast.error(
'Paste a YouTube, Vimeo, Dailymotion, Youku, Coub or X link.'
);
return null;
},
{ select: true }
)
.then((inserted) => {
if (
inserted &&
canRestoreFocus(editor, ownerDocument, activeElement)
) {
editor.api.dom.focus();
}
})
.catch((error: unknown) => {
console.error('Could not insert the embed URL.', error);
});
},
});
}
if (toc.installed) {
advancedBlocks.push({
icon: <TableOfContentsIcon />,
block: blockOf(toc.schema.type),
label: 'Table of contents',
value: PLUGINS.toc,
onSelect: () => {
const current = editor.plugin(BaseTocPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseTocPlugin).insert({}, { select: true });
});
},
});
}
if (column.installed) {
advancedBlocks.push({
icon: <Columns3Icon />,
block: blockOf(column.schema.type),
label: '3 columns',
value: 'action_three_columns',
onSelect: () => {
const current = editor.plugin(BaseColumnGroupPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseColumnGroupPlugin).insert(
{ columns: 3 },
{ select: true }
);
});
},
});
}
if (equation.installed) {
advancedBlocks.push({
focusEditor: false,
icon: <RadicalIcon />,
block: blockOf(equation.schema.type),
label: 'Equation',
value: PLUGINS.equation,
onSelect: () => {
const current = editor.plugin(BaseEquationPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseEquationPlugin).insert({}, { select: true });
});
},
});
}
if (excalidraw.installed) {
advancedBlocks.push({
icon: <PenToolIcon />,
block: blockOf(excalidraw.schema.type),
label: 'Excalidraw',
value: PLUGINS.excalidraw,
onSelect: () => {
const current = editor.plugin(BaseExcalidrawPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
tx.plugin(BaseExcalidrawPlugin).insert({}, { select: true });
});
},
});
}
if (link.installed) {
inline.push({
focusEditor: false,
icon: <Link2Icon />,
label: 'Link',
value: PLUGINS.link,
onSelect: () => {
const current = editor.plugin(linkPlugin);
if (!current.installed || editor.read.view.isReadOnly()) return;
current.store.set({ text: editor.read.text.string() });
current.api.show('insert', editor.id);
},
});
}
if (date.installed) {
inline.push({
icon: <CalendarIcon />,
label: 'Date',
value: PLUGINS.date,
onSelect: () => {
if (
!editor.plugin(BaseDatePlugin).installed ||
editor.read.view.isReadOnly()
) {
return;
}
editor.update((tx) => {
tx.plugin(BaseDatePlugin).insert({}, { select: true });
});
},
});
}
if (footnote.installed) {
inline.push({
icon: <SuperscriptIcon />,
label: 'Footnote',
value: 'action_footnote',
onSelect: () => {
if (
!editor.plugin(BaseFootnotePlugin).installed ||
editor.read.view.isReadOnly()
) {
return;
}
editor.update((tx) => {
tx.plugin(BaseFootnotePlugin).insert({}, { select: true });
});
},
});
}
if (inlineEquation.installed) {
inline.push({
focusEditor: false,
icon: <RadicalIcon />,
label: 'Inline Equation',
value: PLUGINS.inlineEquation,
onSelect: () => {
if (
!editor.plugin(BaseInlineEquationPlugin).installed ||
editor.read.view.isReadOnly()
) {
return;
}
editor.update((tx) => {
tx.plugin(BaseInlineEquationPlugin).insert({}, { select: true });
});
},
});
}
if (basicBlocks.length > 0) {
groups.push({ group: 'Basic blocks', items: basicBlocks });
}
if (lists.length > 0) groups.push({ group: 'Lists', items: lists });
if (media.length > 0) groups.push({ group: 'Media', items: media });
if (advancedBlocks.length > 0) {
groups.push({ group: 'Advanced blocks', items: advancedBlocks });
}
if (inline.length > 0) groups.push({ group: 'Inline', items: inline });
return groups;
}
const noRefusedItems: string[] = [];
const getNoRefusedItems = () => noRefusedItems;
const getRefusedItems = (editor: Editor) => {
const entry = editor.read.selection() ? editor.read.nodes.block() : undefined;
if (!entry) return noRefusedItems;
const at = PathApi.next(entry[1]);
const root = editor.read.view.root();
return getGroups(editor).flatMap(({ items }) =>
items.flatMap(({ block, value }) =>
block && !editor.read.schema.canPlace([block], { at, root })
? [value]
: []
)
);
};
export function InsertToolbarButton() {
const editor = useEditor();
const readOnly = useEditorReadOnly();
const [open, setOpen] = React.useState(false);
const groups = getGroups(editor);
const refused = useEditorSelector(open ? getRefusedItems : getNoRefusedItems);
return (
<DropdownMenu open={open} onOpenChange={setOpen} modal={false}>
<DropdownMenuTrigger>
<ToolbarButton
disabled={readOnly || groups.length === 0}
pressed={open}
tooltip="Insert"
isDropdown
>
<PlusIcon />
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="flex max-h-[500px] min-w-0 flex-col overflow-y-auto"
align="start"
>
{groups.map(({ group, items }) => (
<ToolbarMenuGroup key={group} label={group}>
{items.map(
({ focusEditor = true, icon, label, value, onSelect }) => (
<DropdownMenuItem
key={value}
className="min-w-[180px]"
disabled={refused.includes(value)}
finalFocus={
focusEditor
? () => {
if (!editor.read.view.isReadOnly()) {
editor.api.dom.focus();
}
}
: false
}
onSelect={onSelect}
>
{icon}
{label}
</DropdownMenuItem>
)
)}
</ToolbarMenuGroup>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}{
icon: <Heading2Icon />,
label: 'Heading 2',
value: 'heading-2',
onSelect: () => {
const heading = editor.plugin(BaseHeadingPlugin);
if (!heading.installed || editor.read.view.isReadOnly()) return;
editor.update((tx) => {
insertBlock(tx, {
matches: (block) =>
!block.listType &&
block.type === heading.schema.type &&
block.level === 2,
insert: (options) => {
tx.plugin(BaseHeadingPlugin).insert({ level: 2 }, options);
},
});
});
},
}