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

AI

PreviousNext

AI-powered writing assistance.

Plus
Loading…
OverviewCopilot

On This Page

FeaturesKit usageInstallationAdd kitRender the editorAdd API routeConfigure credentialsManual usageInstallationConfigure the kitBuild API routeOwn the chat lifecyclePrompt templatesClient promptingServer promptingKeyboard shortcutsStreamingTracked AI editsPlate PlusAPI ReferenceAIChatPlugineditor.plugin(AIChatPlugin).api.submit(input, options?)editor.plugin(AIChatPlugin).api.reset()editor.read.aiChat.node(options?)editor.plugin(AIChatPlugin).api.reload()editor.plugin(AIChatPlugin).api.stop()editor.plugin(AIChatPlugin).api.show()editor.plugin(AIChatPlugin).api.hide(options?)editor.plugin(AIChatPlugin).api.accept()editor.plugin(AIChatPlugin).api.insertBelow(options?)editor.plugin(AIChatPlugin).api.replaceSelection(options?)Registry chat previewuseAIChatAI chat capabilitiesCustomizationAdding custom AI commandsSimple custom commandCommand with complex logic
Build your editor
Production-ready AI template and reusable components.
Get all-access

Features

  • Context-aware command menu that adapts to cursor, text selection, and block selection workflows.
  • Streaming Markdown previews with table, column, and code block support through editor.plugin(AIChatPlugin).api.setPreview.
  • Insert and chat review modes that hold a generated response as a temporary draft and a chat edit as a suggestion in the document.
  • Block selection aware actions to replace or append entire sections using editor.plugin(AIChatPlugin).api.replaceSelection and insertBelow.
  • Direct integration with @ai-sdk/react so editor.plugin(AIChatPlugin).api.submit can stream responses from Vercel AI SDK helpers.
  • Explicit acceptance that applies a draft in one undo step, or accepts a chat edit's suggestion, without changing the editing mode.
Report an issue

Kit usage

Installation

The fastest way to add AI functionality is with the AIKit. It ships the configured AIChatPlugin, Markdown streaming helpers, cursor overlay, and their Plate UI components.

'use client';
 
import { BaseParagraphPlugin } from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import {
  useEditorSelector,
  usePluginStore,
  type RenderNodeWrapperProps,
  type WrapRootProps,
} from 'platejs/react';
 
import {
  AIChatEditor,
  AILoadingBar,
  AIMenu,
} from '@/components/editor/ai-menu';
 
import { AIChatTransportPlugin, useEditorChat } from './use-chat';
 
function AIInlinePreview({
  children,
  element,
}: RenderNodeWrapperProps<typeof AIChatTransportPlugin>) {
  const replacesEmptyParagraph = useEditorSelector((editor) => {
    const paragraph = editor.read.nodes.get(element, {
      type: editor.plugin(BaseParagraphPlugin).schema.type,
    });
 
    return !!paragraph && editor.read.nodes.isEmpty(paragraph[0]);
  });
  return (
    <div data-editor-ai-preview-wrapper="">
      <div hidden={replacesEmptyParagraph}>{children}</div>
      <div contentEditable={false} data-editor-ai-preview="">
        <AIChatEditor inline />
      </div>
    </div>
  );
}
 
function AIIntegration({ children, editableRef }: WrapRootProps) {
  useEditorChat(editableRef);
 
  return children;
}
 
export const AIKit = [
  AIChatTransportPlugin.extend(({ api, store }) => ({
    render: {
      useViewElementAttributes() {
        const key = usePluginStore(AIChatPlugin, (state) =>
          state.mode === 'insert' && state.previewValue.length > 0
            ? state._blockKey
            : null
        );
 
        return key
          ? [{ key, attributes: { 'data-editor-ai-preview-anchor': '' } }]
          : [];
      },
    },
    slots: {
      wrapNode: {
        component: AIInlinePreview,
        match: ({ editor, element }) => {
          const state = store.get();
          return (
            state.mode === 'insert' &&
            state.previewValue.length > 0 &&
            editor.key(element) === state._blockKey
          );
        },
      },
      afterContainer: AILoadingBar,
      caret: AIMenu,
      wrapRoot: AIIntegration,
    },
    shortcuts: {
      show: {
        keys: 'mod+j',
        handler: ({ editor }) => {
          editor.plugin(AIChatPlugin).api.show();
        },
      },
      stop: {
        keys: 'escape',
        handler: () => {
          const status = store.get().chat?.status;
          if (status !== 'streaming' && status !== 'submitted') return false;
          api.stop();
          return true;
        },
      },
    },
  })),
];
'use client';
 
import { BaseParagraphPlugin } from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import {
  useEditorSelector,
  usePluginStore,
  type RenderNodeWrapperProps,
  type WrapRootProps,
} from 'platejs/react';
 
import {
  AIChatEditor,
  AILoadingBar,
  AIMenu,
} from '@/components/editor/ai-menu';
 
import { AIChatTransportPlugin, useEditorChat } from './use-chat';
 
function AIInlinePreview({
  children,
  element









































































  • AIMenu: Floating command surface for prompts, tool shortcuts, and chat review.
  • AILoadingBar: Displays streaming status at the editor container.

Add kit

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




Render the editor

AIKit connects one chat session to each editor object. Render the editor inside EditorRoot; the kit owns transport and streaming cleanup independently of menu visibility.

import { EditorRoot, useCreateEditor } from 'platejs/react';
import { AIKit } from '@/components/editor/ai';
import { Editor, EditorContainer } from '@/components/editor/editor';
 
export function AIEditor() {
  const editor = useCreateEditor({ plugins: AIKit });
 
  return (
    <EditorRoot editor={editor}>
      <EditorContainer>
        <Editor />
      </EditorContainer>
    </EditorRoot>
  );
}

Views of the same editor share that session. A writable mounted view can continue streaming when a sibling detaches. The last view detaching aborts pending work. Put controlled readOnly state on each EditorRoot boundary and its Editor.

Add API route

Expose a streaming command endpoint that proxies your model provider:

import { createGateway } from '@ai-sdk/gateway';
import {
  type LanguageModel,
  type UIMessageStreamWriter,
  createUIMessageStream,
  createUIMessageStreamResponse,
  generateText,
  Output,
  streamText,
  tool,
} from 'ai';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { createEditor, nanoid } from 'platejs';
import {
  type AIChatRequestContext,
  type AIChatRequestRefs,
  resolveAIChatRequestContext,
} from
































































































































































































































































































































Configure credentials

For bring-your-own-key (BYOK) usage, enter your AI Gateway key in the editor settings or pass it as apiKey in the request body. The browser sends the caller's own key to the API route, which uses it for that request.

For a shared application credential, authenticate and authorize each request, enforce per-user usage limits, and load the key on the server. Keep that shared key out of client code and request bodies.

Manual usage

Installation

pnpm add platejs @ai-sdk/react ai fastest-levenshtein remark-parse remark-stringify unified
pnpm add platejs @ai-sdk/react ai fastest-levenshtein remark-parse remark-stringify unified

platejs supplies the editor and AI plugins.

Configure the kit

Copy the ai and use-chat components to configure transport, comment persistence, and rendering. The package owns streaming and session cleanup. Install AIKit, then configure its endpoint and presentation through AIChatTransportPlugin:

import { createEditor } from 'platejs/react';
import { AIKit } from '@/components/editor/ai';
import { AILoadingBar, AIMenu } from '@/components/editor/ai-menu';
import { AIChatTransportPlugin } from '@/components/editor/use-chat';
 
const editor = createEditor({
  plugins: [
    ...AIKit,
    AIChatTransportPlugin.configure({
      slots: {
        afterContainer: AILoadingBar,
        caret: AIMenu,
      },
      initialState: {
        chatOptions: {
          api: '/api/ai/command',
          body: { model: 'openai/gpt-4o-mini' },
        },



AIKit includes the Markdown dependency and the required React integration. Custom afterContainer and caret slots preserve the session. Replacing wrapRoot replaces its React attachment; compose the attachment inside your wrapper when customizing that slot. For AI comments, install DiscussionKit, create the editor with the current user as createEditor({ userId }), and configure CommentsPlugin with initialComments: { ranges, threads }, the thread rows from your tables and the ranges saved with the matching revision. AI comments are ordinary threads, so api.ranges() saves their ranges too. List aiUser from the copied use-chat among the comment users:

import { CommentsPlugin } from 'platejs/comments/react';
import { aiUser } from '@/components/editor/use-chat';
 
CommentsPlugin.configure({
  initialState: {
    initialComments: { ranges, threads },
    users: { ...users, [aiUser.id]: aiUser },
  },
});
import { CommentsPlugin } from 'platejs/comments/react';
import { aiUser } from '@/components/editor/use-chat';
 
CommentsPlugin.configure




The copied AIChatTransportPlugin sets authorId: aiUser.id, so AI comments and suggestions name the AI as their author. The copied use-chat creates each generated comment through a view with that author, with data.requestedBy set to the editor's user and data.model set to the model the route streams with that comment. The copied comment card lets the user in requestedBy resolve, reopen, edit and delete the AI's messages, as the thread's creator can for their own thread.

Completed generated comments publish directly as ordinary threads without an approval prompt. Configure authorization and canonical persistence through CommentsPlugin.configure({ initialState: { mutate } }); the integration awaits the durable mutation result before treating publication as successful. mutate receives the AI's ID as the thread's author, so check there that the signed-in user may publish as the AI. The draft acceptance controls for generated document edits do not gate comment publication. See Comments for persistence and mutation results.

Build API route

Handle editor.plugin(AIChatPlugin).api.submit requests on the server. Each request includes the chat messages from @ai-sdk/react and a ctx payload with children, selection and the last toolName. ctx.children holds the editor's children. A request from text in a board note holds only the note's blocks instead, with ctx.selection relative to the note, so a server editor without the board plugins loads it. A request made with a whole note selected still holds the board's shapes. Every request drops review marks from its blocks, so a pending change reaches the model as plain text. Complete API example

app/api/ai/command/route.ts
import { createGateway } from '@ai-sdk/gateway';
import { convertToModelMessages, streamText } from 'ai';
import { createEditor } from 'platejs';
 
import { BaseEditorKit } from '@/registry/components/editor/plugins-static';
 
export async function POST(req: Request) {
  const { apiKey: key, ctx, messages, model } = await req.json();
  const apiKey = typeof key === 'string' ? key.trim() 




















  • ctx.children and ctx.selection are rehydrated into a Plate editor so you can build rich prompts (see Prompt Templates).
  • Forward model settings through chatOptions.body. In the BYOK flow shown above, include the caller's own key as apiKey; the browser sends it in the JSON payload.
  • For a shared application key, the client sends session credentials or a short-lived authorization token. Authorize the request and load the shared provider key on the server instead of accepting it from the browser.
  • Return a streaming response so the kit can apply chunks incrementally.

Own the chat lifecycle

The copied use-chat implementation owns one SDK session and chunk consumer per editor object. It publishes the adapter through AIChatPlugin, checks writable view authority, and aborts requests when no writable view remains. Customize that implementation when integrating a provider; AIKit owns its React attachment.

'use client';
 
import { type UIMessage, DefaultChatTransport } from 'ai';
import { createEditorView, NodeApi } from 'platejs';
import { AIChatPlugin, useAIChat } from 'platejs/ai/react';
import type { CommentUser } from 'platejs/comments';
import { CommentsPlugin } from 'platejs/comments/react';
import { MarkdownPlugin } from 'platejs/markdown';
import { useEditor, usePluginStore } from 'platejs/react';
import * as React from 'react';
import { toast } from 'sonner';
 











































































































































































































The copied ai-menu item owns floating-menu anchoring for cursor, text, and block selections. Keep product-specific menu effects beside that component.

'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
























































































































































































































































































































































































































































































































































































































































































































































































































Now you can submit prompts programmatically:

editor.plugin(AIChatPlugin).api.submit('', {
  prompt: {
    default: 'Continue the document after {block}',
    selecting: 'Rewrite {selection} with a clearer tone',
  },
  toolName: 'generate',
});
editor.plugin(AIChatPlugin).api.submit('', {
  prompt: {
    default: 'Continue the document after {block}',
    selecting: 'Rewrite {selection} with a clearer tone',
  },

Prompt templates

Client prompting

  • aiChat.api.submit accepts an EditorPrompt: a string, a default/selecting/nodeSelecting object, or a function receiving { editor, isSelecting, isNodeSelecting }.
  • isSelecting reports whether the representative range is expanded. isNodeSelecting reports exact node membership and remains true for selected empty nodes whose representative range is collapsed. nodeSelecting takes precedence over selecting.
  • aiChat.read.prompt resolves that input for the current snapshot.
  • aiChat.read.resolvePlaceholders expands {editor}, {block}, {nodeSelection}, and {prompt} with snapshot Markdown, and leaves out content with no Markdown mapping.
  • When a prompt throws, aiChat.api.submit stops the running request and discards its draft, then lets the error reach the caller. No new request starts.
const aiChat = editor.plugin(AIChatPlugin);
const template = aiChat.read.resolvePlaceholders(
  'Rewrite {nodeSelection} using a friendly tone.'
);
 
aiChat.api.submit('Improve tone', {
  prompt: template,
  toolName: 'generate',
});
const aiChat = editor.plugin(AIChatPlugin);
const template = aiChat.read.resolvePlaceholders(
  'Rewrite {nodeSelection} using a friendly tone.'
);
 
aiChat.api.submit('Improve tone', {
  prompt: template,
  toolName: 'generate',
});

Server prompting

The demo backend in apps/www/src/app/api/ai/command reconstructs the editor from ctx and builds structured prompts:

  • getChooseToolPrompt decides whether the request is generate, edit, or comment.
  • getGeneratePrompt, getEditPrompt, and getCommentPrompt transform the current editor state into instructions tailored to each mode.
  • Server prompt helpers serialize explicit editor snapshots through editor.api.markdown.serialize and assemble <block ref="…"> references and <Selection> markers with buildStructuredPrompt.

Augment the payload you send from the client to fine-tune server prompts:

editor.plugin(AIChatTransportPlugin).store.set({
  chatOptions: {
    api: '/api/ai/command',
    body: {
      model: 'openai/gpt-4o-mini',
      tone: 'playful',
      temperature: 0.4,
    },
  },
});
editor.plugin(AIChatTransportPlugin).store.set({
  chatOptions: {
    api: '/api/ai/command',
    body: {
      model: 'openai/gpt-4o-mini',
      tone: 'playful',
      temperature: 0.4,
    },
  },
});

Everything under chatOptions.body arrives in the route handler, letting you swap providers, pass user-specific metadata, or branch into different prompt templates.

Keyboard shortcuts

KeyDescription
SpaceOpen the AI menu in an empty block (cursor mode)
Cmd + JShow the AI menu (set via shortcuts.show)
EscapeHide the AI menu and stop streaming

Streaming

Publish the accumulated Markdown response with aiChat.api.setPreview(content, { final, requestId }). The plugin parses it with the editor's installed Markdown mappings and stores the result in previewValue. With final: false, the parse uses { lossPolicy: 'allow', partial: true }: an unfinished trailing tag stays hidden and unsupported content previews as text. Bold, italic and strikethrough preview styled before their closing markers arrive. final defaults to true; that parse is strict, and a response that Markdown cannot represent clears the draft. Each parse, the final one included, continues the latest partial parse of the same response. After a final parse, hide(), reset(), reload() or submit(), the next parse starts over. stop() ends the request and publishes the current response as the final draft. hide(), reset() and reload() cancel it without publishing. useAIChat handles this publication for AI SDK transports. Structured table responses use aiChat.api.setTablePreview({ ref, content }, { requestId }). See Markdown streaming previews.

The draft does not modify the document, history, or editing mode. accept() applies it in one history batch. reset() drops it and restores the mapped invoking selection without reverting other edits. A deleted target cannot be replaced through its former path.

A chat edit skips the draft. With mode: 'chat' and toolName: 'edit', setPreview writes the response into the document as a suggestion, in Editing and Suggesting alike, and previewValue stays empty. useAIChat publishes it once the response finishes. The parse is strict, and a response that Markdown cannot represent withdraws the suggestion. accept() accepts it, and hide(), reset() and reload() withdraw it.

Open in New Tab
Loading…

Tracked AI edits

A draft keeps the current view's input policy. Accepting it in Editing writes ordinary content, and accepting it in Suggesting creates a native tracked edit for later review. A chat edit is a suggestion in either view, and accepting it decides that suggestion. Streaming does not create suggestions or change the mode.

The authorId state, such as 'ai', writes these edits under the AI's own name. A suggestion the AI writes is then a proposal by that author, and accept() and the withdrawals above run through a view with that author. With authorId: null, the default, the AI writes as the editor's user. The copied AIChatTransportPlugin sets it to aiUser.id; configure it yourself when you install AIChatPlugin without that item:

AIChatPlugin.configure({ initialState: { authorId: 'ai' } });
AIChatPlugin.configure({ initialState: { authorId: 'ai' } });

Copilot ghost text also stays temporary until accepted.

Plate Plus

Combobox menu with free-form prompt input

  • Additional trigger methods:
    • Block menu button
    • Slash command menu
  • Beautifully crafted UI
Get the code

API Reference

AIChatPlugin

Main plugin that powers the AI menu, chat state, and transforms.

Options

    Character(s) that open the command menu. Defaults to ' '.

    Pattern that must match the character before the trigger. Defaults to /^\s?$/.

    Return false to cancel opening in specific contexts.

    Author of the AI's document writes: its suggestions, the output it inserts or replaces, and its acceptances and withdrawals of its own suggestions. null writes them as the editor's user. Defaults to null.

    Current messages, status, error, and controls published by useAIChat (managed internally).

    Node snapshots paired with editor-scoped node keys for native authored replacements (managed internally).

    Selection captured before submitting a prompt (managed internally).

    'insert' shows the draft after the invoking block, and 'chat' shows it in the review menu. In 'chat' mode the edit tool writes a suggestion into the document instead of a draft. Defaults to 'insert'.

    Whether the AI menu is visible. Defaults to false.

    Generated preview nodes parsed by the editor session for insert and replace commands (managed internally).

    True while a response is streaming. Defaults to false.

    Active tool used to interpret the response.

editor.plugin(AIChatPlugin).api.submit(input, options?)

Submits a prompt to your model provider. When mode is omitted it defaults to 'insert' for a collapsed cursor and 'chat' otherwise.

Parameters

    Raw input from the user.

    Fine-tune submission behaviour.

Optionsobject

    Override the response mode.

    Forwarded to chat.sendMessage (model, headers, etc.).

    String, config, or function resolved against the current editor snapshot.

    Tags the submission so hooks can react differently.

editor.plugin(AIChatPlugin).api.reset()

Stops the request, clears the draft and chat state, and restores the mapped invoking selection when its target still exists in a writable view. It withdraws a chat edit's suggestion. It does not undo other edits or decide other suggestions.

editor.read.aiChat.node(options?)

Retrieves the source block anchoring the current AI draft.

Parameters

    Set streaming: true to retrieve the source block while a response is streaming.

ReturnsNodeEntry | undefined

    Matching node entry, if found.

editor.plugin(AIChatPlugin).api.reload()

Replays the last prompt using the stored chat adapter, restoring the original selection or block selection before resubmitting.

editor.plugin(AIChatPlugin).api.stop()

Stops generation, publishes all received text, and keeps the partial draft available for review.

editor.plugin(AIChatPlugin).api.show()

Opens the AI menu, clears previous chat messages, and resets tool state. Inside a non-empty block, a collapsed caret selects that block for editing. At the block end or in an empty block, the caret remains an insertion target. The session retains this target through submission and retry.

editor.plugin(AIChatPlugin).api.hide(options?)

Closes the AI menu, stops its request, and discards the unapplied draft or withdraws a chat edit's suggestion. Nothing else in the document changes. Use stop() to pause generation while keeping the partial response available for review.

Parameters

    Set focus: false to keep focus outside the editor.

editor.plugin(AIChatPlugin).api.accept()

Applies the current draft as one reversible edit under the current editing mode, or accepts a chat edit's suggestion.

editor.plugin(AIChatPlugin).api.insertBelow(options?)

Inserts the draft below the captured selection in one history batch. After a chat edit's suggestion, it first withdraws the suggestion in a batch of its own, then inserts the response below its target, so undo takes two steps. After a table-cell edit, it inserts nothing.

Parameters

    Copy formatting from the source selection. Defaults to 'single'.

editor.plugin(AIChatPlugin).api.replaceSelection(options?)

Replaces the mapped selection with the draft in one history batch.

Parameters

    Controls how much formatting from the original selection should be applied.

Registry chat preview

AIChatEditor renders previewValue as the document of a static preview editor, with purple draft text and a trailing stream indicator; the preview editor itself is never edited. Insert mode places it after the invoking block; chat mode places it in the review menu. Both use the same draft and acceptance actions. A chat edit shows no preview, because its suggestion is already in the document. The package parses Markdown using the editor's installed plugins, so applying a draft also works without a mounted preview component.

'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
  NodeApi,
  RangeApi,
  TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
  useCreateEditor,
  useEditorSelector,
  useFocusedLast,
  usePluginStore,
  type Editor,
  useEditor,
} from 'platejs/react';
import * as React from 'react';
 
import { Button } from '@/components/ui/button';
import {
  Command,
  CommandGroup,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import {
  FloatingPopover,
  FloatingPopoverAnchor,
  FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
 
import { EditorStatic } from './editor-static';
 
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
  decorate: {
    // The end marker sits on the draft's last text, so only the last block
    // decorates. Only the last character carries it, so it stays one element
    // when other decorations, such as code highlighting, split that text.
    read: ({ editor, entry: [node, path] }) => {
      if (path.length !== 1 || node !== editor.read.children().at(-1)) {
        return [];
      }
 
      const [last, lastPath] = NodeApi.last(node, []);
 
      if (!TextApi.isText(last) || last.text.length === 0) return [];
 
      const textPath = [...path, ...lastPath];
      const end = last.text.length;
      // The last code point: a surrogate pair is two UTF-16 units.
      const start =
        end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
 
      return [
        {
          key: 'ai-preview-end',
          range: {
            anchor: { path: textPath, offset: start },
            focus: { path: textPath, offset: end },
          },
          attributes: { 'data-editor-ai-end': '' },
        },
      ];
    },
  },
});
 
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
  const scrollElement = editor.api.dom.scroll();
  const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
  if (!scrollElement || !target) return;
 
  const scrollBounds = scrollElement.getBoundingClientRect();
  const targetBounds = target.getBoundingClientRect();
 
  scrollElement.scrollTop +=
    targetBounds.top +
    targetBounds.height / 2 -
    (scrollBounds.top + scrollBounds.height / 2);
};
 
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
  const editor = useEditor();
  const draftRef = React.useRef<HTMLDivElement>(null);
  // Supplies the preview plugins; the draft renders as its document.
  const aiEditor = useCreateEditor({
    plugins: [...BaseEditorKit, AIPreviewEndPlugin],
  });
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  // Renders the latest draft when rendering falls behind the stream,
  // skipping drafts that were never shown.
  const previewDocument = React.useDeferredValue(
    React.useMemo(
      () => (previewValue.length > 0 ? { children: previewValue } : undefined),
      [previewValue]
    )
  );
 
  // The draft resizes as it streams. Scrolling from the resize callback reads
  // layout the browser has already computed, rather than forcing it after
  // every render.
  React.useEffect(() => {
    const draft = draftRef.current;
    const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
    if (!inline || !draft || !Observer) return undefined;
 
    const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
    observer.observe(draft);
 
    return () => observer.disconnect();
  }, [editor, inline]);
 
  const last = previewDocument
    ? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
    : null;
 
  // Rendering reads every block's decorations, so the preview renders only
  // when its document or appearance changes, not on each update's urgent pass.
  const preview = React.useMemo(
    () => (
      <EditorStatic
        variant={inline ? 'none' : 'aiChat'}
        document={previewDocument}
        editor={aiEditor}
        className={cn(
          '[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
          streaming &&
            '[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
        )}
      />
    ),
    [aiEditor, inline, previewDocument, streaming]
  );
 
  const endWithoutText =
    streaming && (!last || !TextApi.isText(last) || !last.text);
 
  return (
    <div ref={draftRef} data-editor-ai-draft="">
      {preview}
      {/* Stays mounted: adding or removing it flips whether the preview is
          the last child, and `:last-child` descendant rules then restyle the
          whole preview. */}
      <span
        data-editor-ai-end={endWithoutText ? '' : undefined}
        className={cn(
          'size-3 rounded-full bg-purple-600 align-middle',
          endWithoutText ? 'inline-block' : 'hidden'
        )}
      />
    </div>
  );
}
 
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
  const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
 
  return block && ElementApi.isElement(block[0])
    ? editor.api.dom.resolveDOMNode(block[0])
    : null;
};
 
export function AIMenu() {
  const editor = useEditor();
  const { api, read } = useEditor().plugin(AIChatPlugin);
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
 
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  const editAnchorKey = useEditorSelector((innerEditor) => {
    const entry = innerEditor.read.selection.nodes().at(-1);
 
    return entry && ElementApi.isElement(entry[0])
      ? innerEditor.key(entry[0])
      : null;
  });
  const isFocusedLast = useFocusedLast();
  const chatOpen = usePluginStore(AIChatPlugin, 'open');
  const open = chatOpen && isFocusedLast;
  const [value, setValue] = React.useState('');
 
  const [input, setInput] = React.useState('');
 
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
 
  const messages = chat?.messages;
  const status = chat?.status ?? 'ready';
  const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
    null
  );
 
  React.useEffect(() => {
    if (!streaming && previewValue.length === 0) return undefined;
 
    const anchorEntry = read.node();
    if (!anchorEntry) return undefined;
 
    const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
    if (!anchorDom) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(
        anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
          anchorDom
      );
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editor, previewValue, read, streaming]);
 
  const setOpen = (innerOpen: boolean) => {
    if (innerOpen) {
      if (!chatOpen) api.show();
    } else if (chatOpen) {
      api.hide({ focus: false });
    }
  };
 
  React.useEffect(() => {
    if (!chatOpen) {
      const animationFrame = window.requestAnimationFrame(() => {
        setAnchorElement(null);
        setInput('');
      });
 
      return () => {
        window.cancelAnimationFrame(animationFrame);
      };
    }
 
    const nextAnchor = resolveSelectionAnchor(editor);
 
    if (!nextAnchor) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [chatOpen, editor]);
 
  const children = useEditorSelector((innerEditor) =>
    chatOpen ? innerEditor.read.children() : null
  );
 
  React.useEffect(() => {
    if (!chatOpen || !anchorElement) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      if (anchorElement.isConnected) return;
 
      const nextAnchor = resolveSelectionAnchor(editor);
 
      if (nextAnchor) setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [anchorElement, chatOpen, children, editor]);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  React.useEffect(() => {
    if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
 
    let anchorNode = editAnchorKey
      ? editor.read.nodes.get(editAnchorKey, {
          match: ElementApi.isElement,
        })
      : undefined;
 
    if (!anchorNode) {
      anchorNode =
        editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
    }
 
    if (!anchorNode) return undefined;
 
    const block = editor.read.nodes.block({ at: anchorNode[1] });
    const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
 
    if (!domNode) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(domNode);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editAnchorKey, editor, isLoading, mode, toolName]);
 
  if (isLoading && mode === 'insert') return null;
 
  if (toolName === 'comment') return null;
 
  if (!anchorElement) return null;
 
  return (
    <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
      <FloatingPopoverAnchor element={anchorElement} />
 
      <FloatingPopoverContent
        className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
        onEscapeKeyDown={(e) => {
          e.preventDefault();
 
          api.hide();
        }}
        align="center"
        side="bottom"
      >
        <Command
          className="w-full rounded-lg border shadow-md"
          value={value}
          onValueChange={setValue}
        >
          {mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
 
          {isLoading ? (
            <div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
              <Loader2Icon className="size-4 animate-spin" />
              {(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
            </div>
          ) : (
            <CommandPrimitive.Input
              className={cn(
                'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
                'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
                'border-b focus-visible:ring-transparent'
              )}
              value={input}
              onKeyDown={(e) => {
                if (isHotkey('backspace')(e) && input.length === 0) {
                  e.preventDefault();
                  api.hide();
                }
                if (isHotkey('enter')(e) && !e.shiftKey && !value) {
                  e.preventDefault();
                  api.submit(input);
                  setInput('');
                }
              }}
              onValueChange={setInput}
              placeholder="Ask AI anything..."
              data-editor-keep-selection-visible
              autoFocus
            />
          )}
 
          {!isLoading && (
            <CommandList>
              <AIMenuItems
                input={input}
                setInput={setInput}
                setValue={setValue}
              />
            </CommandList>
          )}
        </Command>
      </FloatingPopoverContent>
    </FloatingPopover>
  );
}
 
type EditorChatState =
  | 'cursorCommand'
  | 'cursorSuggestion'
  | 'selectionCommand'
  | 'selectionSuggestion';
 
const AICommentIcon = () => (
  <svg
    fill="none"
    height="24"
    stroke="currentColor"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth="2"
    viewBox="0 0 24 24"
    width="24"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path d="M0 0h24v24H0z" fill="none" stroke="none" />
    <path d="M8 9h8" />
    <path d="M8 13h4.5" />
    <path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
    <path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
  </svg>
);
 
const focusEditorOnceClosed = (editor: Editor) => {
  if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
 
const aiChatItems = {
  accept: {
    icon: <Check />,
    label: 'Accept',
    value: 'accept',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.accept();
      focusEditorOnceClosed(editor);
    },
  },
  comment: {
    icon: <AICommentIcon />,
    label: 'Comment',
    value: 'comment',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt:
          'Please comment on the following content and provide reasonable and meaningful feedback.',
        toolName: 'comment',
      });
    },
  },
  continueWrite: {
    icon: <PenLine />,
    label: 'Continue writing',
    value: 'continueWrite',
    onSelect: ({ editor, input }) => {
      const ancestorNode = editor.read.nodes.block();
 
      if (!ancestorNode) return;
 
      const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
 
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: isEmpty
          ? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
          : `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
        toolName: 'generate',
      });
    },
  },
  discard: {
    icon: <X />,
    label: 'Discard',
    shortcut: 'Escape',
    value: 'discard',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.hide();
    },
  },
  emojify: {
    icon: <SmileIcon />,
    label: 'Emojify',
    value: 'emojify',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
        toolName: 'edit',
      });
    },
  },
  explain: {
    icon: <BadgeHelp />,
    label: 'Explain',
    value: 'explain',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: {
          default: 'Explain {editor}',
          selecting: 'Explain',
        },
        toolName: 'generate',
      });
    },
  },
  fixSpelling: {
    icon: <Check />,
    label: 'Fix spelling & grammar',
    value: 'fixSpelling',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
        toolName: 'edit',
      });
    },
  },
  generateMarkdownSample: {
    icon: <BookOpenCheck />,
    label: 'Generate Markdown sample',
    value: 'generateMarkdownSample',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: 'Generate a markdown sample',
        toolName: 'generate',
      });
    },
  },
  improveWriting: {
    icon: <Wand />,
    label: 'Improve writing',
    value: 'improveWriting',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Improve the writing for clarity and flow, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  insertBelow: {
    icon: <ListEnd />,
    label: 'Insert below',
    value: 'insertBelow',
    onSelect: ({ editor }) => {
      /** Format: 'none' Fix insert table */
      editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
      focusEditorOnceClosed(editor);
    },
  },
  makeLonger: {
    icon: <ListPlus />,
    label: 'Make longer',
    value: 'makeLonger',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  makeShorter: {
    icon: <ListMinus />,
    label: 'Make shorter',
    value: 'makeShorter',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
        toolName: 'edit',
      });
    },
  },
  replace: {
    icon: <Check />,
    label: 'Replace selection',
    value: 'replace',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.replaceSelection();
      focusEditorOnceClosed(editor);
    },
  },
  simplifyLanguage: {
    icon: <FeatherIcon />,
    label: 'Simplify language',
    value: 'simplifyLanguage',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  summarize: {
    icon: <Album />,
    label: 'Add a summary',
    value: 'summarize',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: {
          default: 'Summarize {editor}',
          selecting: 'Summarize',
        },
        toolName: 'generate',
      });
    },
  },
  tryAgain: {
    icon: <CornerUpLeft />,
    label: 'Try again',
    value: 'tryAgain',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.reload();
    },
  },
} satisfies Record<
  string,
  {
    icon: React.ReactNode;
    label: string;
    value: string;
    component?: React.ComponentType<{ menuState: EditorChatState }>;
    filterItems?: boolean;
    items?: Array<{ label: string; value: string }>;
    shortcut?: string;
    onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
  }
>;
 
const menuStateItems: Record<
  EditorChatState,
  Array<{
    items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
    heading?: string;
  }>
> = {
  cursorCommand: [
    {
      items: [
        aiChatItems.comment,
        aiChatItems.generateMarkdownSample,
        aiChatItems.continueWrite,
        aiChatItems.summarize,
        aiChatItems.explain,
      ],
    },
  ],
  cursorSuggestion: [
    {
      items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
    },
  ],
  selectionCommand: [
    {
      items: [
        aiChatItems.improveWriting,
        aiChatItems.comment,
        aiChatItems.emojify,
        aiChatItems.makeLonger,
        aiChatItems.makeShorter,
        aiChatItems.fixSpelling,
        aiChatItems.simplifyLanguage,
      ],
    },
  ],
  selectionSuggestion: [
    {
      items: [
        aiChatItems.accept,
        aiChatItems.discard,
        aiChatItems.insertBelow,
        aiChatItems.tryAgain,
      ],
    },
  ],
};
 
export const AIMenuItems = ({
  input,
  setInput,
  setValue,
}: {
  input: string;
  setInput: (value: string) => void;
  setValue: (value: string) => void;
}) => {
  const editor = useEditor();
  const comments = editor.plugin(CommentsPlugin);
  const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
  const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
  const isSelecting =
    chatNodeMode !== null ||
    (!!chatSelection && RangeApi.isExpanded(chatSelection));
 
  const menuState: EditorChatState =
    (messages?.length ?? 0) > 0
      ? mode === 'chat'
        ? 'selectionSuggestion'
        : 'cursorSuggestion'
      : isSelecting
        ? 'selectionCommand'
        : 'cursorCommand';
  const menuGroups = comments.installed
    ? menuStateItems[menuState]
    : menuStateItems[menuState].map((group) => ({
        ...group,
        items: group.items.filter((item) => item !== aiChatItems.comment),
      }));
  const firstItemValue = menuGroups[0]?.items[0]?.value;
 
  React.useEffect(() => {
    if (firstItemValue) setValue(firstItemValue);
  }, [firstItemValue, setValue]);
 
  return (
    <>
      {menuGroups.map((group) => (
        <CommandGroup
          key={group.heading ?? group.items[0]?.value}
          heading={group.heading}
        >
          {group.items.map((menuItem) => (
            <CommandItem
              key={menuItem.value}
              className="[&_svg]:text-muted-foreground"
              value={menuItem.value}
              onSelect={() => {
                menuItem.onSelect?.({ editor, input });
                setInput('');
              }}
            >
              {menuItem.icon}
              <span>{menuItem.label}</span>
            </CommandItem>
          ))}
        </CommandGroup>
      ))}
    </>
  );
};
 
export function AILoadingBar() {
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const mode = usePluginStore(AIChatPlugin, 'mode');
 
  const status = chat?.status ?? 'ready';
 
  const { api } = useEditor().plugin(AIChatPlugin);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  if (isLoading && (mode === 'insert' || toolName === 'comment')) {
    return (
      <div
        className={cn(
          'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
        )}
      >
        <span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
        <span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
        <Button
          size="sm"
          variant="ghost"
          className="flex items-center gap-1 text-xs"
          onKeyDown={(event) => {
            if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
            event.preventDefault();
            event.stopPropagation();
            api.stop();
          }}
          onClick={() => {
            api.stop();
          }}
        >
          <PauseIcon className="h-4 w-4" />
          Stop
          <kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
            Esc
          </kbd>
        </Button>
      </div>
    );
  }
 
  if (toolName === 'comment' && status === 'error') {
    return (
      <div
        className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
        data-ai-comment-error=""
        data-editor-keep-selection-visible
      >
        <p className="w-full px-1 text-destructive" role="alert">
          Could not generate comments.
        </p>
        <Button onClick={() => api.reload()} size="sm" variant="outline">
          Try again
        </Button>
        <Button onClick={() => api.hide()} size="sm" variant="outline">
          <X data-icon="inline-start" />
          Dismiss
        </Button>
      </div>
    );
  }
 
  return null;
}
'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
  NodeApi,























































































































































































































































































































































































































































































































































































































































































































































































































useAIChat

Connects a shared AI SDK transport to an editor's mounted views. The hook owns draft publication and request cancellation. It returns void.

import { DefaultChatTransport } from 'ai';
import { AIChatPlugin, useAIChat } from 'platejs/ai/react';
 
const CustomAIChatPlugin = AIChatPlugin.extend(() => {
  const transport = new DefaultChatTransport({ api: '/api/ai/command' });
 
  return {
    slots: {
      wrapRoot: function ChatIntegration({ children, editableRef }) {
        useAIChat({ editableRef, transport });
        return children;
      },
    },
  };
});
import { DefaultChatTransport } from 'ai';
import { AIChatPlugin, useAIChat } from 'platejs/ai/react';
 
const CustomAIChatPlugin = AIChatPlugin.extend(() => {
  const transport = new DefaultChatTransport({ api: '/api/ai/command' });
 
  return {
    slots: {
      wrapRoot: function ChatIntegration({ children, editableRef }) {
        useAIChat({ editableRef, transport });
        return children;
      },
    },
  };
});

Share the transport between views of one editor. Replacing it cancels the previous request. The last view detaching or the editor becoming read-only also cancels pending work. A stopped request cannot write after a view is remounted.

Parameters

    The view's editable root.

    The application's shared AI SDK transport.

    Handles application data such as comment persistence. Check signal.aborted after asynchronous work before applying its result.

The copied use-chat component keeps endpoint/body settings and comment persistence local. Production transports report HTTP errors; documentation demos provide sample responses from their own server endpoints.

AI chat capabilities

Use the installed plugin for AI Chat services, snapshot reads, and updates:

const aiChat = editor.plugin(AIChatPlugin);
 
const prompt = aiChat.read.prompt({ prompt: 'Improve this' });
aiChat.api.setPreview(accumulatedMarkdown);
const aiChat = editor.plugin(AIChatPlugin);
 
const prompt = aiChat.read.prompt({ prompt: 'Improve this' });
aiChat.api.setPreview(accumulatedMarkdown);
NamespaceMethods
aiChat.apiaccept, setPreview, setTablePreview, hide, insertBelow, reload, replaceSelection, reset, show, stop, submit
aiChat.readcommentRange, insertStart, markdown, node, prompt, resolvePlaceholders
aiChat.store.getlastAssistantMessage

Customization

Adding custom AI commands

'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
  NodeApi,
  RangeApi,
  TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
  useCreateEditor,
  useEditorSelector,
  useFocusedLast,
  usePluginStore,
  type Editor,
  useEditor,
} from 'platejs/react';
import * as React from 'react';
 
import { Button } from '@/components/ui/button';
import {
  Command,
  CommandGroup,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import {
  FloatingPopover,
  FloatingPopoverAnchor,
  FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
 
import { EditorStatic } from './editor-static';
 
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
  decorate: {
    // The end marker sits on the draft's last text, so only the last block
    // decorates. Only the last character carries it, so it stays one element
    // when other decorations, such as code highlighting, split that text.
    read: ({ editor, entry: [node, path] }) => {
      if (path.length !== 1 || node !== editor.read.children().at(-1)) {
        return [];
      }
 
      const [last, lastPath] = NodeApi.last(node, []);
 
      if (!TextApi.isText(last) || last.text.length === 0) return [];
 
      const textPath = [...path, ...lastPath];
      const end = last.text.length;
      // The last code point: a surrogate pair is two UTF-16 units.
      const start =
        end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
 
      return [
        {
          key: 'ai-preview-end',
          range: {
            anchor: { path: textPath, offset: start },
            focus: { path: textPath, offset: end },
          },
          attributes: { 'data-editor-ai-end': '' },
        },
      ];
    },
  },
});
 
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
  const scrollElement = editor.api.dom.scroll();
  const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
  if (!scrollElement || !target) return;
 
  const scrollBounds = scrollElement.getBoundingClientRect();
  const targetBounds = target.getBoundingClientRect();
 
  scrollElement.scrollTop +=
    targetBounds.top +
    targetBounds.height / 2 -
    (scrollBounds.top + scrollBounds.height / 2);
};
 
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
  const editor = useEditor();
  const draftRef = React.useRef<HTMLDivElement>(null);
  // Supplies the preview plugins; the draft renders as its document.
  const aiEditor = useCreateEditor({
    plugins: [...BaseEditorKit, AIPreviewEndPlugin],
  });
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  // Renders the latest draft when rendering falls behind the stream,
  // skipping drafts that were never shown.
  const previewDocument = React.useDeferredValue(
    React.useMemo(
      () => (previewValue.length > 0 ? { children: previewValue } : undefined),
      [previewValue]
    )
  );
 
  // The draft resizes as it streams. Scrolling from the resize callback reads
  // layout the browser has already computed, rather than forcing it after
  // every render.
  React.useEffect(() => {
    const draft = draftRef.current;
    const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
    if (!inline || !draft || !Observer) return undefined;
 
    const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
    observer.observe(draft);
 
    return () => observer.disconnect();
  }, [editor, inline]);
 
  const last = previewDocument
    ? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
    : null;
 
  // Rendering reads every block's decorations, so the preview renders only
  // when its document or appearance changes, not on each update's urgent pass.
  const preview = React.useMemo(
    () => (
      <EditorStatic
        variant={inline ? 'none' : 'aiChat'}
        document={previewDocument}
        editor={aiEditor}
        className={cn(
          '[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
          streaming &&
            '[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
        )}
      />
    ),
    [aiEditor, inline, previewDocument, streaming]
  );
 
  const endWithoutText =
    streaming && (!last || !TextApi.isText(last) || !last.text);
 
  return (
    <div ref={draftRef} data-editor-ai-draft="">
      {preview}
      {/* Stays mounted: adding or removing it flips whether the preview is
          the last child, and `:last-child` descendant rules then restyle the
          whole preview. */}
      <span
        data-editor-ai-end={endWithoutText ? '' : undefined}
        className={cn(
          'size-3 rounded-full bg-purple-600 align-middle',
          endWithoutText ? 'inline-block' : 'hidden'
        )}
      />
    </div>
  );
}
 
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
  const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
 
  return block && ElementApi.isElement(block[0])
    ? editor.api.dom.resolveDOMNode(block[0])
    : null;
};
 
export function AIMenu() {
  const editor = useEditor();
  const { api, read } = useEditor().plugin(AIChatPlugin);
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
 
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  const editAnchorKey = useEditorSelector((innerEditor) => {
    const entry = innerEditor.read.selection.nodes().at(-1);
 
    return entry && ElementApi.isElement(entry[0])
      ? innerEditor.key(entry[0])
      : null;
  });
  const isFocusedLast = useFocusedLast();
  const chatOpen = usePluginStore(AIChatPlugin, 'open');
  const open = chatOpen && isFocusedLast;
  const [value, setValue] = React.useState('');
 
  const [input, setInput] = React.useState('');
 
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
 
  const messages = chat?.messages;
  const status = chat?.status ?? 'ready';
  const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
    null
  );
 
  React.useEffect(() => {
    if (!streaming && previewValue.length === 0) return undefined;
 
    const anchorEntry = read.node();
    if (!anchorEntry) return undefined;
 
    const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
    if (!anchorDom) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(
        anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
          anchorDom
      );
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editor, previewValue, read, streaming]);
 
  const setOpen = (innerOpen: boolean) => {
    if (innerOpen) {
      if (!chatOpen) api.show();
    } else if (chatOpen) {
      api.hide({ focus: false });
    }
  };
 
  React.useEffect(() => {
    if (!chatOpen) {
      const animationFrame = window.requestAnimationFrame(() => {
        setAnchorElement(null);
        setInput('');
      });
 
      return () => {
        window.cancelAnimationFrame(animationFrame);
      };
    }
 
    const nextAnchor = resolveSelectionAnchor(editor);
 
    if (!nextAnchor) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [chatOpen, editor]);
 
  const children = useEditorSelector((innerEditor) =>
    chatOpen ? innerEditor.read.children() : null
  );
 
  React.useEffect(() => {
    if (!chatOpen || !anchorElement) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      if (anchorElement.isConnected) return;
 
      const nextAnchor = resolveSelectionAnchor(editor);
 
      if (nextAnchor) setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [anchorElement, chatOpen, children, editor]);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  React.useEffect(() => {
    if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
 
    let anchorNode = editAnchorKey
      ? editor.read.nodes.get(editAnchorKey, {
          match: ElementApi.isElement,
        })
      : undefined;
 
    if (!anchorNode) {
      anchorNode =
        editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
    }
 
    if (!anchorNode) return undefined;
 
    const block = editor.read.nodes.block({ at: anchorNode[1] });
    const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
 
    if (!domNode) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(domNode);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editAnchorKey, editor, isLoading, mode, toolName]);
 
  if (isLoading && mode === 'insert') return null;
 
  if (toolName === 'comment') return null;
 
  if (!anchorElement) return null;
 
  return (
    <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
      <FloatingPopoverAnchor element={anchorElement} />
 
      <FloatingPopoverContent
        className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
        onEscapeKeyDown={(e) => {
          e.preventDefault();
 
          api.hide();
        }}
        align="center"
        side="bottom"
      >
        <Command
          className="w-full rounded-lg border shadow-md"
          value={value}
          onValueChange={setValue}
        >
          {mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
 
          {isLoading ? (
            <div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
              <Loader2Icon className="size-4 animate-spin" />
              {(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
            </div>
          ) : (
            <CommandPrimitive.Input
              className={cn(
                'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
                'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
                'border-b focus-visible:ring-transparent'
              )}
              value={input}
              onKeyDown={(e) => {
                if (isHotkey('backspace')(e) && input.length === 0) {
                  e.preventDefault();
                  api.hide();
                }
                if (isHotkey('enter')(e) && !e.shiftKey && !value) {
                  e.preventDefault();
                  api.submit(input);
                  setInput('');
                }
              }}
              onValueChange={setInput}
              placeholder="Ask AI anything..."
              data-editor-keep-selection-visible
              autoFocus
            />
          )}
 
          {!isLoading && (
            <CommandList>
              <AIMenuItems
                input={input}
                setInput={setInput}
                setValue={setValue}
              />
            </CommandList>
          )}
        </Command>
      </FloatingPopoverContent>
    </FloatingPopover>
  );
}
 
type EditorChatState =
  | 'cursorCommand'
  | 'cursorSuggestion'
  | 'selectionCommand'
  | 'selectionSuggestion';
 
const AICommentIcon = () => (
  <svg
    fill="none"
    height="24"
    stroke="currentColor"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth="2"
    viewBox="0 0 24 24"
    width="24"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path d="M0 0h24v24H0z" fill="none" stroke="none" />
    <path d="M8 9h8" />
    <path d="M8 13h4.5" />
    <path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
    <path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
  </svg>
);
 
const focusEditorOnceClosed = (editor: Editor) => {
  if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
 
const aiChatItems = {
  accept: {
    icon: <Check />,
    label: 'Accept',
    value: 'accept',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.accept();
      focusEditorOnceClosed(editor);
    },
  },
  comment: {
    icon: <AICommentIcon />,
    label: 'Comment',
    value: 'comment',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt:
          'Please comment on the following content and provide reasonable and meaningful feedback.',
        toolName: 'comment',
      });
    },
  },
  continueWrite: {
    icon: <PenLine />,
    label: 'Continue writing',
    value: 'continueWrite',
    onSelect: ({ editor, input }) => {
      const ancestorNode = editor.read.nodes.block();
 
      if (!ancestorNode) return;
 
      const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
 
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: isEmpty
          ? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
          : `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
        toolName: 'generate',
      });
    },
  },
  discard: {
    icon: <X />,
    label: 'Discard',
    shortcut: 'Escape',
    value: 'discard',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.hide();
    },
  },
  emojify: {
    icon: <SmileIcon />,
    label: 'Emojify',
    value: 'emojify',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
        toolName: 'edit',
      });
    },
  },
  explain: {
    icon: <BadgeHelp />,
    label: 'Explain',
    value: 'explain',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: {
          default: 'Explain {editor}',
          selecting: 'Explain',
        },
        toolName: 'generate',
      });
    },
  },
  fixSpelling: {
    icon: <Check />,
    label: 'Fix spelling & grammar',
    value: 'fixSpelling',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
        toolName: 'edit',
      });
    },
  },
  generateMarkdownSample: {
    icon: <BookOpenCheck />,
    label: 'Generate Markdown sample',
    value: 'generateMarkdownSample',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: 'Generate a markdown sample',
        toolName: 'generate',
      });
    },
  },
  improveWriting: {
    icon: <Wand />,
    label: 'Improve writing',
    value: 'improveWriting',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Improve the writing for clarity and flow, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  insertBelow: {
    icon: <ListEnd />,
    label: 'Insert below',
    value: 'insertBelow',
    onSelect: ({ editor }) => {
      /** Format: 'none' Fix insert table */
      editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
      focusEditorOnceClosed(editor);
    },
  },
  makeLonger: {
    icon: <ListPlus />,
    label: 'Make longer',
    value: 'makeLonger',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  makeShorter: {
    icon: <ListMinus />,
    label: 'Make shorter',
    value: 'makeShorter',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
        toolName: 'edit',
      });
    },
  },
  replace: {
    icon: <Check />,
    label: 'Replace selection',
    value: 'replace',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.replaceSelection();
      focusEditorOnceClosed(editor);
    },
  },
  simplifyLanguage: {
    icon: <FeatherIcon />,
    label: 'Simplify language',
    value: 'simplifyLanguage',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  summarize: {
    icon: <Album />,
    label: 'Add a summary',
    value: 'summarize',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: {
          default: 'Summarize {editor}',
          selecting: 'Summarize',
        },
        toolName: 'generate',
      });
    },
  },
  tryAgain: {
    icon: <CornerUpLeft />,
    label: 'Try again',
    value: 'tryAgain',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.reload();
    },
  },
} satisfies Record<
  string,
  {
    icon: React.ReactNode;
    label: string;
    value: string;
    component?: React.ComponentType<{ menuState: EditorChatState }>;
    filterItems?: boolean;
    items?: Array<{ label: string; value: string }>;
    shortcut?: string;
    onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
  }
>;
 
const menuStateItems: Record<
  EditorChatState,
  Array<{
    items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
    heading?: string;
  }>
> = {
  cursorCommand: [
    {
      items: [
        aiChatItems.comment,
        aiChatItems.generateMarkdownSample,
        aiChatItems.continueWrite,
        aiChatItems.summarize,
        aiChatItems.explain,
      ],
    },
  ],
  cursorSuggestion: [
    {
      items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
    },
  ],
  selectionCommand: [
    {
      items: [
        aiChatItems.improveWriting,
        aiChatItems.comment,
        aiChatItems.emojify,
        aiChatItems.makeLonger,
        aiChatItems.makeShorter,
        aiChatItems.fixSpelling,
        aiChatItems.simplifyLanguage,
      ],
    },
  ],
  selectionSuggestion: [
    {
      items: [
        aiChatItems.accept,
        aiChatItems.discard,
        aiChatItems.insertBelow,
        aiChatItems.tryAgain,
      ],
    },
  ],
};
 
export const AIMenuItems = ({
  input,
  setInput,
  setValue,
}: {
  input: string;
  setInput: (value: string) => void;
  setValue: (value: string) => void;
}) => {
  const editor = useEditor();
  const comments = editor.plugin(CommentsPlugin);
  const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
  const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
  const isSelecting =
    chatNodeMode !== null ||
    (!!chatSelection && RangeApi.isExpanded(chatSelection));
 
  const menuState: EditorChatState =
    (messages?.length ?? 0) > 0
      ? mode === 'chat'
        ? 'selectionSuggestion'
        : 'cursorSuggestion'
      : isSelecting
        ? 'selectionCommand'
        : 'cursorCommand';
  const menuGroups = comments.installed
    ? menuStateItems[menuState]
    : menuStateItems[menuState].map((group) => ({
        ...group,
        items: group.items.filter((item) => item !== aiChatItems.comment),
      }));
  const firstItemValue = menuGroups[0]?.items[0]?.value;
 
  React.useEffect(() => {
    if (firstItemValue) setValue(firstItemValue);
  }, [firstItemValue, setValue]);
 
  return (
    <>
      {menuGroups.map((group) => (
        <CommandGroup
          key={group.heading ?? group.items[0]?.value}
          heading={group.heading}
        >
          {group.items.map((menuItem) => (
            <CommandItem
              key={menuItem.value}
              className="[&_svg]:text-muted-foreground"
              value={menuItem.value}
              onSelect={() => {
                menuItem.onSelect?.({ editor, input });
                setInput('');
              }}
            >
              {menuItem.icon}
              <span>{menuItem.label}</span>
            </CommandItem>
          ))}
        </CommandGroup>
      ))}
    </>
  );
};
 
export function AILoadingBar() {
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const mode = usePluginStore(AIChatPlugin, 'mode');
 
  const status = chat?.status ?? 'ready';
 
  const { api } = useEditor().plugin(AIChatPlugin);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  if (isLoading && (mode === 'insert' || toolName === 'comment')) {
    return (
      <div
        className={cn(
          'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
        )}
      >
        <span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
        <span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
        <Button
          size="sm"
          variant="ghost"
          className="flex items-center gap-1 text-xs"
          onKeyDown={(event) => {
            if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
            event.preventDefault();
            event.stopPropagation();
            api.stop();
          }}
          onClick={() => {
            api.stop();
          }}
        >
          <PauseIcon className="h-4 w-4" />
          Stop
          <kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
            Esc
          </kbd>
        </Button>
      </div>
    );
  }
 
  if (toolName === 'comment' && status === 'error') {
    return (
      <div
        className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
        data-ai-comment-error=""
        data-editor-keep-selection-visible
      >
        <p className="w-full px-1 text-destructive" role="alert">
          Could not generate comments.
        </p>
        <Button onClick={() => api.reload()} size="sm" variant="outline">
          Try again
        </Button>
        <Button onClick={() => api.hide()} size="sm" variant="outline">
          <X data-icon="inline-start" />
          Dismiss
        </Button>
      </div>
    );
  }
 
  return null;
}
'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
  NodeApi,























































































































































































































































































































































































































































































































































































































































































































































































































Extend the aiChatItems map to add new commands. Each command receives { editor, input } and can call editor.plugin(AIChatPlugin).api.submit with custom prompts or transforms.

Simple custom command

import { AIChatPlugin } from 'platejs/ai/react';
import { ListIcon } from 'lucide-react';
 
export const aiChatItems = {
  summarizeInBullets: {
    icon: <ListIcon />,
    label: 'Summarize in bullets',
    value: 'summarizeInBullets',
    onSelect: ({ editor }) => {
      void editor.plugin(AIChatPlugin).api.submit('', {
        prompt: 'Summarize the current selection using bullet points',
        toolName: 'generate',
      });
    },
  },
};
import { AIChatPlugin } from 'platejs/ai/react';
import { ListIcon } from 'lucide-react';
 
export const aiChatItems = {
  summarizeInBullets: {
    icon: <ListIcon />,
    label: 'Summarize in bullets',
    value: 'summarizeInBullets',
    onSelect: ({ editor }) => {
      void editor.plugin(AIChatPlugin).api.submit('', {
        prompt: 'Summarize the current selection using bullet points',
        toolName: 'generate',
      });
    },
  },
};

Command with complex logic

import { AIChatPlugin } from 'platejs/ai/react';
import { BaseHeadingPlugin } from 'platejs';
import { BookIcon } from 'lucide-react';
 
export const aiChatItems = {
  generateTOC: {
    icon: <BookIcon />,
    label: 'Generate table of contents',
    value: 'generateTOC',
    onSelect: ({ editor }) => {
      const heading = editor.plugin(BaseHeadingPlugin);
      const headingTypes = heading.installed ? [heading.schema.type] : [];
      const headings = editor.read.nodes.toArray({
        at: [],
        type: headingTypes,
      });
 
      const prompt =
        headings.length === 0
          ? 'Create a realistic table of contents for this document'
          : 'Generate a table of contents that reflects the existing headings';
 
      void editor.plugin(AIChatPlugin).api.submit('', {
        mode: 'insert',
        prompt,
        toolName: 'generate',
      });
    },
  },
};
import { AIChatPlugin } from 'platejs/ai/react';
import { BaseHeadingPlugin } from 'platejs';
import { BookIcon } from 'lucide-react';
 
export const aiChatItems = {
  generateTOC: {
    icon: <BookIcon />,
    label: 'Generate table of contents',
    value: 'generateTOC',
    onSelect: ({ editor }) => {
      const heading = editor.plugin(BaseHeadingPlugin);
      const headingTypes = heading.installed ? [heading.schema.type] : [];
      const headings = editor.read.nodes.
















The command reads the installed H1-H3 capabilities. If the editor omits all three, it uses the fallback prompt instead of assuming persisted type strings.

The menu automatically switches between command and suggestion states:

  • cursorCommand: Cursor is collapsed and no response yet.
  • selectionCommand: Text is selected and no response yet.
  • cursorSuggestion / selectionSuggestion: A response exists, so actions like Accept, Try Again, or Insert Below are shown.

Use toolName ('generate' | 'edit' | 'comment') to control how streaming hooks process the response. 'generate' publishes a draft, 'edit' publishes a draft in insert mode and a suggestion in chat mode, and 'comment' can map feedback through aiChat.read.commentRange.

,
}: RenderNodeWrapperProps<typeof AIChatTransportPlugin>) {
const replacesEmptyParagraph = useEditorSelector((editor) => {
const paragraph = editor.read.nodes.get(element, {
type: editor.plugin(BaseParagraphPlugin).schema.type,
});
return !!paragraph && editor.read.nodes.isEmpty(paragraph[0]);
});
return (
<div data-editor-ai-preview-wrapper="">
<div hidden={replacesEmptyParagraph}>{children}</div>
<div contentEditable={false} data-editor-ai-preview="">
<AIChatEditor inline />
</div>
</div>
);
}
function AIIntegration({ children, editableRef }: WrapRootProps) {
useEditorChat(editableRef);
return children;
}
export const AIKit = [
AIChatTransportPlugin.extend(({ api, store }) => ({
render: {
useViewElementAttributes() {
const key = usePluginStore(AIChatPlugin, (state) =>
state.mode === 'insert' && state.previewValue.length > 0
? state._blockKey
: null
);
return key
? [{ key, attributes: { 'data-editor-ai-preview-anchor': '' } }]
: [];
},
},
slots: {
wrapNode: {
component: AIInlinePreview,
match: ({ editor, element }) => {
const state = store.get();
return (
state.mode === 'insert' &&
state.previewValue.length > 0 &&
editor.key(element) === state._blockKey
);
},
},
afterContainer: AILoadingBar,
caret: AIMenu,
wrapRoot: AIIntegration,
},
shortcuts: {
show: {
keys: 'mod+j',
handler: ({ editor }) => {
editor.plugin(AIChatPlugin).api.show();
},
},
stop: {
keys: 'escape',
handler: () => {
const status = store.get().chat?.status;
if (status !== 'streaming' && status !== 'submitted') return false;
api.stop();
return true;
},
},
},
})),
];
plugins: [
// ...otherPlugins,
...AIKit,
],
});
import { EditorRoot, useCreateEditor } from 'platejs/react';
import { AIKit } from '@/components/editor/ai';
import { Editor, EditorContainer } from '@/components/editor/editor';
 
export function AIEditor() {
  const editor = useCreateEditor({ plugins: AIKit });
 
  return (
    <EditorRoot editor={editor}>
      <EditorContainer>
        <Editor />
      </EditorContainer>
    </EditorRoot>
  );
}
'platejs/ai'
;
import type { MarkdownEditor } from 'platejs/markdown';
import { z } from 'zod';
import { BaseEditorKit } from '@/components/editor/plugins-static';
import type {
ChatMessage,
ToolName,
} from '@/components/editor/use-chat';
import { getChooseToolPrompt } from './prompt/getChooseToolPrompt';
import { getCommentPrompt } from './prompt/getCommentPrompt';
import { getEditPrompt } from './prompt/getEditPrompt';
import { buildEditTableMultiCellPrompt } from './prompt/getEditTablePrompt';
import { getGeneratePrompt } from './prompt/getGeneratePrompt';
const toolNameSchema = z.enum(['comment', 'edit', 'generate']);
export async function POST(req: NextRequest) {
const { apiKey: key, ctx, messages: messagesRaw, model } = await req.json();
const apiKey = typeof key === 'string' ? key.trim() : '';
if (!apiKey) {
return NextResponse.json(
{ error: 'Missing AI Gateway API key.' },
{ status: 401 }
);
}
const {
children,
nodeSelection,
refs,
selection,
toolName: toolNameParam,
} = ctx as AIChatRequestContext;
const request = resolveAIChatRequestContext({ nodeSelection, selection });
const { isSelecting } = request;
const editor = createEditor({
plugins: BaseEditorKit,
initialSelection: request.selection,
initialValue: children,
});
const gatewayProvider = createGateway({
apiKey,
});
try {
const stream = createUIMessageStream<ChatMessage>({
execute: async ({ writer }) => {
let toolName = toolNameParam;
if (!toolName) {
const prompt = getChooseToolPrompt({
isSelecting,
messages: messagesRaw,
});
const enumOptions: ToolName[] = isSelecting
? ['generate', 'edit', 'comment']
: ['generate', 'comment'];
const modelId = model || 'google/gemini-2.5-flash';
const { output } = await generateText({
model: gatewayProvider(modelId),
output: Output.choice({ options: enumOptions }),
prompt,
});
const selectedToolName = toolNameSchema.parse(output);
writer.write({
data: selectedToolName,
type: 'data-toolName',
});
toolName = selectedToolName;
}
const innerStream = streamText({
model: gatewayProvider(model || 'openai/gpt-4o-mini'),
// Not used
prompt: '',
tools: {
comment: getCommentTool(editor, {
messagesRaw,
model: gatewayProvider(model || 'google/gemini-2.5-flash'),
modelId: model || 'google/gemini-2.5-flash',
refs: refs.blocks,
writer,
}),
table: getTableTool(editor, {
messagesRaw,
model: gatewayProvider(model || 'google/gemini-2.5-flash'),
refs: refs.tableCells,
writer,
}),
},
prepareStep: (step) => {
if (toolName === 'comment') {
// The selection task is more challenging, so use Gemini 2.5 Flash.
return {
...step,
toolChoice: { toolName: 'comment', type: 'tool' },
};
}
if (toolName === 'edit') {
const [editPrompt, editType] = getEditPrompt(editor, {
isSelecting,
messages: messagesRaw,
tableCellRefs: refs.tableCells,
});
// Table editing uses the table tool
if (editType === 'table') {
return {
...step,
toolChoice: { toolName: 'table', type: 'tool' },
};
}
return {
...step,
activeTools: [],
model:
editType === 'selection'
? gatewayProvider(model || 'google/gemini-2.5-flash')
: gatewayProvider(model || 'openai/gpt-4o-mini'),
messages: [
{
content: editPrompt,
role: 'user',
},
],
};
}
if (toolName === 'generate') {
const generatePrompt = getGeneratePrompt(editor, {
isSelecting,
messages: messagesRaw,
});
return {
...step,
activeTools: [],
messages: [
{
content: generatePrompt,
role: 'user',
},
],
model: gatewayProvider(model || 'openai/gpt-4o-mini'),
};
}
return undefined;
},
});
writer.merge(innerStream.toUIMessageStream({ sendFinish: false }));
},
});
return createUIMessageStreamResponse({ stream });
} catch {
return NextResponse.json(
{ error: 'Failed to process AI request' },
{ status: 500 }
);
}
}
const getCommentTool = (
editor: MarkdownEditor,
{
messagesRaw,
model,
modelId,
refs,
writer,
}: {
messagesRaw: ChatMessage[];
model: LanguageModel;
modelId: string;
refs: AIChatRequestRefs['blocks'];
writer: UIMessageStreamWriter<ChatMessage>;
}
) =>
tool({
description: 'Comment on the content',
inputSchema: z.object({}),
strict: true,
execute: async () => {
const commentSchema = z.object({
blockRef: z
.string()
.describe(
'The request-local reference of the starting block. If the comment spans multiple blocks, use the reference of the first block.'
),
comment: z
.string()
.describe('A brief comment or explanation for this fragment.'),
content: z
.string()
.describe(
String.raw`The original document fragment to be commented on.It can be the entire block, a small part within a block, or span multiple blocks. If spanning multiple blocks, separate them with two \n\n.`
),
});
const { partialOutputStream } = streamText({
model,
output: Output.array({ element: commentSchema }),
prompt: getCommentPrompt(editor, {
messages: messagesRaw,
refs,
}),
});
let lastLength = 0;
for await (const partialArray of partialOutputStream) {
for (let i = lastLength; i < partialArray.length; i++) {
const comment = partialArray[i];
const commentDataId = nanoid();
writer.write({
id: commentDataId,
data: {
comment,
model: modelId,
status: 'streaming',
},
type: 'data-comment',
});
}
lastLength = partialArray.length;
}
writer.write({
id: nanoid(),
data: {
comment: null,
status: 'finished',
},
type: 'data-comment',
});
return 'Comments added.';
},
});
const getTableTool = (
editor: MarkdownEditor,
{
messagesRaw,
model,
refs,
writer,
}: {
messagesRaw: ChatMessage[];
model: LanguageModel;
refs: AIChatRequestRefs['tableCells'];
writer: UIMessageStreamWriter<ChatMessage>;
}
) =>
tool({
description: 'Edit table cells',
inputSchema: z.object({}),
strict: true,
execute: async () => {
const cellUpdateSchema = z.object({
content: z
.string()
.describe(
String.raw`The new content for the cell. Can contain multiple paragraphs separated by \n\n.`
),
ref: z
.string()
.describe('The request-local reference of the table cell to update.'),
});
const { partialOutputStream } = streamText({
model,
output: Output.array({ element: cellUpdateSchema }),
prompt: buildEditTableMultiCellPrompt(editor, messagesRaw, refs),
});
let lastLength = 0;
for await (const partialArray of partialOutputStream) {
for (let i = lastLength; i < partialArray.length; i++) {
const cellUpdate = partialArray[i];
writer.write({
id: nanoid(),
data: {
cellUpdate,
status: 'streaming',
},
type: 'data-table',
});
}
lastLength = partialArray.length;
}
writer.write({
id: nanoid(),
data: {
cellUpdate: null,
status: 'finished',
},
type: 'data-table',
});
return 'Table cells updated.';
},
});
import { createGateway } from '@ai-sdk/gateway';
import {
  type LanguageModel,
  type UIMessageStreamWriter,
  createUIMessageStream,
  createUIMessageStreamResponse,
  generateText,
  Output,
  streamText,
  tool,
} from 'ai';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { createEditor, nanoid } from 'platejs';
import {
  type AIChatRequestContext,
  type AIChatRequestRefs,
  resolveAIChatRequestContext,
} from 'platejs/ai';
import type { MarkdownEditor } from 'platejs/markdown';
import { z } from 'zod';
 
import { BaseEditorKit } from '@/components/editor/plugins-static';
import type {
  ChatMessage,
  ToolName,
} from '@/components/editor/use-chat';
 
import { getChooseToolPrompt } from './prompt/getChooseToolPrompt';
import { getCommentPrompt } from './prompt/getCommentPrompt';
import { getEditPrompt } from './prompt/getEditPrompt';
import { buildEditTableMultiCellPrompt } from './prompt/getEditTablePrompt';
import { getGeneratePrompt } from './prompt/getGeneratePrompt';
 
const toolNameSchema = z.enum(['comment', 'edit', 'generate']);
 
export async function POST(req: NextRequest) {
  const { apiKey: key, ctx, messages: messagesRaw, model } = await req.json();
  const apiKey = typeof key === 'string' ? key.trim() : '';
 
  if (!apiKey) {
    return NextResponse.json(
      { error: 'Missing AI Gateway API key.' },
      { status: 401 }
    );
  }
 
  const {
    children,
    nodeSelection,
    refs,
    selection,
    toolName: toolNameParam,
  } = ctx as AIChatRequestContext;
  const request = resolveAIChatRequestContext({ nodeSelection, selection });
  const { isSelecting } = request;
 
  const editor = createEditor({
    plugins: BaseEditorKit,
    initialSelection: request.selection,
    initialValue: children,
  });
 
  const gatewayProvider = createGateway({
    apiKey,
  });
 
  try {
    const stream = createUIMessageStream<ChatMessage>({
      execute: async ({ writer }) => {
        let toolName = toolNameParam;
 
        if (!toolName) {
          const prompt = getChooseToolPrompt({
            isSelecting,
            messages: messagesRaw,
          });
 
          const enumOptions: ToolName[] = isSelecting
            ? ['generate', 'edit', 'comment']
            : ['generate', 'comment'];
          const modelId = model || 'google/gemini-2.5-flash';
 
          const { output } = await generateText({
            model: gatewayProvider(modelId),
            output: Output.choice({ options: enumOptions }),
            prompt,
          });
          const selectedToolName = toolNameSchema.parse(output);
 
          writer.write({
            data: selectedToolName,
            type: 'data-toolName',
          });
 
          toolName = selectedToolName;
        }
 
        const innerStream = streamText({
          model: gatewayProvider(model || 'openai/gpt-4o-mini'),
          // Not used
          prompt: '',
          tools: {
            comment: getCommentTool(editor, {
              messagesRaw,
              model: gatewayProvider(model || 'google/gemini-2.5-flash'),
              modelId: model || 'google/gemini-2.5-flash',
              refs: refs.blocks,
              writer,
            }),
            table: getTableTool(editor, {
              messagesRaw,
              model: gatewayProvider(model || 'google/gemini-2.5-flash'),
              refs: refs.tableCells,
              writer,
            }),
          },
          prepareStep: (step) => {
            if (toolName === 'comment') {
              // The selection task is more challenging, so use Gemini 2.5 Flash.
              return {
                ...step,
                toolChoice: { toolName: 'comment', type: 'tool' },
              };
            }
 
            if (toolName === 'edit') {
              const [editPrompt, editType] = getEditPrompt(editor, {
                isSelecting,
                messages: messagesRaw,
                tableCellRefs: refs.tableCells,
              });
 
              // Table editing uses the table tool
              if (editType === 'table') {
                return {
                  ...step,
                  toolChoice: { toolName: 'table', type: 'tool' },
                };
              }
 
              return {
                ...step,
                activeTools: [],
                model:
                  editType === 'selection'
                    ? gatewayProvider(model || 'google/gemini-2.5-flash')
                    : gatewayProvider(model || 'openai/gpt-4o-mini'),
                messages: [
                  {
                    content: editPrompt,
                    role: 'user',
                  },
                ],
              };
            }
 
            if (toolName === 'generate') {
              const generatePrompt = getGeneratePrompt(editor, {
                isSelecting,
                messages: messagesRaw,
              });
 
              return {
                ...step,
                activeTools: [],
                messages: [
                  {
                    content: generatePrompt,
                    role: 'user',
                  },
                ],
                model: gatewayProvider(model || 'openai/gpt-4o-mini'),
              };
            }
 
            return undefined;
          },
        });
 
        writer.merge(innerStream.toUIMessageStream({ sendFinish: false }));
      },
    });
 
    return createUIMessageStreamResponse({ stream });
  } catch {
    return NextResponse.json(
      { error: 'Failed to process AI request' },
      { status: 500 }
    );
  }
}
 
const getCommentTool = (
  editor: MarkdownEditor,
  {
    messagesRaw,
    model,
    modelId,
    refs,
    writer,
  }: {
    messagesRaw: ChatMessage[];
    model: LanguageModel;
    modelId: string;
    refs: AIChatRequestRefs['blocks'];
    writer: UIMessageStreamWriter<ChatMessage>;
  }
) =>
  tool({
    description: 'Comment on the content',
    inputSchema: z.object({}),
    strict: true,
    execute: async () => {
      const commentSchema = z.object({
        blockRef: z
          .string()
          .describe(
            'The request-local reference of the starting block. If the comment spans multiple blocks, use the reference of the first block.'
          ),
        comment: z
          .string()
          .describe('A brief comment or explanation for this fragment.'),
        content: z
          .string()
          .describe(
            String.raw`The original document fragment to be commented on.It can be the entire block, a small part within a block, or span multiple blocks. If spanning multiple blocks, separate them with two \n\n.`
          ),
      });
 
      const { partialOutputStream } = streamText({
        model,
        output: Output.array({ element: commentSchema }),
        prompt: getCommentPrompt(editor, {
          messages: messagesRaw,
          refs,
        }),
      });
 
      let lastLength = 0;
 
      for await (const partialArray of partialOutputStream) {
        for (let i = lastLength; i < partialArray.length; i++) {
          const comment = partialArray[i];
          const commentDataId = nanoid();
 
          writer.write({
            id: commentDataId,
            data: {
              comment,
              model: modelId,
              status: 'streaming',
            },
            type: 'data-comment',
          });
        }
 
        lastLength = partialArray.length;
      }
 
      writer.write({
        id: nanoid(),
        data: {
          comment: null,
          status: 'finished',
        },
        type: 'data-comment',
      });
 
      return 'Comments added.';
    },
  });
 
const getTableTool = (
  editor: MarkdownEditor,
  {
    messagesRaw,
    model,
    refs,
    writer,
  }: {
    messagesRaw: ChatMessage[];
    model: LanguageModel;
    refs: AIChatRequestRefs['tableCells'];
    writer: UIMessageStreamWriter<ChatMessage>;
  }
) =>
  tool({
    description: 'Edit table cells',
    inputSchema: z.object({}),
    strict: true,
    execute: async () => {
      const cellUpdateSchema = z.object({
        content: z
          .string()
          .describe(
            String.raw`The new content for the cell. Can contain multiple paragraphs separated by \n\n.`
          ),
        ref: z
          .string()
          .describe('The request-local reference of the table cell to update.'),
      });
 
      const { partialOutputStream } = streamText({
        model,
        output: Output.array({ element: cellUpdateSchema }),
        prompt: buildEditTableMultiCellPrompt(editor, messagesRaw, refs),
      });
 
      let lastLength = 0;
 
      for await (const partialArray of partialOutputStream) {
        for (let i = lastLength; i < partialArray.length; i++) {
          const cellUpdate = partialArray[i];
 
          writer.write({
            id: nanoid(),
            data: {
              cellUpdate,
              status: 'streaming',
            },
            type: 'data-table',
          });
        }
 
        lastLength = partialArray.length;
      }
 
      writer.write({
        id: nanoid(),
        data: {
          cellUpdate: null,
          status: 'finished',
        },
        type: 'data-table',
      });
 
      return 'Table cells updated.';
    },
  });
},
}),
],
});
import { createEditor } from 'platejs/react';
import { AIKit } from '@/components/editor/ai';
import { AILoadingBar, AIMenu } from '@/components/editor/ai-menu';
import { AIChatTransportPlugin } from '@/components/editor/use-chat';
 
const editor = createEditor({
  plugins: [
    ...AIKit,
    AIChatTransportPlugin.configure({
      slots: {
        afterContainer: AILoadingBar,
        caret: AIMenu,
      },
      initialState: {
        chatOptions: {
          api: '/api/ai/command',
          body: { model: 'openai/gpt-4o-mini' },
        },
      },
    }),
  ],
});
({
initialState: {
initialComments: { ranges, threads },
users: { ...users, [aiUser.id]: aiUser },
},
});
:
''
;
if (!apiKey) {
return Response.json({ error: 'Missing AI Gateway API key.' }, { status: 401 });
}
const editor = createEditor({
plugins: BaseEditorKit,
initialSelection: ctx.selection,
initialValue: ctx.children,
});
const gateway = createGateway({ apiKey });
const result = streamText({
messages: await convertToModelMessages(messages),
model: gateway(model ?? 'openai/gpt-4o-mini'),
system: ctx.toolName === 'edit' ? 'You are an editor that rewrites user text.' : undefined,
});
return result.toUIMessageStreamResponse();
}
app/api/ai/command/route.ts
import { createGateway } from '@ai-sdk/gateway';
import { convertToModelMessages, streamText } from 'ai';
import { createEditor } from 'platejs';
 
import { BaseEditorKit } from '@/registry/components/editor/plugins-static';
 
export async function POST(req: Request) {
  const { apiKey: key, ctx, messages, model } = await req.json();
  const apiKey = typeof key === 'string' ? key.trim() : '';
 
  if (!apiKey) {
    return Response.json({ error: 'Missing AI Gateway API key.' }, { status: 401 });
  }
 
  const editor = createEditor({
    plugins: BaseEditorKit,
    initialSelection: ctx.selection,
    initialValue: ctx.children,
  });
 
  const gateway = createGateway({ apiKey });
 
  const result = streamText({
    messages: await convertToModelMessages(messages),
    model: gateway(model ?? 'openai/gpt-4o-mini'),
    system: ctx.toolName === 'edit' ? 'You are an editor that rewrites user text.' : undefined,
  });
 
  return result.toUIMessageStreamResponse();
}
import
{ createCommentValue }
from
'@/components/editor/comment'
;
export const aiUser: CommentUser = {
id: 'ai',
name: 'AI',
avatarUrl: 'https://api.dicebear.com/9.x/bottts/svg?seed=ai',
};
export type AIChatTransportPluginState = {
chatOptions: { api: string; body: Record<string, unknown> };
};
const initialState: AIChatTransportPluginState = {
chatOptions: { api: '/api/ai/command', body: {} },
};
export const AIChatTransportPlugin = AIChatPlugin.extend({
initialState: { ...initialState, authorId: aiUser.id },
}).extend(({ store }) => {
let api: string | undefined;
let transport: DefaultChatTransport<UIMessage> | undefined;
return {
api: () => ({
transport: () => {
const options = store.get('chatOptions');
if (!transport || options.api !== api) {
({ api } = options);
transport = new DefaultChatTransport<UIMessage>({
api,
body: () => store.get('chatOptions').body,
});
}
return transport;
},
}),
};
});
export type ToolName = 'comment' | 'edit' | 'generate';
export type TComment = {
comment: {
blockRef: string;
comment: string;
content: string;
} | null;
status: 'finished' | 'streaming';
model?: string;
};
export type TTableCellUpdate = {
cellUpdate: {
content: string;
ref: string;
} | null;
status: 'finished' | 'streaming';
};
export type MessageDataPart = {
toolName: ToolName;
comment: TComment;
table: TTableCellUpdate;
};
export type ChatMessage = UIMessage<unknown, MessageDataPart>;
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null;
const isStreamStatus = (value: unknown): value is 'finished' | 'streaming' =>
value === 'finished' || value === 'streaming';
const isComment = (value: unknown): value is TComment =>
isRecord(value) &&
isStreamStatus(value.status) &&
(value.model === undefined || typeof value.model === 'string') &&
(value.comment === null ||
(isRecord(value.comment) &&
typeof value.comment.blockRef === 'string' &&
typeof value.comment.comment === 'string' &&
typeof value.comment.content === 'string'));
export function useEditorChat(
editableRef: React.RefObject<HTMLElement | null>
) {
const editor = useEditor();
const authorId = usePluginStore(AIChatPlugin, 'authorId');
const comments = React.useMemo(
() =>
(authorId === null
? editor
: createEditorView(editor, { authorId })
).plugin(CommentsPlugin),
[authorId, editor]
);
const { api: transportApi } = editor.plugin(AIChatTransportPlugin);
const transport = usePluginStore(AIChatTransportPlugin, () =>
transportApi.transport()
);
const chat = usePluginStore(AIChatPlugin, 'chat');
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const markdownApi = editor.plugin(MarkdownPlugin).api;
React.useEffect(() => {
if (
toolName === 'comment' &&
chat?.status === 'ready' &&
chat.messages.length > 0
) {
// Completed streams can still have comment saves awaiting persistence.
editor.plugin(AIChatPlugin).store.set({ open: false });
}
}, [chat?.messages.length, chat?.status, editor, toolName]);
useAIChat({
editableRef,
transport,
onData: (data, signal) => {
if (data.type === 'data-comment' && isComment(data.data)) {
const commentData = data.data;
if (commentData.status === 'finished') {
editor.update.selection.set(null);
return;
}
const aiComment = commentData.comment;
if (aiComment == null) {
throw new Error('Streaming comment data requires a comment');
}
const range = editor.plugin(AIChatPlugin).read.commentRange(aiComment);
if (!range) {
console.warn('No range found for AI comment');
return;
}
if (!comments.installed) {
console.warn('AI comments require CommentsPlugin');
return;
}
void (async () => {
if (signal.aborted) return;
let id: string | null = null;
const discard = () => {
if (id) comments.api.discardDraft(id);
};
try {
const parsed = markdownApi.parseSlice(aiComment.content);
if (!parsed.ok) throw new Error(parsed.diagnostics[0].message);
id = comments.api.createDraft({
target: { range, type: 'range' },
body: createCommentValue(aiComment.comment),
data: {
requestedBy: editor.userId,
...(commentData.model && { model: commentData.model }),
},
excerpt: parsed.slice.content
.map((node) => NodeApi.string(node))
.join('\n'),
});
if (!id) {
console.warn('Could not create AI comment');
toast.error(
'Could not save AI comment. Try generating comments again.'
);
return;
}
signal.addEventListener('abort', discard, { once: true });
if (signal.aborted) {
discard();
return;
}
const result = await comments.api.publishDraft(id);
if (signal.aborted) return;
if (result.status !== 'applied') {
discard();
console.warn('Could not publish AI comment');
toast.error(
'Could not save AI comment. Try generating comments again.'
);
return;
}
comments.api.setActive([id]);
} catch (error) {
discard();
// The SDK does not await onData promises, so rejection must terminate here.
if (!signal.aborted) {
console.warn('Could not publish AI comment', error);
toast.error(
'Could not save AI comment. Try generating comments again.'
);
}
} finally {
signal.removeEventListener('abort', discard);
}
})();
}
},
});
}
'use client';
 
import { type UIMessage, DefaultChatTransport } from 'ai';
import { createEditorView, NodeApi } from 'platejs';
import { AIChatPlugin, useAIChat } from 'platejs/ai/react';
import type { CommentUser } from 'platejs/comments';
import { CommentsPlugin } from 'platejs/comments/react';
import { MarkdownPlugin } from 'platejs/markdown';
import { useEditor, usePluginStore } from 'platejs/react';
import * as React from 'react';
import { toast } from 'sonner';
 
import { createCommentValue } from '@/components/editor/comment';
 
export const aiUser: CommentUser = {
  id: 'ai',
  name: 'AI',
  avatarUrl: 'https://api.dicebear.com/9.x/bottts/svg?seed=ai',
};
 
export type AIChatTransportPluginState = {
  chatOptions: { api: string; body: Record<string, unknown> };
};
const initialState: AIChatTransportPluginState = {
  chatOptions: { api: '/api/ai/command', body: {} },
};
 
export const AIChatTransportPlugin = AIChatPlugin.extend({
  initialState: { ...initialState, authorId: aiUser.id },
}).extend(({ store }) => {
  let api: string | undefined;
  let transport: DefaultChatTransport<UIMessage> | undefined;
 
  return {
    api: () => ({
      transport: () => {
        const options = store.get('chatOptions');
        if (!transport || options.api !== api) {
          ({ api } = options);
          transport = new DefaultChatTransport<UIMessage>({
            api,
            body: () => store.get('chatOptions').body,
          });
        }
        return transport;
      },
    }),
  };
});
 
export type ToolName = 'comment' | 'edit' | 'generate';
 
export type TComment = {
  comment: {
    blockRef: string;
    comment: string;
    content: string;
  } | null;
  status: 'finished' | 'streaming';
  model?: string;
};
 
export type TTableCellUpdate = {
  cellUpdate: {
    content: string;
    ref: string;
  } | null;
  status: 'finished' | 'streaming';
};
 
export type MessageDataPart = {
  toolName: ToolName;
  comment: TComment;
  table: TTableCellUpdate;
};
 
export type ChatMessage = UIMessage<unknown, MessageDataPart>;
 
const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null;
const isStreamStatus = (value: unknown): value is 'finished' | 'streaming' =>
  value === 'finished' || value === 'streaming';
const isComment = (value: unknown): value is TComment =>
  isRecord(value) &&
  isStreamStatus(value.status) &&
  (value.model === undefined || typeof value.model === 'string') &&
  (value.comment === null ||
    (isRecord(value.comment) &&
      typeof value.comment.blockRef === 'string' &&
      typeof value.comment.comment === 'string' &&
      typeof value.comment.content === 'string'));
 
export function useEditorChat(
  editableRef: React.RefObject<HTMLElement | null>
) {
  const editor = useEditor();
  const authorId = usePluginStore(AIChatPlugin, 'authorId');
  const comments = React.useMemo(
    () =>
      (authorId === null
        ? editor
        : createEditorView(editor, { authorId })
      ).plugin(CommentsPlugin),
    [authorId, editor]
  );
  const { api: transportApi } = editor.plugin(AIChatTransportPlugin);
  const transport = usePluginStore(AIChatTransportPlugin, () =>
    transportApi.transport()
  );
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
  const markdownApi = editor.plugin(MarkdownPlugin).api;
 
  React.useEffect(() => {
    if (
      toolName === 'comment' &&
      chat?.status === 'ready' &&
      chat.messages.length > 0
    ) {
      // Completed streams can still have comment saves awaiting persistence.
      editor.plugin(AIChatPlugin).store.set({ open: false });
    }
  }, [chat?.messages.length, chat?.status, editor, toolName]);
 
  useAIChat({
    editableRef,
    transport,
    onData: (data, signal) => {
      if (data.type === 'data-comment' && isComment(data.data)) {
        const commentData = data.data;
 
        if (commentData.status === 'finished') {
          editor.update.selection.set(null);
 
          return;
        }
 
        const aiComment = commentData.comment;
 
        if (aiComment == null) {
          throw new Error('Streaming comment data requires a comment');
        }
 
        const range = editor.plugin(AIChatPlugin).read.commentRange(aiComment);
 
        if (!range) {
          console.warn('No range found for AI comment');
          return;
        }
 
        if (!comments.installed) {
          console.warn('AI comments require CommentsPlugin');
          return;
        }
 
        void (async () => {
          if (signal.aborted) return;
          let id: string | null = null;
          const discard = () => {
            if (id) comments.api.discardDraft(id);
          };
          try {
            const parsed = markdownApi.parseSlice(aiComment.content);
 
            if (!parsed.ok) throw new Error(parsed.diagnostics[0].message);
            id = comments.api.createDraft({
              target: { range, type: 'range' },
              body: createCommentValue(aiComment.comment),
              data: {
                requestedBy: editor.userId,
                ...(commentData.model && { model: commentData.model }),
              },
              excerpt: parsed.slice.content
                .map((node) => NodeApi.string(node))
                .join('\n'),
            });
            if (!id) {
              console.warn('Could not create AI comment');
              toast.error(
                'Could not save AI comment. Try generating comments again.'
              );
              return;
            }
            signal.addEventListener('abort', discard, { once: true });
            if (signal.aborted) {
              discard();
              return;
            }
            const result = await comments.api.publishDraft(id);
            if (signal.aborted) return;
            if (result.status !== 'applied') {
              discard();
              console.warn('Could not publish AI comment');
              toast.error(
                'Could not save AI comment. Try generating comments again.'
              );
              return;
            }
            comments.api.setActive([id]);
          } catch (error) {
            discard();
            // The SDK does not await onData promises, so rejection must terminate here.
            if (!signal.aborted) {
              console.warn('Could not publish AI comment', error);
              toast.error(
                'Could not save AI comment. Try generating comments again.'
              );
            }
          } finally {
            signal.removeEventListener('abort', discard);
          }
        })();
      }
    },
  });
}
NodeApi,
RangeApi,
TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
useCreateEditor,
useEditorSelector,
useFocusedLast,
usePluginStore,
type Editor,
useEditor,
} from 'platejs/react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import {
Command,
CommandGroup,
CommandItem,
CommandList,
} from '@/components/ui/command';
import {
FloatingPopover,
FloatingPopoverAnchor,
FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
import { EditorStatic } from './editor-static';
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
decorate: {
// The end marker sits on the draft's last text, so only the last block
// decorates. Only the last character carries it, so it stays one element
// when other decorations, such as code highlighting, split that text.
read: ({ editor, entry: [node, path] }) => {
if (path.length !== 1 || node !== editor.read.children().at(-1)) {
return [];
}
const [last, lastPath] = NodeApi.last(node, []);
if (!TextApi.isText(last) || last.text.length === 0) return [];
const textPath = [...path, ...lastPath];
const end = last.text.length;
// The last code point: a surrogate pair is two UTF-16 units.
const start =
end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
return [
{
key: 'ai-preview-end',
range: {
anchor: { path: textPath, offset: start },
focus: { path: textPath, offset: end },
},
attributes: { 'data-editor-ai-end': '' },
},
];
},
},
});
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
const scrollElement = editor.api.dom.scroll();
const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
if (!scrollElement || !target) return;
const scrollBounds = scrollElement.getBoundingClientRect();
const targetBounds = target.getBoundingClientRect();
scrollElement.scrollTop +=
targetBounds.top +
targetBounds.height / 2 -
(scrollBounds.top + scrollBounds.height / 2);
};
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
const editor = useEditor();
const draftRef = React.useRef<HTMLDivElement>(null);
// Supplies the preview plugins; the draft renders as its document.
const aiEditor = useCreateEditor({
plugins: [...BaseEditorKit, AIPreviewEndPlugin],
});
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
// Renders the latest draft when rendering falls behind the stream,
// skipping drafts that were never shown.
const previewDocument = React.useDeferredValue(
React.useMemo(
() => (previewValue.length > 0 ? { children: previewValue } : undefined),
[previewValue]
)
);
// The draft resizes as it streams. Scrolling from the resize callback reads
// layout the browser has already computed, rather than forcing it after
// every render.
React.useEffect(() => {
const draft = draftRef.current;
const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
if (!inline || !draft || !Observer) return undefined;
const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
observer.observe(draft);
return () => observer.disconnect();
}, [editor, inline]);
const last = previewDocument
? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
: null;
// Rendering reads every block's decorations, so the preview renders only
// when its document or appearance changes, not on each update's urgent pass.
const preview = React.useMemo(
() => (
<EditorStatic
variant={inline ? 'none' : 'aiChat'}
document={previewDocument}
editor={aiEditor}
className={cn(
'[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
streaming &&
'[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
)}
/>
),
[aiEditor, inline, previewDocument, streaming]
);
const endWithoutText =
streaming && (!last || !TextApi.isText(last) || !last.text);
return (
<div ref={draftRef} data-editor-ai-draft="">
{preview}
{/* Stays mounted: adding or removing it flips whether the preview is
the last child, and `:last-child` descendant rules then restyle the
whole preview. */}
<span
data-editor-ai-end={endWithoutText ? '' : undefined}
className={cn(
'size-3 rounded-full bg-purple-600 align-middle',
endWithoutText ? 'inline-block' : 'hidden'
)}
/>
</div>
);
}
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
return block && ElementApi.isElement(block[0])
? editor.api.dom.resolveDOMNode(block[0])
: null;
};
export function AIMenu() {
const editor = useEditor();
const { api, read } = useEditor().plugin(AIChatPlugin);
const mode = usePluginStore(AIChatPlugin, 'mode');
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
const editAnchorKey = useEditorSelector((innerEditor) => {
const entry = innerEditor.read.selection.nodes().at(-1);
return entry && ElementApi.isElement(entry[0])
? innerEditor.key(entry[0])
: null;
});
const isFocusedLast = useFocusedLast();
const chatOpen = usePluginStore(AIChatPlugin, 'open');
const open = chatOpen && isFocusedLast;
const [value, setValue] = React.useState('');
const [input, setInput] = React.useState('');
const chat = usePluginStore(AIChatPlugin, 'chat');
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const messages = chat?.messages;
const status = chat?.status ?? 'ready';
const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
null
);
React.useEffect(() => {
if (!streaming && previewValue.length === 0) return undefined;
const anchorEntry = read.node();
if (!anchorEntry) return undefined;
const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
if (!anchorDom) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(
anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
anchorDom
);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editor, previewValue, read, streaming]);
const setOpen = (innerOpen: boolean) => {
if (innerOpen) {
if (!chatOpen) api.show();
} else if (chatOpen) {
api.hide({ focus: false });
}
};
React.useEffect(() => {
if (!chatOpen) {
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(null);
setInput('');
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}
const nextAnchor = resolveSelectionAnchor(editor);
if (!nextAnchor) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [chatOpen, editor]);
const children = useEditorSelector((innerEditor) =>
chatOpen ? innerEditor.read.children() : null
);
React.useEffect(() => {
if (!chatOpen || !anchorElement) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
if (anchorElement.isConnected) return;
const nextAnchor = resolveSelectionAnchor(editor);
if (nextAnchor) setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [anchorElement, chatOpen, children, editor]);
const isLoading = status === 'streaming' || status === 'submitted';
React.useEffect(() => {
if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
let anchorNode = editAnchorKey
? editor.read.nodes.get(editAnchorKey, {
match: ElementApi.isElement,
})
: undefined;
if (!anchorNode) {
anchorNode =
editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
}
if (!anchorNode) return undefined;
const block = editor.read.nodes.block({ at: anchorNode[1] });
const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
if (!domNode) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(domNode);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editAnchorKey, editor, isLoading, mode, toolName]);
if (isLoading && mode === 'insert') return null;
if (toolName === 'comment') return null;
if (!anchorElement) return null;
return (
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverAnchor element={anchorElement} />
<FloatingPopoverContent
className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
onEscapeKeyDown={(e) => {
e.preventDefault();
api.hide();
}}
align="center"
side="bottom"
>
<Command
className="w-full rounded-lg border shadow-md"
value={value}
onValueChange={setValue}
>
{mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
{isLoading ? (
<div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
<Loader2Icon className="size-4 animate-spin" />
{(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
</div>
) : (
<CommandPrimitive.Input
className={cn(
'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
'border-b focus-visible:ring-transparent'
)}
value={input}
onKeyDown={(e) => {
if (isHotkey('backspace')(e) && input.length === 0) {
e.preventDefault();
api.hide();
}
if (isHotkey('enter')(e) && !e.shiftKey && !value) {
e.preventDefault();
api.submit(input);
setInput('');
}
}}
onValueChange={setInput}
placeholder="Ask AI anything..."
data-editor-keep-selection-visible
autoFocus
/>
)}
{!isLoading && (
<CommandList>
<AIMenuItems
input={input}
setInput={setInput}
setValue={setValue}
/>
</CommandList>
)}
</Command>
</FloatingPopoverContent>
</FloatingPopover>
);
}
type EditorChatState =
| 'cursorCommand'
| 'cursorSuggestion'
| 'selectionCommand'
| 'selectionSuggestion';
const AICommentIcon = () => (
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M0 0h24v24H0z" fill="none" stroke="none" />
<path d="M8 9h8" />
<path d="M8 13h4.5" />
<path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
<path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
</svg>
);
const focusEditorOnceClosed = (editor: Editor) => {
if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
const aiChatItems = {
accept: {
icon: <Check />,
label: 'Accept',
value: 'accept',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.accept();
focusEditorOnceClosed(editor);
},
},
comment: {
icon: <AICommentIcon />,
label: 'Comment',
value: 'comment',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt:
'Please comment on the following content and provide reasonable and meaningful feedback.',
toolName: 'comment',
});
},
},
continueWrite: {
icon: <PenLine />,
label: 'Continue writing',
value: 'continueWrite',
onSelect: ({ editor, input }) => {
const ancestorNode = editor.read.nodes.block();
if (!ancestorNode) return;
const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: isEmpty
? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
: `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
toolName: 'generate',
});
},
},
discard: {
icon: <X />,
label: 'Discard',
shortcut: 'Escape',
value: 'discard',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.hide();
},
},
emojify: {
icon: <SmileIcon />,
label: 'Emojify',
value: 'emojify',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
toolName: 'edit',
});
},
},
explain: {
icon: <BadgeHelp />,
label: 'Explain',
value: 'explain',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: {
default: 'Explain {editor}',
selecting: 'Explain',
},
toolName: 'generate',
});
},
},
fixSpelling: {
icon: <Check />,
label: 'Fix spelling & grammar',
value: 'fixSpelling',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
toolName: 'edit',
});
},
},
generateMarkdownSample: {
icon: <BookOpenCheck />,
label: 'Generate Markdown sample',
value: 'generateMarkdownSample',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: 'Generate a markdown sample',
toolName: 'generate',
});
},
},
improveWriting: {
icon: <Wand />,
label: 'Improve writing',
value: 'improveWriting',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Improve the writing for clarity and flow, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
insertBelow: {
icon: <ListEnd />,
label: 'Insert below',
value: 'insertBelow',
onSelect: ({ editor }) => {
/** Format: 'none' Fix insert table */
editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
focusEditorOnceClosed(editor);
},
},
makeLonger: {
icon: <ListPlus />,
label: 'Make longer',
value: 'makeLonger',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
makeShorter: {
icon: <ListMinus />,
label: 'Make shorter',
value: 'makeShorter',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
toolName: 'edit',
});
},
},
replace: {
icon: <Check />,
label: 'Replace selection',
value: 'replace',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.replaceSelection();
focusEditorOnceClosed(editor);
},
},
simplifyLanguage: {
icon: <FeatherIcon />,
label: 'Simplify language',
value: 'simplifyLanguage',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
summarize: {
icon: <Album />,
label: 'Add a summary',
value: 'summarize',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: {
default: 'Summarize {editor}',
selecting: 'Summarize',
},
toolName: 'generate',
});
},
},
tryAgain: {
icon: <CornerUpLeft />,
label: 'Try again',
value: 'tryAgain',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.reload();
},
},
} satisfies Record<
string,
{
icon: React.ReactNode;
label: string;
value: string;
component?: React.ComponentType<{ menuState: EditorChatState }>;
filterItems?: boolean;
items?: Array<{ label: string; value: string }>;
shortcut?: string;
onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
}
>;
const menuStateItems: Record<
EditorChatState,
Array<{
items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
heading?: string;
}>
> = {
cursorCommand: [
{
items: [
aiChatItems.comment,
aiChatItems.generateMarkdownSample,
aiChatItems.continueWrite,
aiChatItems.summarize,
aiChatItems.explain,
],
},
],
cursorSuggestion: [
{
items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
},
],
selectionCommand: [
{
items: [
aiChatItems.improveWriting,
aiChatItems.comment,
aiChatItems.emojify,
aiChatItems.makeLonger,
aiChatItems.makeShorter,
aiChatItems.fixSpelling,
aiChatItems.simplifyLanguage,
],
},
],
selectionSuggestion: [
{
items: [
aiChatItems.accept,
aiChatItems.discard,
aiChatItems.insertBelow,
aiChatItems.tryAgain,
],
},
],
};
export const AIMenuItems = ({
input,
setInput,
setValue,
}: {
input: string;
setInput: (value: string) => void;
setValue: (value: string) => void;
}) => {
const editor = useEditor();
const comments = editor.plugin(CommentsPlugin);
const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
const mode = usePluginStore(AIChatPlugin, 'mode');
const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
const isSelecting =
chatNodeMode !== null ||
(!!chatSelection && RangeApi.isExpanded(chatSelection));
const menuState: EditorChatState =
(messages?.length ?? 0) > 0
? mode === 'chat'
? 'selectionSuggestion'
: 'cursorSuggestion'
: isSelecting
? 'selectionCommand'
: 'cursorCommand';
const menuGroups = comments.installed
? menuStateItems[menuState]
: menuStateItems[menuState].map((group) => ({
...group,
items: group.items.filter((item) => item !== aiChatItems.comment),
}));
const firstItemValue = menuGroups[0]?.items[0]?.value;
React.useEffect(() => {
if (firstItemValue) setValue(firstItemValue);
}, [firstItemValue, setValue]);
return (
<>
{menuGroups.map((group) => (
<CommandGroup
key={group.heading ?? group.items[0]?.value}
heading={group.heading}
>
{group.items.map((menuItem) => (
<CommandItem
key={menuItem.value}
className="[&_svg]:text-muted-foreground"
value={menuItem.value}
onSelect={() => {
menuItem.onSelect?.({ editor, input });
setInput('');
}}
>
{menuItem.icon}
<span>{menuItem.label}</span>
</CommandItem>
))}
</CommandGroup>
))}
</>
);
};
export function AILoadingBar() {
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const chat = usePluginStore(AIChatPlugin, 'chat');
const mode = usePluginStore(AIChatPlugin, 'mode');
const status = chat?.status ?? 'ready';
const { api } = useEditor().plugin(AIChatPlugin);
const isLoading = status === 'streaming' || status === 'submitted';
if (isLoading && (mode === 'insert' || toolName === 'comment')) {
return (
<div
className={cn(
'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
)}
>
<span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
<span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
<Button
size="sm"
variant="ghost"
className="flex items-center gap-1 text-xs"
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
event.preventDefault();
event.stopPropagation();
api.stop();
}}
onClick={() => {
api.stop();
}}
>
<PauseIcon className="h-4 w-4" />
Stop
<kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
Esc
</kbd>
</Button>
</div>
);
}
if (toolName === 'comment' && status === 'error') {
return (
<div
className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
data-ai-comment-error=""
data-editor-keep-selection-visible
>
<p className="w-full px-1 text-destructive" role="alert">
Could not generate comments.
</p>
<Button onClick={() => api.reload()} size="sm" variant="outline">
Try again
</Button>
<Button onClick={() => api.hide()} size="sm" variant="outline">
<X data-icon="inline-start" />
Dismiss
</Button>
</div>
);
}
return null;
}
'use client';
 
import { Command as CommandPrimitive } from 'cmdk';
import { cn } from 'cn';
import {
  Album,
  BadgeHelp,
  BookOpenCheck,
  Check,
  CornerUpLeft,
  FeatherIcon,
  ListEnd,
  ListMinus,
  ListPlus,
  Loader2Icon,
  PauseIcon,
  PenLine,
  SmileIcon,
  Wand,
  X,
} from 'lucide-react';
import {
  definePlugin,
  ElementApi,
  isHotkey,
  NodeApi,
  RangeApi,
  TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
  useCreateEditor,
  useEditorSelector,
  useFocusedLast,
  usePluginStore,
  type Editor,
  useEditor,
} from 'platejs/react';
import * as React from 'react';
 
import { Button } from '@/components/ui/button';
import {
  Command,
  CommandGroup,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import {
  FloatingPopover,
  FloatingPopoverAnchor,
  FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
 
import { EditorStatic } from './editor-static';
 
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
  decorate: {
    // The end marker sits on the draft's last text, so only the last block
    // decorates. Only the last character carries it, so it stays one element
    // when other decorations, such as code highlighting, split that text.
    read: ({ editor, entry: [node, path] }) => {
      if (path.length !== 1 || node !== editor.read.children().at(-1)) {
        return [];
      }
 
      const [last, lastPath] = NodeApi.last(node, []);
 
      if (!TextApi.isText(last) || last.text.length === 0) return [];
 
      const textPath = [...path, ...lastPath];
      const end = last.text.length;
      // The last code point: a surrogate pair is two UTF-16 units.
      const start =
        end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
 
      return [
        {
          key: 'ai-preview-end',
          range: {
            anchor: { path: textPath, offset: start },
            focus: { path: textPath, offset: end },
          },
          attributes: { 'data-editor-ai-end': '' },
        },
      ];
    },
  },
});
 
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
  const scrollElement = editor.api.dom.scroll();
  const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
  if (!scrollElement || !target) return;
 
  const scrollBounds = scrollElement.getBoundingClientRect();
  const targetBounds = target.getBoundingClientRect();
 
  scrollElement.scrollTop +=
    targetBounds.top +
    targetBounds.height / 2 -
    (scrollBounds.top + scrollBounds.height / 2);
};
 
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
  const editor = useEditor();
  const draftRef = React.useRef<HTMLDivElement>(null);
  // Supplies the preview plugins; the draft renders as its document.
  const aiEditor = useCreateEditor({
    plugins: [...BaseEditorKit, AIPreviewEndPlugin],
  });
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  // Renders the latest draft when rendering falls behind the stream,
  // skipping drafts that were never shown.
  const previewDocument = React.useDeferredValue(
    React.useMemo(
      () => (previewValue.length > 0 ? { children: previewValue } : undefined),
      [previewValue]
    )
  );
 
  // The draft resizes as it streams. Scrolling from the resize callback reads
  // layout the browser has already computed, rather than forcing it after
  // every render.
  React.useEffect(() => {
    const draft = draftRef.current;
    const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
    if (!inline || !draft || !Observer) return undefined;
 
    const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
    observer.observe(draft);
 
    return () => observer.disconnect();
  }, [editor, inline]);
 
  const last = previewDocument
    ? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
    : null;
 
  // Rendering reads every block's decorations, so the preview renders only
  // when its document or appearance changes, not on each update's urgent pass.
  const preview = React.useMemo(
    () => (
      <EditorStatic
        variant={inline ? 'none' : 'aiChat'}
        document={previewDocument}
        editor={aiEditor}
        className={cn(
          '[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
          streaming &&
            '[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
        )}
      />
    ),
    [aiEditor, inline, previewDocument, streaming]
  );
 
  const endWithoutText =
    streaming && (!last || !TextApi.isText(last) || !last.text);
 
  return (
    <div ref={draftRef} data-editor-ai-draft="">
      {preview}
      {/* Stays mounted: adding or removing it flips whether the preview is
          the last child, and `:last-child` descendant rules then restyle the
          whole preview. */}
      <span
        data-editor-ai-end={endWithoutText ? '' : undefined}
        className={cn(
          'size-3 rounded-full bg-purple-600 align-middle',
          endWithoutText ? 'inline-block' : 'hidden'
        )}
      />
    </div>
  );
}
 
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
  const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
 
  return block && ElementApi.isElement(block[0])
    ? editor.api.dom.resolveDOMNode(block[0])
    : null;
};
 
export function AIMenu() {
  const editor = useEditor();
  const { api, read } = useEditor().plugin(AIChatPlugin);
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
 
  const streaming = usePluginStore(AIChatPlugin, 'streaming');
  const editAnchorKey = useEditorSelector((innerEditor) => {
    const entry = innerEditor.read.selection.nodes().at(-1);
 
    return entry && ElementApi.isElement(entry[0])
      ? innerEditor.key(entry[0])
      : null;
  });
  const isFocusedLast = useFocusedLast();
  const chatOpen = usePluginStore(AIChatPlugin, 'open');
  const open = chatOpen && isFocusedLast;
  const [value, setValue] = React.useState('');
 
  const [input, setInput] = React.useState('');
 
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
 
  const messages = chat?.messages;
  const status = chat?.status ?? 'ready';
  const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
    null
  );
 
  React.useEffect(() => {
    if (!streaming && previewValue.length === 0) return undefined;
 
    const anchorEntry = read.node();
    if (!anchorEntry) return undefined;
 
    const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
    if (!anchorDom) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(
        anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
          anchorDom
      );
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editor, previewValue, read, streaming]);
 
  const setOpen = (innerOpen: boolean) => {
    if (innerOpen) {
      if (!chatOpen) api.show();
    } else if (chatOpen) {
      api.hide({ focus: false });
    }
  };
 
  React.useEffect(() => {
    if (!chatOpen) {
      const animationFrame = window.requestAnimationFrame(() => {
        setAnchorElement(null);
        setInput('');
      });
 
      return () => {
        window.cancelAnimationFrame(animationFrame);
      };
    }
 
    const nextAnchor = resolveSelectionAnchor(editor);
 
    if (!nextAnchor) return undefined;
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [chatOpen, editor]);
 
  const children = useEditorSelector((innerEditor) =>
    chatOpen ? innerEditor.read.children() : null
  );
 
  React.useEffect(() => {
    if (!chatOpen || !anchorElement) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      if (anchorElement.isConnected) return;
 
      const nextAnchor = resolveSelectionAnchor(editor);
 
      if (nextAnchor) setAnchorElement(nextAnchor);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [anchorElement, chatOpen, children, editor]);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  React.useEffect(() => {
    if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
 
    let anchorNode = editAnchorKey
      ? editor.read.nodes.get(editAnchorKey, {
          match: ElementApi.isElement,
        })
      : undefined;
 
    if (!anchorNode) {
      anchorNode =
        editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
    }
 
    if (!anchorNode) return undefined;
 
    const block = editor.read.nodes.block({ at: anchorNode[1] });
    const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
 
    if (!domNode) return undefined;
 
    const animationFrame = window.requestAnimationFrame(() => {
      setAnchorElement(domNode);
    });
 
    return () => {
      window.cancelAnimationFrame(animationFrame);
    };
  }, [editAnchorKey, editor, isLoading, mode, toolName]);
 
  if (isLoading && mode === 'insert') return null;
 
  if (toolName === 'comment') return null;
 
  if (!anchorElement) return null;
 
  return (
    <FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
      <FloatingPopoverAnchor element={anchorElement} />
 
      <FloatingPopoverContent
        className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
        onEscapeKeyDown={(e) => {
          e.preventDefault();
 
          api.hide();
        }}
        align="center"
        side="bottom"
      >
        <Command
          className="w-full rounded-lg border shadow-md"
          value={value}
          onValueChange={setValue}
        >
          {mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
 
          {isLoading ? (
            <div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
              <Loader2Icon className="size-4 animate-spin" />
              {(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
            </div>
          ) : (
            <CommandPrimitive.Input
              className={cn(
                'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
                'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
                'border-b focus-visible:ring-transparent'
              )}
              value={input}
              onKeyDown={(e) => {
                if (isHotkey('backspace')(e) && input.length === 0) {
                  e.preventDefault();
                  api.hide();
                }
                if (isHotkey('enter')(e) && !e.shiftKey && !value) {
                  e.preventDefault();
                  api.submit(input);
                  setInput('');
                }
              }}
              onValueChange={setInput}
              placeholder="Ask AI anything..."
              data-editor-keep-selection-visible
              autoFocus
            />
          )}
 
          {!isLoading && (
            <CommandList>
              <AIMenuItems
                input={input}
                setInput={setInput}
                setValue={setValue}
              />
            </CommandList>
          )}
        </Command>
      </FloatingPopoverContent>
    </FloatingPopover>
  );
}
 
type EditorChatState =
  | 'cursorCommand'
  | 'cursorSuggestion'
  | 'selectionCommand'
  | 'selectionSuggestion';
 
const AICommentIcon = () => (
  <svg
    fill="none"
    height="24"
    stroke="currentColor"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth="2"
    viewBox="0 0 24 24"
    width="24"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path d="M0 0h24v24H0z" fill="none" stroke="none" />
    <path d="M8 9h8" />
    <path d="M8 13h4.5" />
    <path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
    <path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
  </svg>
);
 
const focusEditorOnceClosed = (editor: Editor) => {
  if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
 
const aiChatItems = {
  accept: {
    icon: <Check />,
    label: 'Accept',
    value: 'accept',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.accept();
      focusEditorOnceClosed(editor);
    },
  },
  comment: {
    icon: <AICommentIcon />,
    label: 'Comment',
    value: 'comment',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt:
          'Please comment on the following content and provide reasonable and meaningful feedback.',
        toolName: 'comment',
      });
    },
  },
  continueWrite: {
    icon: <PenLine />,
    label: 'Continue writing',
    value: 'continueWrite',
    onSelect: ({ editor, input }) => {
      const ancestorNode = editor.read.nodes.block();
 
      if (!ancestorNode) return;
 
      const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
 
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: isEmpty
          ? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
          : `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
        toolName: 'generate',
      });
    },
  },
  discard: {
    icon: <X />,
    label: 'Discard',
    shortcut: 'Escape',
    value: 'discard',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.hide();
    },
  },
  emojify: {
    icon: <SmileIcon />,
    label: 'Emojify',
    value: 'emojify',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
        toolName: 'edit',
      });
    },
  },
  explain: {
    icon: <BadgeHelp />,
    label: 'Explain',
    value: 'explain',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: {
          default: 'Explain {editor}',
          selecting: 'Explain',
        },
        toolName: 'generate',
      });
    },
  },
  fixSpelling: {
    icon: <Check />,
    label: 'Fix spelling & grammar',
    value: 'fixSpelling',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
        toolName: 'edit',
      });
    },
  },
  generateMarkdownSample: {
    icon: <BookOpenCheck />,
    label: 'Generate Markdown sample',
    value: 'generateMarkdownSample',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt: 'Generate a markdown sample',
        toolName: 'generate',
      });
    },
  },
  improveWriting: {
    icon: <Wand />,
    label: 'Improve writing',
    value: 'improveWriting',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Improve the writing for clarity and flow, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  insertBelow: {
    icon: <ListEnd />,
    label: 'Insert below',
    value: 'insertBelow',
    onSelect: ({ editor }) => {
      /** Format: 'none' Fix insert table */
      editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
      focusEditorOnceClosed(editor);
    },
  },
  makeLonger: {
    icon: <ListPlus />,
    label: 'Make longer',
    value: 'makeLonger',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  makeShorter: {
    icon: <ListMinus />,
    label: 'Make shorter',
    value: 'makeShorter',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
        toolName: 'edit',
      });
    },
  },
  replace: {
    icon: <Check />,
    label: 'Replace selection',
    value: 'replace',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.replaceSelection();
      focusEditorOnceClosed(editor);
    },
  },
  simplifyLanguage: {
    icon: <FeatherIcon />,
    label: 'Simplify language',
    value: 'simplifyLanguage',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        prompt:
          'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
        toolName: 'edit',
      });
    },
  },
  summarize: {
    icon: <Album />,
    label: 'Add a summary',
    value: 'summarize',
    onSelect: ({ editor, input }) => {
      editor.plugin(AIChatPlugin).api.submit(input, {
        mode: 'insert',
        prompt: {
          default: 'Summarize {editor}',
          selecting: 'Summarize',
        },
        toolName: 'generate',
      });
    },
  },
  tryAgain: {
    icon: <CornerUpLeft />,
    label: 'Try again',
    value: 'tryAgain',
    onSelect: ({ editor }) => {
      editor.plugin(AIChatPlugin).api.reload();
    },
  },
} satisfies Record<
  string,
  {
    icon: React.ReactNode;
    label: string;
    value: string;
    component?: React.ComponentType<{ menuState: EditorChatState }>;
    filterItems?: boolean;
    items?: Array<{ label: string; value: string }>;
    shortcut?: string;
    onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
  }
>;
 
const menuStateItems: Record<
  EditorChatState,
  Array<{
    items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
    heading?: string;
  }>
> = {
  cursorCommand: [
    {
      items: [
        aiChatItems.comment,
        aiChatItems.generateMarkdownSample,
        aiChatItems.continueWrite,
        aiChatItems.summarize,
        aiChatItems.explain,
      ],
    },
  ],
  cursorSuggestion: [
    {
      items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
    },
  ],
  selectionCommand: [
    {
      items: [
        aiChatItems.improveWriting,
        aiChatItems.comment,
        aiChatItems.emojify,
        aiChatItems.makeLonger,
        aiChatItems.makeShorter,
        aiChatItems.fixSpelling,
        aiChatItems.simplifyLanguage,
      ],
    },
  ],
  selectionSuggestion: [
    {
      items: [
        aiChatItems.accept,
        aiChatItems.discard,
        aiChatItems.insertBelow,
        aiChatItems.tryAgain,
      ],
    },
  ],
};
 
export const AIMenuItems = ({
  input,
  setInput,
  setValue,
}: {
  input: string;
  setInput: (value: string) => void;
  setValue: (value: string) => void;
}) => {
  const editor = useEditor();
  const comments = editor.plugin(CommentsPlugin);
  const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
  const mode = usePluginStore(AIChatPlugin, 'mode');
  const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
  const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
  const isSelecting =
    chatNodeMode !== null ||
    (!!chatSelection && RangeApi.isExpanded(chatSelection));
 
  const menuState: EditorChatState =
    (messages?.length ?? 0) > 0
      ? mode === 'chat'
        ? 'selectionSuggestion'
        : 'cursorSuggestion'
      : isSelecting
        ? 'selectionCommand'
        : 'cursorCommand';
  const menuGroups = comments.installed
    ? menuStateItems[menuState]
    : menuStateItems[menuState].map((group) => ({
        ...group,
        items: group.items.filter((item) => item !== aiChatItems.comment),
      }));
  const firstItemValue = menuGroups[0]?.items[0]?.value;
 
  React.useEffect(() => {
    if (firstItemValue) setValue(firstItemValue);
  }, [firstItemValue, setValue]);
 
  return (
    <>
      {menuGroups.map((group) => (
        <CommandGroup
          key={group.heading ?? group.items[0]?.value}
          heading={group.heading}
        >
          {group.items.map((menuItem) => (
            <CommandItem
              key={menuItem.value}
              className="[&_svg]:text-muted-foreground"
              value={menuItem.value}
              onSelect={() => {
                menuItem.onSelect?.({ editor, input });
                setInput('');
              }}
            >
              {menuItem.icon}
              <span>{menuItem.label}</span>
            </CommandItem>
          ))}
        </CommandGroup>
      ))}
    </>
  );
};
 
export function AILoadingBar() {
  const toolName = usePluginStore(AIChatPlugin, 'toolName');
  const chat = usePluginStore(AIChatPlugin, 'chat');
  const mode = usePluginStore(AIChatPlugin, 'mode');
 
  const status = chat?.status ?? 'ready';
 
  const { api } = useEditor().plugin(AIChatPlugin);
 
  const isLoading = status === 'streaming' || status === 'submitted';
 
  if (isLoading && (mode === 'insert' || toolName === 'comment')) {
    return (
      <div
        className={cn(
          'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
        )}
      >
        <span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
        <span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
        <Button
          size="sm"
          variant="ghost"
          className="flex items-center gap-1 text-xs"
          onKeyDown={(event) => {
            if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
            event.preventDefault();
            event.stopPropagation();
            api.stop();
          }}
          onClick={() => {
            api.stop();
          }}
        >
          <PauseIcon className="h-4 w-4" />
          Stop
          <kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
            Esc
          </kbd>
        </Button>
      </div>
    );
  }
 
  if (toolName === 'comment' && status === 'error') {
    return (
      <div
        className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
        data-ai-comment-error=""
        data-editor-keep-selection-visible
      >
        <p className="w-full px-1 text-destructive" role="alert">
          Could not generate comments.
        </p>
        <Button onClick={() => api.reload()} size="sm" variant="outline">
          Try again
        </Button>
        <Button onClick={() => api.hide()} size="sm" variant="outline">
          <X data-icon="inline-start" />
          Dismiss
        </Button>
      </div>
    );
  }
 
  return null;
}
toolName:
'generate'
,
});
RangeApi,
TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
useCreateEditor,
useEditorSelector,
useFocusedLast,
usePluginStore,
type Editor,
useEditor,
} from 'platejs/react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import {
Command,
CommandGroup,
CommandItem,
CommandList,
} from '@/components/ui/command';
import {
FloatingPopover,
FloatingPopoverAnchor,
FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
import { EditorStatic } from './editor-static';
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
decorate: {
// The end marker sits on the draft's last text, so only the last block
// decorates. Only the last character carries it, so it stays one element
// when other decorations, such as code highlighting, split that text.
read: ({ editor, entry: [node, path] }) => {
if (path.length !== 1 || node !== editor.read.children().at(-1)) {
return [];
}
const [last, lastPath] = NodeApi.last(node, []);
if (!TextApi.isText(last) || last.text.length === 0) return [];
const textPath = [...path, ...lastPath];
const end = last.text.length;
// The last code point: a surrogate pair is two UTF-16 units.
const start =
end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
return [
{
key: 'ai-preview-end',
range: {
anchor: { path: textPath, offset: start },
focus: { path: textPath, offset: end },
},
attributes: { 'data-editor-ai-end': '' },
},
];
},
},
});
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
const scrollElement = editor.api.dom.scroll();
const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
if (!scrollElement || !target) return;
const scrollBounds = scrollElement.getBoundingClientRect();
const targetBounds = target.getBoundingClientRect();
scrollElement.scrollTop +=
targetBounds.top +
targetBounds.height / 2 -
(scrollBounds.top + scrollBounds.height / 2);
};
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
const editor = useEditor();
const draftRef = React.useRef<HTMLDivElement>(null);
// Supplies the preview plugins; the draft renders as its document.
const aiEditor = useCreateEditor({
plugins: [...BaseEditorKit, AIPreviewEndPlugin],
});
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
// Renders the latest draft when rendering falls behind the stream,
// skipping drafts that were never shown.
const previewDocument = React.useDeferredValue(
React.useMemo(
() => (previewValue.length > 0 ? { children: previewValue } : undefined),
[previewValue]
)
);
// The draft resizes as it streams. Scrolling from the resize callback reads
// layout the browser has already computed, rather than forcing it after
// every render.
React.useEffect(() => {
const draft = draftRef.current;
const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
if (!inline || !draft || !Observer) return undefined;
const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
observer.observe(draft);
return () => observer.disconnect();
}, [editor, inline]);
const last = previewDocument
? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
: null;
// Rendering reads every block's decorations, so the preview renders only
// when its document or appearance changes, not on each update's urgent pass.
const preview = React.useMemo(
() => (
<EditorStatic
variant={inline ? 'none' : 'aiChat'}
document={previewDocument}
editor={aiEditor}
className={cn(
'[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
streaming &&
'[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
)}
/>
),
[aiEditor, inline, previewDocument, streaming]
);
const endWithoutText =
streaming && (!last || !TextApi.isText(last) || !last.text);
return (
<div ref={draftRef} data-editor-ai-draft="">
{preview}
{/* Stays mounted: adding or removing it flips whether the preview is
the last child, and `:last-child` descendant rules then restyle the
whole preview. */}
<span
data-editor-ai-end={endWithoutText ? '' : undefined}
className={cn(
'size-3 rounded-full bg-purple-600 align-middle',
endWithoutText ? 'inline-block' : 'hidden'
)}
/>
</div>
);
}
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
return block && ElementApi.isElement(block[0])
? editor.api.dom.resolveDOMNode(block[0])
: null;
};
export function AIMenu() {
const editor = useEditor();
const { api, read } = useEditor().plugin(AIChatPlugin);
const mode = usePluginStore(AIChatPlugin, 'mode');
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
const editAnchorKey = useEditorSelector((innerEditor) => {
const entry = innerEditor.read.selection.nodes().at(-1);
return entry && ElementApi.isElement(entry[0])
? innerEditor.key(entry[0])
: null;
});
const isFocusedLast = useFocusedLast();
const chatOpen = usePluginStore(AIChatPlugin, 'open');
const open = chatOpen && isFocusedLast;
const [value, setValue] = React.useState('');
const [input, setInput] = React.useState('');
const chat = usePluginStore(AIChatPlugin, 'chat');
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const messages = chat?.messages;
const status = chat?.status ?? 'ready';
const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
null
);
React.useEffect(() => {
if (!streaming && previewValue.length === 0) return undefined;
const anchorEntry = read.node();
if (!anchorEntry) return undefined;
const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
if (!anchorDom) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(
anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
anchorDom
);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editor, previewValue, read, streaming]);
const setOpen = (innerOpen: boolean) => {
if (innerOpen) {
if (!chatOpen) api.show();
} else if (chatOpen) {
api.hide({ focus: false });
}
};
React.useEffect(() => {
if (!chatOpen) {
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(null);
setInput('');
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}
const nextAnchor = resolveSelectionAnchor(editor);
if (!nextAnchor) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [chatOpen, editor]);
const children = useEditorSelector((innerEditor) =>
chatOpen ? innerEditor.read.children() : null
);
React.useEffect(() => {
if (!chatOpen || !anchorElement) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
if (anchorElement.isConnected) return;
const nextAnchor = resolveSelectionAnchor(editor);
if (nextAnchor) setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [anchorElement, chatOpen, children, editor]);
const isLoading = status === 'streaming' || status === 'submitted';
React.useEffect(() => {
if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
let anchorNode = editAnchorKey
? editor.read.nodes.get(editAnchorKey, {
match: ElementApi.isElement,
})
: undefined;
if (!anchorNode) {
anchorNode =
editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
}
if (!anchorNode) return undefined;
const block = editor.read.nodes.block({ at: anchorNode[1] });
const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
if (!domNode) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(domNode);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editAnchorKey, editor, isLoading, mode, toolName]);
if (isLoading && mode === 'insert') return null;
if (toolName === 'comment') return null;
if (!anchorElement) return null;
return (
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverAnchor element={anchorElement} />
<FloatingPopoverContent
className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
onEscapeKeyDown={(e) => {
e.preventDefault();
api.hide();
}}
align="center"
side="bottom"
>
<Command
className="w-full rounded-lg border shadow-md"
value={value}
onValueChange={setValue}
>
{mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
{isLoading ? (
<div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
<Loader2Icon className="size-4 animate-spin" />
{(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
</div>
) : (
<CommandPrimitive.Input
className={cn(
'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
'border-b focus-visible:ring-transparent'
)}
value={input}
onKeyDown={(e) => {
if (isHotkey('backspace')(e) && input.length === 0) {
e.preventDefault();
api.hide();
}
if (isHotkey('enter')(e) && !e.shiftKey && !value) {
e.preventDefault();
api.submit(input);
setInput('');
}
}}
onValueChange={setInput}
placeholder="Ask AI anything..."
data-editor-keep-selection-visible
autoFocus
/>
)}
{!isLoading && (
<CommandList>
<AIMenuItems
input={input}
setInput={setInput}
setValue={setValue}
/>
</CommandList>
)}
</Command>
</FloatingPopoverContent>
</FloatingPopover>
);
}
type EditorChatState =
| 'cursorCommand'
| 'cursorSuggestion'
| 'selectionCommand'
| 'selectionSuggestion';
const AICommentIcon = () => (
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M0 0h24v24H0z" fill="none" stroke="none" />
<path d="M8 9h8" />
<path d="M8 13h4.5" />
<path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
<path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
</svg>
);
const focusEditorOnceClosed = (editor: Editor) => {
if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
const aiChatItems = {
accept: {
icon: <Check />,
label: 'Accept',
value: 'accept',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.accept();
focusEditorOnceClosed(editor);
},
},
comment: {
icon: <AICommentIcon />,
label: 'Comment',
value: 'comment',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt:
'Please comment on the following content and provide reasonable and meaningful feedback.',
toolName: 'comment',
});
},
},
continueWrite: {
icon: <PenLine />,
label: 'Continue writing',
value: 'continueWrite',
onSelect: ({ editor, input }) => {
const ancestorNode = editor.read.nodes.block();
if (!ancestorNode) return;
const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: isEmpty
? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
: `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
toolName: 'generate',
});
},
},
discard: {
icon: <X />,
label: 'Discard',
shortcut: 'Escape',
value: 'discard',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.hide();
},
},
emojify: {
icon: <SmileIcon />,
label: 'Emojify',
value: 'emojify',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
toolName: 'edit',
});
},
},
explain: {
icon: <BadgeHelp />,
label: 'Explain',
value: 'explain',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: {
default: 'Explain {editor}',
selecting: 'Explain',
},
toolName: 'generate',
});
},
},
fixSpelling: {
icon: <Check />,
label: 'Fix spelling & grammar',
value: 'fixSpelling',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
toolName: 'edit',
});
},
},
generateMarkdownSample: {
icon: <BookOpenCheck />,
label: 'Generate Markdown sample',
value: 'generateMarkdownSample',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: 'Generate a markdown sample',
toolName: 'generate',
});
},
},
improveWriting: {
icon: <Wand />,
label: 'Improve writing',
value: 'improveWriting',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Improve the writing for clarity and flow, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
insertBelow: {
icon: <ListEnd />,
label: 'Insert below',
value: 'insertBelow',
onSelect: ({ editor }) => {
/** Format: 'none' Fix insert table */
editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
focusEditorOnceClosed(editor);
},
},
makeLonger: {
icon: <ListPlus />,
label: 'Make longer',
value: 'makeLonger',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
makeShorter: {
icon: <ListMinus />,
label: 'Make shorter',
value: 'makeShorter',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
toolName: 'edit',
});
},
},
replace: {
icon: <Check />,
label: 'Replace selection',
value: 'replace',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.replaceSelection();
focusEditorOnceClosed(editor);
},
},
simplifyLanguage: {
icon: <FeatherIcon />,
label: 'Simplify language',
value: 'simplifyLanguage',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
summarize: {
icon: <Album />,
label: 'Add a summary',
value: 'summarize',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: {
default: 'Summarize {editor}',
selecting: 'Summarize',
},
toolName: 'generate',
});
},
},
tryAgain: {
icon: <CornerUpLeft />,
label: 'Try again',
value: 'tryAgain',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.reload();
},
},
} satisfies Record<
string,
{
icon: React.ReactNode;
label: string;
value: string;
component?: React.ComponentType<{ menuState: EditorChatState }>;
filterItems?: boolean;
items?: Array<{ label: string; value: string }>;
shortcut?: string;
onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
}
>;
const menuStateItems: Record<
EditorChatState,
Array<{
items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
heading?: string;
}>
> = {
cursorCommand: [
{
items: [
aiChatItems.comment,
aiChatItems.generateMarkdownSample,
aiChatItems.continueWrite,
aiChatItems.summarize,
aiChatItems.explain,
],
},
],
cursorSuggestion: [
{
items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
},
],
selectionCommand: [
{
items: [
aiChatItems.improveWriting,
aiChatItems.comment,
aiChatItems.emojify,
aiChatItems.makeLonger,
aiChatItems.makeShorter,
aiChatItems.fixSpelling,
aiChatItems.simplifyLanguage,
],
},
],
selectionSuggestion: [
{
items: [
aiChatItems.accept,
aiChatItems.discard,
aiChatItems.insertBelow,
aiChatItems.tryAgain,
],
},
],
};
export const AIMenuItems = ({
input,
setInput,
setValue,
}: {
input: string;
setInput: (value: string) => void;
setValue: (value: string) => void;
}) => {
const editor = useEditor();
const comments = editor.plugin(CommentsPlugin);
const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
const mode = usePluginStore(AIChatPlugin, 'mode');
const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
const isSelecting =
chatNodeMode !== null ||
(!!chatSelection && RangeApi.isExpanded(chatSelection));
const menuState: EditorChatState =
(messages?.length ?? 0) > 0
? mode === 'chat'
? 'selectionSuggestion'
: 'cursorSuggestion'
: isSelecting
? 'selectionCommand'
: 'cursorCommand';
const menuGroups = comments.installed
? menuStateItems[menuState]
: menuStateItems[menuState].map((group) => ({
...group,
items: group.items.filter((item) => item !== aiChatItems.comment),
}));
const firstItemValue = menuGroups[0]?.items[0]?.value;
React.useEffect(() => {
if (firstItemValue) setValue(firstItemValue);
}, [firstItemValue, setValue]);
return (
<>
{menuGroups.map((group) => (
<CommandGroup
key={group.heading ?? group.items[0]?.value}
heading={group.heading}
>
{group.items.map((menuItem) => (
<CommandItem
key={menuItem.value}
className="[&_svg]:text-muted-foreground"
value={menuItem.value}
onSelect={() => {
menuItem.onSelect?.({ editor, input });
setInput('');
}}
>
{menuItem.icon}
<span>{menuItem.label}</span>
</CommandItem>
))}
</CommandGroup>
))}
</>
);
};
export function AILoadingBar() {
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const chat = usePluginStore(AIChatPlugin, 'chat');
const mode = usePluginStore(AIChatPlugin, 'mode');
const status = chat?.status ?? 'ready';
const { api } = useEditor().plugin(AIChatPlugin);
const isLoading = status === 'streaming' || status === 'submitted';
if (isLoading && (mode === 'insert' || toolName === 'comment')) {
return (
<div
className={cn(
'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
)}
>
<span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
<span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
<Button
size="sm"
variant="ghost"
className="flex items-center gap-1 text-xs"
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
event.preventDefault();
event.stopPropagation();
api.stop();
}}
onClick={() => {
api.stop();
}}
>
<PauseIcon className="h-4 w-4" />
Stop
<kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
Esc
</kbd>
</Button>
</div>
);
}
if (toolName === 'comment' && status === 'error') {
return (
<div
className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
data-ai-comment-error=""
data-editor-keep-selection-visible
>
<p className="w-full px-1 text-destructive" role="alert">
Could not generate comments.
</p>
<Button onClick={() => api.reload()} size="sm" variant="outline">
Try again
</Button>
<Button onClick={() => api.hide()} size="sm" variant="outline">
<X data-icon="inline-start" />
Dismiss
</Button>
</div>
);
}
return null;
}
RangeApi,
TextApi,
} from 'platejs';
import { AIChatPlugin } from 'platejs/ai/react';
import { CommentsPlugin } from 'platejs/comments/react';
import {
useCreateEditor,
useEditorSelector,
useFocusedLast,
usePluginStore,
type Editor,
useEditor,
} from 'platejs/react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import {
Command,
CommandGroup,
CommandItem,
CommandList,
} from '@/components/ui/command';
import {
FloatingPopover,
FloatingPopoverAnchor,
FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { BaseEditorKit } from '@/components/editor/plugins-static';
import { EditorStatic } from './editor-static';
// The preview renders a document through this plugin's editor, so its
// decoration reads that document from the rendering view in its context.
const AIPreviewEndPlugin = definePlugin('aiPreviewEnd', {
decorate: {
// The end marker sits on the draft's last text, so only the last block
// decorates. Only the last character carries it, so it stays one element
// when other decorations, such as code highlighting, split that text.
read: ({ editor, entry: [node, path] }) => {
if (path.length !== 1 || node !== editor.read.children().at(-1)) {
return [];
}
const [last, lastPath] = NodeApi.last(node, []);
if (!TextApi.isText(last) || last.text.length === 0) return [];
const textPath = [...path, ...lastPath];
const end = last.text.length;
// The last code point: a surrogate pair is two UTF-16 units.
const start =
end - ((last.text.codePointAt(end - 2) ?? 0) > 0xff_ff ? 2 : 1);
return [
{
key: 'ai-preview-end',
range: {
anchor: { path: textPath, offset: start },
focus: { path: textPath, offset: end },
},
attributes: { 'data-editor-ai-end': '' },
},
];
},
},
});
const scrollAIPreviewEnd = (editor: Editor, draft: HTMLElement | null) => {
const scrollElement = editor.api.dom.scroll();
const target = draft?.querySelector<HTMLElement>('[data-editor-ai-end]');
if (!scrollElement || !target) return;
const scrollBounds = scrollElement.getBoundingClientRect();
const targetBounds = target.getBoundingClientRect();
scrollElement.scrollTop +=
targetBounds.top +
targetBounds.height / 2 -
(scrollBounds.top + scrollBounds.height / 2);
};
export function AIChatEditor({ inline = false }: { inline?: boolean }) {
const editor = useEditor();
const draftRef = React.useRef<HTMLDivElement>(null);
// Supplies the preview plugins; the draft renders as its document.
const aiEditor = useCreateEditor({
plugins: [...BaseEditorKit, AIPreviewEndPlugin],
});
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
// Renders the latest draft when rendering falls behind the stream,
// skipping drafts that were never shown.
const previewDocument = React.useDeferredValue(
React.useMemo(
() => (previewValue.length > 0 ? { children: previewValue } : undefined),
[previewValue]
)
);
// The draft resizes as it streams. Scrolling from the resize callback reads
// layout the browser has already computed, rather than forcing it after
// every render.
React.useEffect(() => {
const draft = draftRef.current;
const Observer = draft?.ownerDocument.defaultView?.ResizeObserver;
if (!inline || !draft || !Observer) return undefined;
const observer = new Observer(() => scrollAIPreviewEnd(editor, draft));
observer.observe(draft);
return () => observer.disconnect();
}, [editor, inline]);
const last = previewDocument
? NodeApi.last({ children: previewDocument.children, type: '' }, [])[0]
: null;
// Rendering reads every block's decorations, so the preview renders only
// when its document or appearance changes, not on each update's urgent pass.
const preview = React.useMemo(
() => (
<EditorStatic
variant={inline ? 'none' : 'aiChat'}
document={previewDocument}
editor={aiEditor}
className={cn(
'[&_[data-editor-string]]:border-b-2 [&_[data-editor-string]]:border-b-purple-100 [&_[data-editor-string]]:bg-purple-50 [&_[data-editor-string]]:text-purple-800',
streaming &&
'[&_[data-editor-ai-end]]:after:ms-1.5 [&_[data-editor-ai-end]]:after:inline-block [&_[data-editor-ai-end]]:after:size-3 [&_[data-editor-ai-end]]:after:rounded-full [&_[data-editor-ai-end]]:after:bg-purple-600 [&_[data-editor-ai-end]]:after:align-middle [&_[data-editor-ai-end]]:after:content-[""]'
)}
/>
),
[aiEditor, inline, previewDocument, streaming]
);
const endWithoutText =
streaming && (!last || !TextApi.isText(last) || !last.text);
return (
<div ref={draftRef} data-editor-ai-draft="">
{preview}
{/* Stays mounted: adding or removing it flips whether the preview is
the last child, and `:last-child` descendant rules then restyle the
whole preview. */}
<span
data-editor-ai-end={endWithoutText ? '' : undefined}
className={cn(
'size-3 rounded-full bg-purple-600 align-middle',
endWithoutText ? 'inline-block' : 'hidden'
)}
/>
</div>
);
}
const resolveSelectionAnchor = (editor: ReturnType<typeof useEditor>) => {
const block = editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
return block && ElementApi.isElement(block[0])
? editor.api.dom.resolveDOMNode(block[0])
: null;
};
export function AIMenu() {
const editor = useEditor();
const { api, read } = useEditor().plugin(AIChatPlugin);
const mode = usePluginStore(AIChatPlugin, 'mode');
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const streaming = usePluginStore(AIChatPlugin, 'streaming');
const editAnchorKey = useEditorSelector((innerEditor) => {
const entry = innerEditor.read.selection.nodes().at(-1);
return entry && ElementApi.isElement(entry[0])
? innerEditor.key(entry[0])
: null;
});
const isFocusedLast = useFocusedLast();
const chatOpen = usePluginStore(AIChatPlugin, 'open');
const open = chatOpen && isFocusedLast;
const [value, setValue] = React.useState('');
const [input, setInput] = React.useState('');
const chat = usePluginStore(AIChatPlugin, 'chat');
const previewValue = usePluginStore(AIChatPlugin, 'previewValue');
const messages = chat?.messages;
const status = chat?.status ?? 'ready';
const [anchorElement, setAnchorElement] = React.useState<HTMLElement | null>(
null
);
React.useEffect(() => {
if (!streaming && previewValue.length === 0) return undefined;
const anchorEntry = read.node();
if (!anchorEntry) return undefined;
const anchorDom = editor.api.dom.resolveDOMNode(anchorEntry[0]);
if (!anchorDom) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(
anchorDom.closest<HTMLElement>('[data-editor-ai-preview-wrapper]') ??
anchorDom
);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editor, previewValue, read, streaming]);
const setOpen = (innerOpen: boolean) => {
if (innerOpen) {
if (!chatOpen) api.show();
} else if (chatOpen) {
api.hide({ focus: false });
}
};
React.useEffect(() => {
if (!chatOpen) {
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(null);
setInput('');
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}
const nextAnchor = resolveSelectionAnchor(editor);
if (!nextAnchor) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [chatOpen, editor]);
const children = useEditorSelector((innerEditor) =>
chatOpen ? innerEditor.read.children() : null
);
React.useEffect(() => {
if (!chatOpen || !anchorElement) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
if (anchorElement.isConnected) return;
const nextAnchor = resolveSelectionAnchor(editor);
if (nextAnchor) setAnchorElement(nextAnchor);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [anchorElement, chatOpen, children, editor]);
const isLoading = status === 'streaming' || status === 'submitted';
React.useEffect(() => {
if (toolName !== 'edit' || mode !== 'chat' || isLoading) return undefined;
let anchorNode = editAnchorKey
? editor.read.nodes.get(editAnchorKey, {
match: ElementApi.isElement,
})
: undefined;
if (!anchorNode) {
anchorNode =
editor.read.nodes.blocks().at(-1) ?? editor.read.nodes.block();
}
if (!anchorNode) return undefined;
const block = editor.read.nodes.block({ at: anchorNode[1] });
const domNode = block ? editor.api.dom.resolveDOMNode(block[0]) : null;
if (!domNode) return undefined;
const animationFrame = window.requestAnimationFrame(() => {
setAnchorElement(domNode);
});
return () => {
window.cancelAnimationFrame(animationFrame);
};
}, [editAnchorKey, editor, isLoading, mode, toolName]);
if (isLoading && mode === 'insert') return null;
if (toolName === 'comment') return null;
if (!anchorElement) return null;
return (
<FloatingPopover open={open} onOpenChange={setOpen} modal={false}>
<FloatingPopoverAnchor element={anchorElement} />
<FloatingPopoverContent
className="w-(--floating-popover-anchor-width) max-w-[calc(100vw-16px)] border-none bg-transparent p-0 shadow-none ring-0"
onEscapeKeyDown={(e) => {
e.preventDefault();
api.hide();
}}
align="center"
side="bottom"
>
<Command
className="w-full rounded-lg border shadow-md"
value={value}
onValueChange={setValue}
>
{mode === 'chat' && previewValue.length > 0 && <AIChatEditor />}
{isLoading ? (
<div className="flex grow items-center gap-2 p-2 text-sm text-muted-foreground select-none">
<Loader2Icon className="size-4 animate-spin" />
{(messages?.length ?? 0) > 1 ? 'Editing...' : 'Thinking...'}
</div>
) : (
<CommandPrimitive.Input
className={cn(
'flex h-9 w-full min-w-0 border-input bg-transparent px-3 py-1 text-base outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
'border-b focus-visible:ring-transparent'
)}
value={input}
onKeyDown={(e) => {
if (isHotkey('backspace')(e) && input.length === 0) {
e.preventDefault();
api.hide();
}
if (isHotkey('enter')(e) && !e.shiftKey && !value) {
e.preventDefault();
api.submit(input);
setInput('');
}
}}
onValueChange={setInput}
placeholder="Ask AI anything..."
data-editor-keep-selection-visible
autoFocus
/>
)}
{!isLoading && (
<CommandList>
<AIMenuItems
input={input}
setInput={setInput}
setValue={setValue}
/>
</CommandList>
)}
</Command>
</FloatingPopoverContent>
</FloatingPopover>
);
}
type EditorChatState =
| 'cursorCommand'
| 'cursorSuggestion'
| 'selectionCommand'
| 'selectionSuggestion';
const AICommentIcon = () => (
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M0 0h24v24H0z" fill="none" stroke="none" />
<path d="M8 9h8" />
<path d="M8 13h4.5" />
<path d="M10 19l-1 -1h-3a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v4.5" />
<path d="M17.8 20.817l-2.172 1.138a.392 .392 0 0 1 -.568 -.41l.415 -2.411l-1.757 -1.707a.389 .389 0 0 1 .217 -.665l2.428 -.352l1.086 -2.193a.392 .392 0 0 1 .702 0l1.086 2.193l2.428 .352a.39 .39 0 0 1 .217 .665l-1.757 1.707l.414 2.41a.39 .39 0 0 1 -.567 .411l-2.172 -1.138z" />
</svg>
);
const focusEditorOnceClosed = (editor: Editor) => {
if (!editor.plugin(AIChatPlugin).store.get('open')) editor.api.dom.focus();
};
const aiChatItems = {
accept: {
icon: <Check />,
label: 'Accept',
value: 'accept',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.accept();
focusEditorOnceClosed(editor);
},
},
comment: {
icon: <AICommentIcon />,
label: 'Comment',
value: 'comment',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt:
'Please comment on the following content and provide reasonable and meaningful feedback.',
toolName: 'comment',
});
},
},
continueWrite: {
icon: <PenLine />,
label: 'Continue writing',
value: 'continueWrite',
onSelect: ({ editor, input }) => {
const ancestorNode = editor.read.nodes.block();
if (!ancestorNode) return;
const isEmpty = NodeApi.string(ancestorNode[0]).trim().length === 0;
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: isEmpty
? `<Document>
{editor}
</Document>
Start writing a new paragraph AFTER <Document> ONLY ONE SENTENCE`
: `<Block>
{block}
</Block>
Continue writing AFTER <Block> with ONLY ONE SENTENCE. DO NOT REPEAT THE TEXT.`,
toolName: 'generate',
});
},
},
discard: {
icon: <X />,
label: 'Discard',
shortcut: 'Escape',
value: 'discard',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.hide();
},
},
emojify: {
icon: <SmileIcon />,
label: 'Emojify',
value: 'emojify',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Add a small number of contextually relevant emojis within each block only. You may insert emojis, but do not remove, replace, or rewrite existing text, and do not modify Markdown syntax, links, or line breaks.',
toolName: 'edit',
});
},
},
explain: {
icon: <BadgeHelp />,
label: 'Explain',
value: 'explain',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: {
default: 'Explain {editor}',
selecting: 'Explain',
},
toolName: 'generate',
});
},
},
fixSpelling: {
icon: <Check />,
label: 'Fix spelling & grammar',
value: 'fixSpelling',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Fix spelling, grammar, and punctuation errors within each block only, without changing meaning, tone, or adding new information.',
toolName: 'edit',
});
},
},
generateMarkdownSample: {
icon: <BookOpenCheck />,
label: 'Generate Markdown sample',
value: 'generateMarkdownSample',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt: 'Generate a markdown sample',
toolName: 'generate',
});
},
},
improveWriting: {
icon: <Wand />,
label: 'Improve writing',
value: 'improveWriting',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Improve the writing for clarity and flow, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
insertBelow: {
icon: <ListEnd />,
label: 'Insert below',
value: 'insertBelow',
onSelect: ({ editor }) => {
/** Format: 'none' Fix insert table */
editor.plugin(AIChatPlugin).api.insertBelow({ format: 'none' });
focusEditorOnceClosed(editor);
},
},
makeLonger: {
icon: <ListPlus />,
label: 'Make longer',
value: 'makeLonger',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content longer by elaborating on existing ideas within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
makeShorter: {
icon: <ListMinus />,
label: 'Make shorter',
value: 'makeShorter',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Make the content shorter by reducing verbosity within each block only, without changing meaning or removing essential information.',
toolName: 'edit',
});
},
},
replace: {
icon: <Check />,
label: 'Replace selection',
value: 'replace',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.replaceSelection();
focusEditorOnceClosed(editor);
},
},
simplifyLanguage: {
icon: <FeatherIcon />,
label: 'Simplify language',
value: 'simplifyLanguage',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
prompt:
'Simplify the language by using clearer and more straightforward wording within each block only, without changing meaning or adding new information.',
toolName: 'edit',
});
},
},
summarize: {
icon: <Album />,
label: 'Add a summary',
value: 'summarize',
onSelect: ({ editor, input }) => {
editor.plugin(AIChatPlugin).api.submit(input, {
mode: 'insert',
prompt: {
default: 'Summarize {editor}',
selecting: 'Summarize',
},
toolName: 'generate',
});
},
},
tryAgain: {
icon: <CornerUpLeft />,
label: 'Try again',
value: 'tryAgain',
onSelect: ({ editor }) => {
editor.plugin(AIChatPlugin).api.reload();
},
},
} satisfies Record<
string,
{
icon: React.ReactNode;
label: string;
value: string;
component?: React.ComponentType<{ menuState: EditorChatState }>;
filterItems?: boolean;
items?: Array<{ label: string; value: string }>;
shortcut?: string;
onSelect?: ({ editor, input }: { editor: Editor; input: string }) => void;
}
>;
const menuStateItems: Record<
EditorChatState,
Array<{
items: Array<(typeof aiChatItems)[keyof typeof aiChatItems]>;
heading?: string;
}>
> = {
cursorCommand: [
{
items: [
aiChatItems.comment,
aiChatItems.generateMarkdownSample,
aiChatItems.continueWrite,
aiChatItems.summarize,
aiChatItems.explain,
],
},
],
cursorSuggestion: [
{
items: [aiChatItems.accept, aiChatItems.discard, aiChatItems.tryAgain],
},
],
selectionCommand: [
{
items: [
aiChatItems.improveWriting,
aiChatItems.comment,
aiChatItems.emojify,
aiChatItems.makeLonger,
aiChatItems.makeShorter,
aiChatItems.fixSpelling,
aiChatItems.simplifyLanguage,
],
},
],
selectionSuggestion: [
{
items: [
aiChatItems.accept,
aiChatItems.discard,
aiChatItems.insertBelow,
aiChatItems.tryAgain,
],
},
],
};
export const AIMenuItems = ({
input,
setInput,
setValue,
}: {
input: string;
setInput: (value: string) => void;
setValue: (value: string) => void;
}) => {
const editor = useEditor();
const comments = editor.plugin(CommentsPlugin);
const messages = usePluginStore(AIChatPlugin, 'chat')?.messages;
const mode = usePluginStore(AIChatPlugin, 'mode');
const chatNodeMode = usePluginStore(AIChatPlugin, 'chatNodeMode');
const chatSelection = usePluginStore(AIChatPlugin, 'chatSelection');
const isSelecting =
chatNodeMode !== null ||
(!!chatSelection && RangeApi.isExpanded(chatSelection));
const menuState: EditorChatState =
(messages?.length ?? 0) > 0
? mode === 'chat'
? 'selectionSuggestion'
: 'cursorSuggestion'
: isSelecting
? 'selectionCommand'
: 'cursorCommand';
const menuGroups = comments.installed
? menuStateItems[menuState]
: menuStateItems[menuState].map((group) => ({
...group,
items: group.items.filter((item) => item !== aiChatItems.comment),
}));
const firstItemValue = menuGroups[0]?.items[0]?.value;
React.useEffect(() => {
if (firstItemValue) setValue(firstItemValue);
}, [firstItemValue, setValue]);
return (
<>
{menuGroups.map((group) => (
<CommandGroup
key={group.heading ?? group.items[0]?.value}
heading={group.heading}
>
{group.items.map((menuItem) => (
<CommandItem
key={menuItem.value}
className="[&_svg]:text-muted-foreground"
value={menuItem.value}
onSelect={() => {
menuItem.onSelect?.({ editor, input });
setInput('');
}}
>
{menuItem.icon}
<span>{menuItem.label}</span>
</CommandItem>
))}
</CommandGroup>
))}
</>
);
};
export function AILoadingBar() {
const toolName = usePluginStore(AIChatPlugin, 'toolName');
const chat = usePluginStore(AIChatPlugin, 'chat');
const mode = usePluginStore(AIChatPlugin, 'mode');
const status = chat?.status ?? 'ready';
const { api } = useEditor().plugin(AIChatPlugin);
const isLoading = status === 'streaming' || status === 'submitted';
if (isLoading && (mode === 'insert' || toolName === 'comment')) {
return (
<div
className={cn(
'fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit items-center gap-3 rounded-md border border-border bg-muted px-3 py-1.5 text-muted-foreground text-sm shadow-md transition-all duration-300'
)}
>
<span className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
<span>{status === 'submitted' ? 'Thinking...' : 'Writing...'}</span>
<Button
size="sm"
variant="ghost"
className="flex items-center gap-1 text-xs"
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return;
event.preventDefault();
event.stopPropagation();
api.stop();
}}
onClick={() => {
api.stop();
}}
>
<PauseIcon className="h-4 w-4" />
Stop
<kbd className="ms-1 rounded bg-border px-1 font-mono text-[10px] text-muted-foreground shadow-sm">
Esc
</kbd>
</Button>
</div>
);
}
if (toolName === 'comment' && status === 'error') {
return (
<div
className="fixed inset-x-0 bottom-4 z-50 mx-auto flex w-fit max-w-[calc(100vw-2rem)] flex-wrap items-center gap-2 rounded-lg border bg-popover p-2 text-sm shadow-lg"
data-ai-comment-error=""
data-editor-keep-selection-visible
>
<p className="w-full px-1 text-destructive" role="alert">
Could not generate comments.
</p>
<Button onClick={() => api.reload()} size="sm" variant="outline">
Try again
</Button>
<Button onClick={() => api.hide()} size="sm" variant="outline">
<X data-icon="inline-start" />
Dismiss
</Button>
</div>
);
}
return null;
}
toArray
({
at: [],
type: headingTypes,
});
const prompt =
headings.length === 0
? 'Create a realistic table of contents for this document'
: 'Generate a table of contents that reflects the existing headings';
void editor.plugin(AIChatPlugin).api.submit('', {
mode: 'insert',
prompt,
toolName: 'generate',
});
},
},
};