url and provider, with an optional sourceUrl preserved for reversible editing.The fastest way to add comprehensive media support is with the MediaKit,
which includes pre-configured ImagePlugin, VideoPlugin, AudioPlugin,
FilePlugin, MediaEmbedPlugin, and PlaceholderPlugin with their
Plate UI components.
'use client';
import { generateReactHelpers } from '@uploadthing/react';
import { UploadErrorCode } from 'platejs/media';
import {
PlaceholderPlugin,
AudioPlugin,
FilePlugin,
MediaEmbedPlugin,
VideoPlugin,
} from 'platejs/media/react';
import { usePluginStore } from 'platejs/react';
import * as React from 'react';
import { toast } from 'sonner';
import { AudioElement } from '@/components/editor/media-audio';
import { MediaEmbedElement } from '@/components/editor/media-embed';
import { FileElement }
'use client';
import { generateReactHelpers } from '@uploadthing/react';
import { UploadErrorCode } from 'platejs/media';
import {
PlaceholderPlugin,
AudioPlugin,
FilePlugin,
MediaEmbedPlugin,
VideoPlugin,
} from 'platejs/media/react';
import { usePluginStore } from 'platejs/react';
import * as React from 'react';
import { toast } from 'sonner';
import { AudioElement } from '@/components/editor/media-audio';
import { MediaEmbedElement } from '@/components/editor/media-embed'
ImageElement: Renders image elements.VideoElement: Renders video elements.AudioElement: Renders audio elements.FileElement: Renders file elements.MediaEmbedElement: Renders embedded media.PlaceholderElement: Renders upload placeholders.MediaUploadToast: Shows file validation errors.MediaPreviewDialog: Provides media preview functionality.Add the kit to your plugins:
import { createEditor } from 'platejs/react';
import { MediaKit } from '@/components/editor/media';
const editor = createEditor({
plugins: [
// ...otherPlugins,
...MediaKit,
],
});import { createEditor } from 'platejs/react';
import { MediaKit } from '@/components/editor/media';
const editor = createEditor
Get your secret key from UploadThing and add it to .env:
UPLOADTHING_TOKEN=xxxUPLOADTHING_TOKEN=xxxInclude the media plugins in your Plate plugins array when creating the editor.
import { AudioPlugin, FilePlugin, ImagePlugin, MediaEmbedPlugin, PlaceholderPlugin, VideoPlugin } from 'platejs/media/react';
import { createEditor } from 'platejs/react';
const editor = createEditor({
plugins: [
// ...otherPlugins,
ImagePlugin,
VideoPlugin,
AudioPlugin,
FilePlugin,
MediaEmbedPlugin,
PlaceholderPlugin,
],
});import
Configure the plugins with custom components and upload settings.
import { AudioPlugin, FilePlugin, ImagePlugin, MediaEmbedPlugin, PlaceholderPlugin, VideoPlugin } from 'platejs/media/react';
import { createEditor } from 'platejs/react';
import { AudioElement } from '@/components/editor/media-audio';
import { FileElement } from '@/components/editor/media-file';
import { ImageElement } from '@/components/editor/media-image';
import { MediaEmbedElement } from '@/components/editor/media-embed';
import { PlaceholderElement } from '@/components/editor/media-placeholder';
import { VideoElement } from '@/components/editor/media-video';
import { MediaUploadToast } from '@/components/editor/media';
const editor = createEditor({
component: Assigns custom components to render each media type.initialState.disableEmptyPlaceholder: Starts a separate undo batch when inserting upload placeholders.slots.afterEditable: Renders file validation errors outside the editor.Note: When serialized to Markdown or MDX, embeds persist the canonical url and provider, plus an optional sourceUrl so edits remain reversible. Allowlisted provider snippets (e.g. YouTube, Tweet) are reduced to canonical URLs on paste. Raw <script> or custom embed chrome is out of scope — add your own rules if you need to preserve it.
Every image, audio, video, file, and embed is a non-void, isolating, keyboard-selectable element. Its direct inline children are the caption; the media plugin owns the schema and behavior, with no separate caption plugin, node type, or content root.
Configure only the media plugin and its renderer:
import { ImagePlugin } from 'platejs/media/react';
import { ImageElement } from '@/components/editor/media-image';
export const MediaKit = [
ImagePlugin.configure({ component: ImageElement }),
];import { ImagePlugin } from 'platejs/media/react';
import { ImageElement } from '@/components/editor/media-image';
export const MediaKit = [
ImagePlugin.configure
Keep the asset DOM non-editable and render the media element's ordinary child slot as the caption:
<figure>
<div contentEditable={false}>{/* media chrome */}</div>
<figcaption>{props.children}</figcaption>
</figure><figure>
<div contentEditable={false}>{/* media chrome */}</div>
<figcaption>{props.children}</figcaption>
</figure>Pass a string or inline children through the construction-only caption field:
editor.plugin(ImagePlugin).update.insert({
url: 'https://example.com/image.png',
caption: 'Plain caption',
});
editor.plugin(ImagePlugin).update.insert({
url: 'https://example.com/diagram.png',
caption: [
{ text: 'Rich ' },
{ text: 'caption', bold: true },
],
});editor.plugin
The insert command compiles caption into direct children. Persist only the
resulting media element:
{
type: 'image',
url: 'https://example.com/image.png',
children: [{ text: 'Plain caption' }],
}{
type: 'image',
url: 'https://example.com/image.png',
children: [{ text: 'Plain caption' }],
}An empty text child is the canonical absent-caption state:
{
type: 'image',
url: 'https://example.com/image.png',
children: [{ text: '' }],
}{
type: 'image',
url: 'https://example.com/image.png',
children: [{ text: '' }],
}The renderer can hide that empty caption until the media asset is focused.
Placeholder visibility is UI state and does not change the persisted element.
Shared media nodes persist url, optional rendered width, and direct caption children. Only FileElement adds optional name; Image, Audio, Video, and Media Embed do not inherit filename metadata.
Asset focus and caption editing are separate selection states:
| Selection | Behavior |
|---|---|
Plate NodeSelection at the media path | Focuses the asset, shows its selection ring and empty-caption placeholder, lets ArrowDown enter the caption, and lets Delete remove the media node. |
Plate TextSelection inside the media children | Edits the caption and lets ArrowUp at the caption start return focus to the asset. |
Configure initialState.upload with your upload transport. The placeholder
plugin owns cancellation, progress and replacement of the same live node.
Your endpoint must accept the file and return its public url.
import { PlaceholderPlugin } from 'platejs/media/react';
PlaceholderPlugin.configure({
initialState: {
upload: async (file, { signal, onProgress }) => {
const body = new FormData();
body.append('file', file);
const response = await fetch('/api/upload', {
body,
method: 'POST',
signal,
});
if (!response.ok) throw new Error('Upload failed.'
Pass signal to your transport and report progress from 0 to 100. The result
accepts optional name, naturalWidth and naturalHeight metadata. Image
replacement does not wait for a rendered preview to load. A rejected request
leaves the placeholder in place and exposes the error; no fallback URL is
created. A missing transport also produces a failed task.
Call editor.plugin(PlaceholderPlugin).api.upload(key, file) to upload into an
existing placeholder, and api.cancelUpload(key) to cancel it. Obtain the live
NodeKey with editor.key(element). File insertion starts uploads only after
the document transaction commits.
The copied PlaceholderElement already subscribes to its task. A custom React
view can use usePluginStore from platejs/react and React.useSyncExternalStore:
const task = usePluginStore(PlaceholderPlugin, 'uploadTask', editor.key(element));
const upload = React.useSyncExternalStore(
React.useCallback((notify) => task?.subscribe(notify) ?? (() => {}), [task]),
React.useCallback(() => task?.getSnapshot() ?? null, [task]),
() => null
);
task.file identifies the request. The snapshot contains status, progress
and error. Unsubscribing or remounting a view does not restart the upload.
BasePlaceholderPlugin exposes the same upload operations from platejs/media
for headless consumers. Transport and task types are exported from that subpath.
You can add MediaToolbarButton to your Toolbar to upload and insert media.
You can add these items to the Insert Toolbar Button to insert media elements:
{
icon: <ImageIcon />,
label: 'Image',
value: PLUGINS.image,
}{
icon: <ImageIcon />,
label: 'Image',
value: PLUGINS.image,
}Plugin for non-void, isolating, keyboard-selectable image elements whose direct inline children store captions.
Function to upload image to a server. Receives:
FileReader.readAsDataURLDisables file upload on data insertion.
falseDisables URL embed on data insertion.
falseA function to check whether a text string is a URL.
A function to transform the URL.
Plugin for non-void, isolating, keyboard-selectable video elements whose direct
inline children store captions. Extends MediaPluginState.
Plugin for non-void, isolating, keyboard-selectable audio elements whose direct
inline children store captions. Extends MediaPluginState.
Plugin for non-void, isolating, keyboard-selectable file elements whose direct
inline children store captions. Extends MediaPluginState.
Plugin for non-void, isolating, keyboard-selectable media embed elements whose
direct inline children store captions. Extends MediaPluginState.
Plugin for managing media placeholders during upload. Handles file uploads, drag & drop, and clipboard paste events.
Upload transport returning a URL and optional file metadata. Receives the file, an abort signal and a progress callback. Configure it before inserting files.
Configuration for different file types. The package maps every supported file
family to its media plugin without imposing size or per-type count limits. The
copied MediaKit applies this product policy:
{
audio: {
maxFileCount: 1,
maxFileSize: '8MB',
mediaType: 'audio',
minFileCount: 1,
},
blob: {
maxFileCount: 1,
maxFileSize: '8MB',
mediaType: 'file',
minFileCount: 1,
},
image: {
maxFileCount: 3,
maxFileSize: '4MB',
mediaType: 'image',
minFileCount: 1,
},
pdf: {
maxFileCount: 1,
maxFileSize: '4MB',
mediaType: 'file',
minFileCount: 1,
},
text: {
maxFileCount: 1,
maxFileSize: '64KB',
mediaType: 'file',
minFileCount: 1,
},
video: {
maxFileCount: 1,
maxFileSize: '16MB',
mediaType: 'video',
minFileCount: 1,
},
}{
audio: {
maxFileCount: 1,
maxFileSize: '8MB',
mediaType: 'audio',
minFileCount: 1,
},
blob: {
maxFileCount: 1,
maxFileSize: '8MB',
mediaType: 'file',
minFileCount: 1,
},
image: {
maxFileCount: 3,
maxFileSize: '4MB',
mediaType: 'image',
minFileCount
Supported file types: 'image' | 'video' | 'audio' | 'pdf' | 'text' | 'blob'
Starts a separate undo batch when inserting upload placeholders.
falseEnables the placeholder DOM drop handler when the DnD plugin does not handle file drops.
falseMaximum number of files that can be uploaded at once, if not specified by uploadConfig.
Number.POSITIVE_INFINITYAllow multiple files of the same type to be uploaded.
true| Operation | Contract |
|---|---|
editor.plugin(PlaceholderPlugin).api.upload(key, file) | Validates the file type and size, then starts an upload for the live placeholder. Supersedes its previous request. |
editor.plugin(PlaceholderPlugin).api.cancelUpload(key) | Aborts that request and removes its task. Late callbacks cannot replace the node. |
editor.plugin(PlaceholderPlugin).store.get('uploadTask', key) | Returns MediaUpload or undefined; its file, getSnapshot and subscribe support custom progress UI. |
key is a live NodeKey, not a persisted element ID or path. Completed uploads
replace only the original placeholder. Removed nodes, changed media types and
readonly editors cannot accept a late result. A failed task remains available
until it is cancelled, retried or its placeholder is removed.
Inserts media files into the editor with upload placeholders.
Validates files against configured limits (size, count, type), creates placeholder elements for each file, starts each upload after the insertion commits, and reports validation errors.
Error codes:
enum UploadErrorCode {
INVALID_FILE_TYPE = 400,
TOO_MANY_FILES = 402,
INVALID_FILE_SIZE = 403,
TOO_LESS_FILES = 405,
TOO_LARGE = 413,
}enum UploadErrorCode {
INVALID_FILE_TYPE = 400,
TOO_MANY_FILES = 402,
INVALID_FILE_SIZE = 403,
TOO_LESS_FILES = 405,
TOO_LARGE = 413,
}Inserts one headless placeholder for an image, video, audio, or file.
Inserts an image element into the editor.
Transforms and normalizes a URL, then inserts a media embed.
The selected media plugin captures the insertion target while the application
resolves URL input. Image, embed, audio, video and file plugins expose this API.
The operation calls the installed update.insert, including its URL validation
and application overrides. It returns false for cancelled or invalid input or
a removed target. A rejected resolver promise propagates to the caller.
const inserted = await editor.plugin(BaseImagePlugin).api.insertUrl(
getUrlFromDialog,
{ caption: 'An optional caption', select: true }
);const inserted = await editor.plugin(BaseImagePlugin).api.insertUrl(
getUrlFromDialog,
{ caption: 'An optional caption', select: true }
);getUrlFromDialog is an application function returning a URL, null, or a promise
of either. Options accept the insertion at location, after source block,
replaceEmpty, caption and select. With replaceEmpty: true, the captured
source is replaced only if it is still empty when the URL resolves. Moves and
intervening text edits preserve the source identity and content.
The application owns the URL dialog and selects the media plugin.
media-toolbar owns URL editing, submission, cancellation, and focus restore.
Each copied media node reads its typed element and primitive editor state
directly. media-image renders the image and opens
media-preview-dialog, which owns preview navigation, scale, translation, and
download behavior.
'use client';
import { Link, Trash2Icon } from 'lucide-react';
import type { MediaPlugin } from 'platejs/media/react';
import {
useEditor,
useElement,
useEditorReadOnly,
useFocusedLast,
} from 'platejs/react';
import * as React from 'react';
import { Button, buttonVariants } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import {
FloatingPopover,
FloatingPopoverAnchor,
FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { CaptionButton } from './caption';
function MediaToolbarContent({ plugin }: { plugin: MediaPlugin }) {
const editor = useEditor();
const element = useElement(plugin);
const [isEditing, setIsEditing] = React.useState(false);
const [url, setUrl] = React.useState('');
const reset = () => {
setUrl('');
setIsEditing(false);
};
if (isEditing) {
return (
<div className="flex w-[330px] flex-col">
<div className="flex items-center">
<div className="flex items-center pr-1 pl-2 text-muted-foreground">
<Link className="size-4" />
</div>
<Input
className="h-7 border-none bg-transparent px-1.5 py-1 focus-visible:ring-transparent"
value={url}
placeholder="Paste the embed link..."
onChange={(event) => {
setUrl(event.target.value);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
if (
url !== element.url &&
!editor.plugin(plugin).update.setUrl({ element, url })
) {
return;
}
reset();
editor.api.dom.focus();
}
if (event.key === 'Escape') {
reset();
editor.api.dom.focus();
}
}}
autoFocus
/>
</div>
</div>
);
}
return (
<div className="box-content flex items-center">
<Button
className={buttonVariants({ size: 'sm', variant: 'ghost' })}
onClick={() => {
const sourceUrl =
'sourceUrl' in element && typeof element.sourceUrl === 'string'
? element.sourceUrl
: undefined;
setUrl(sourceUrl ?? element.url);
setIsEditing(true);
}}
>
Edit link
</Button>
<CaptionButton size="sm" variant="ghost">
Caption
</CaptionButton>
<Separator orientation="vertical" className="mx-1 h-6" />
<Button
size="sm"
variant="ghost"
onClick={() => {
editor.update.nodes.remove({ at: element });
editor.api.dom.focus();
}}
onMouseDown={(event) => {
event.preventDefault();
}}
>
<Trash2Icon />
</Button>
</div>
);
}
export function MediaToolbar({
children,
disabled = false,
plugin,
selected,
}: {
children: React.ReactElement;
disabled?: boolean;
plugin: MediaPlugin;
selected: boolean;
}) {
const isFocusedLast = useFocusedLast();
const readOnly = useEditorReadOnly();
const open = isFocusedLast && !readOnly && selected && !disabled;
return (
<FloatingPopover open={open} modal={false}>
<FloatingPopoverAnchor element={children} />
<FloatingPopoverContent
className="w-auto p-1"
onInitialFocus={(e) => {
e.preventDefault();
}}
>
{open ? <MediaToolbarContent plugin={plugin} /> : null}
</FloatingPopoverContent>
</FloatingPopover>
);
}'use client';
import { Link, Trash2Icon } from 'lucide-react';
import type { MediaPlugin } from 'platejs/media/react';
import {
useEditor,
useElement,
useEditorReadOnly,
useFocusedLast,
} from 'platejs/react';
import * as React from 'react';
import { Button, buttonVariants } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import {
FloatingPopover,
FloatingPopoverAnchor,
'use client';
import { useDraggable } from 'platejs/dnd/react';
import { ImagePlugin } from 'platejs/media/react';
import {
EditorElement,
useEditor,
useEditorFocused,
useElementSelected,
usePath,
usePluginStore,
type EditorElementProps,
} from 'platejs/react';
import * as React from 'react';
import { cn } from '@/lib/utils';
import { Caption, useCaptionFocused } from './caption';
import { imagePlugin } from './media-preview-dialog';
import { MediaToolbar } from './media-toolbar';
import {
mediaResizeHandleVariants,
Resizable,
ResizeHandle,
} from './resize-handle';
export function ImageElement(props: EditorElementProps<typeof imagePlugin>) {
const path = usePath();
const focused = useEditorFocused();
const selected = useElementSelected({ mode: 'node' });
const textAlign =
'textAlign' in props.element &&
(props.element.textAlign === 'left' ||
props.element.textAlign === 'right' ||
props.element.textAlign === 'center')
? props.element.textAlign
: 'center';
const editor = useEditor();
const captionFocused = useCaptionFocused(path);
const previewOpen = usePluginStore(imagePlugin, 'previewOpen');
const { isDragging, handleRef } = useDraggable({
element: props.element,
});
return (
<MediaToolbar
disabled={previewOpen}
plugin={ImagePlugin}
selected={selected}
>
<EditorElement {...props} className="py-2.5">
<figure className="relative m-0 hover:[&_.editor-media-resize-handle]:after:opacity-100">
<div contentEditable={false}>
<Resizable
align={textAlign}
minWidth={92}
onResizeEnd={(width) => {
editor.plugin(imagePlugin).update.set({ width }, { at: path });
}}
width={props.element.width}
>
<ResizeHandle
className={mediaResizeHandleVariants({ direction: 'left' })}
direction="left"
/>
<div>
{/* oxlint-disable-next-line nextjs/no-img-element -- [P1 local-invariant] The editor node owns a user URL, native draggable image, composed ref, and resizable width. */}
<img
ref={handleRef}
className={cn(
'block w-full max-w-full cursor-pointer object-cover px-0',
'rounded-sm',
focused && selected && 'ring-2 ring-ring ring-offset-2',
isDragging && 'opacity-50'
)}
alt={props.element.alt}
draggable
src={props.element.url}
onDoubleClickCapture={() => {
editor
.plugin(imagePlugin)
.api.preview.open(props.element, props.element.url);
}}
/>
</div>
<ResizeHandle
className={mediaResizeHandleVariants({
direction: 'right',
})}
direction="right"
/>
</Resizable>
</div>
<Caption
active={selected || captionFocused}
align={textAlign}
element={props.element}
slots={props.slots}
>
{props.children}
</Caption>
</figure>
</EditorElement>
</MediaToolbar>
);
}'use client';
import { useDraggable } from 'platejs/dnd/react';
import { ImagePlugin } from 'platejs/media/react';
import {
EditorElement,
useEditor,
useEditorFocused,
useElementSelected,
usePath,
usePluginStore,
type EditorElementProps,
} from 'platejs/react';
import * as React from 'react';
import { cn } from '@/lib/utils';
import { Caption, useCaptionFocused } from './caption';
import { imagePlugin } from './media-preview-dialog';
'use client';
import { cva } from 'class-variance-authority';
import { ArrowLeft, ArrowRight, Download, Minus, Plus, X } from 'lucide-react';
import { type NodeKey, isHotkey } from 'platejs';
import { BaseImagePlugin, type ImageElement } from 'platejs/media';
import { ImagePlugin } from 'platejs/media/react';
import { useComposedRef, useEditor, usePluginStore } from 'platejs/react';
import * as React from 'react';
import { cn } from '@/lib/utils';
const buttonVariants = cva('rounded bg-[rgba(0,0,0,0.5)] px-1', {
defaultVariants: {
variant: 'default',
},
variants: {
variant: {
default: 'text-white',
disabled: 'cursor-not-allowed text-gray-400',
},
},
});
const SCROLL_SPEED = 4;
const DEFAULT_DOWNLOAD_FILENAME = 'image';
const ZOOM_LEVELS = [0, 0.5, 1, 1.5, 2];
type PreviewItem = {
key: NodeKey;
url: string;
};
type ImagePreviewState = {
boundingClientRect: DOMRect | null;
currentPreview: PreviewItem | null;
isEditingScale: boolean;
openEditorId: string | null;
previewList: PreviewItem[];
scale: number;
translate: { x: number; y: number };
};
const createInitialPreviewState = (): ImagePreviewState => ({
boundingClientRect: null,
currentPreview: null,
isEditingScale: false,
openEditorId: null,
previewList: [],
scale: 1,
translate: { x: 0, y: 0 },
});
export const imagePlugin = ImagePlugin.extend({
initialState: { preview: createInitialPreviewState() },
}).extend(({ editor, store }) => ({
api: () => ({
preview: {
close: () => {
store.set({ preview: createInitialPreviewState() });
editor.api.dom.focus();
},
next: () => {
const preview = store.get('preview');
const currentIndex = preview.currentPreview
? preview.previewList.findIndex(
(item) =>
item.url === preview.currentPreview?.url &&
item.key === preview.currentPreview.key
)
: -1;
if (
currentIndex >= 0 &&
currentIndex < preview.previewList.length - 1
) {
store.set({
preview: {
...preview,
boundingClientRect: null,
currentPreview: preview.previewList[currentIndex + 1],
isEditingScale: false,
scale: 1,
translate: { x: 0, y: 0 },
},
});
}
},
open: (element: ImageElement, resolvedUrl = element.url) => {
const currentKey = editor.key(element);
if (currentKey == null) return;
store.set({
preview: {
...createInitialPreviewState(),
currentPreview: {
key: currentKey,
url: resolvedUrl,
},
openEditorId: editor.id,
previewList: Array.from(
editor.read.nodes.entries({ at: [], type: BaseImagePlugin })
).flatMap(([node, path]) => {
const key = editor.key(path);
return key == null
? []
: [
{
key,
url: key === currentKey ? resolvedUrl : node.url,
},
];
}),
},
});
},
previous: () => {
const preview = store.get('preview');
const currentIndex = preview.currentPreview
? preview.previewList.findIndex(
(item) =>
item.url === preview.currentPreview?.url &&
item.key === preview.currentPreview.key
)
: -1;
if (currentIndex > 0) {
store.set({
preview: {
...preview,
boundingClientRect: null,
currentPreview: preview.previewList[currentIndex - 1],
isEditingScale: false,
scale: 1,
translate: { x: 0, y: 0 },
},
});
}
},
setEditingScale: (isEditingScale: boolean) => {
const preview = store.get('preview');
store.set({ preview: { ...preview, isEditingScale } });
},
setScale: (scale: number) => {
const preview = store.get('preview');
store.set({
preview: {
...preview,
boundingClientRect: scale <= 1 ? null : preview.boundingClientRect,
scale,
translate: scale <= 1 ? { x: 0, y: 0 } : preview.translate,
},
});
},
setTranslate: (translate: { x: number; y: number }) => {
const preview = store.get('preview');
store.set({ preview: { ...preview, translate } });
},
zoomIn: () => {
const preview = store.get('preview');
const scale = ZOOM_LEVELS.find((target) => preview.scale < target);
if (scale !== undefined) {
store.set({ preview: { ...preview, scale } });
}
},
zoomOut: () => {
const preview = store.get('preview');
const scale = ZOOM_LEVELS.findLast((target) => preview.scale > target);
if (scale !== undefined) {
store.set({
preview: {
...preview,
boundingClientRect:
scale <= 1 ? null : preview.boundingClientRect,
scale,
translate: scale <= 1 ? { x: 0, y: 0 } : preview.translate,
},
});
}
},
},
}),
selectors: {
previewOpen: (state) => state.preview.openEditorId === editor.id,
},
}));
export function MediaPreviewDialog() {
const { api } = useEditor().plugin(imagePlugin);
const preview = usePluginStore(imagePlugin, 'preview');
const isOpen = usePluginStore(imagePlugin, 'previewOpen');
const {
boundingClientRect,
currentPreview,
isEditingScale,
previewList,
scale,
translate,
} = preview;
const currentPreviewIndex = currentPreview
? previewList.findIndex(
(item) =>
item.url === currentPreview.url && item.key === currentPreview.key
)
: null;
const prevDisabled = currentPreviewIndex === 0;
const nextDisabled = currentPreviewIndex === previewList.length - 1;
const zoomOutDisabled = scale <= 0.5;
const zoomInDisabled = scale >= 2;
const downloadDisabled = !currentPreview?.url;
React.useEffect(() => {
if (!isOpen) return undefined;
const onWheel = (event: WheelEvent) => {
if (scale <= 1 || !boundingClientRect) return;
event.preventDefault();
const { deltaX, deltaY } = event;
const { x, y } = translate;
const { bottom, left, right, top } = boundingClientRect;
let nextX = x - deltaX / SCROLL_SPEED;
let nextY = y - deltaY / SCROLL_SPEED;
if (left - deltaX / SCROLL_SPEED > window.innerWidth / 2 && deltaX < 0) {
nextX = x;
}
if (right - deltaX / SCROLL_SPEED < window.innerWidth / 2 && deltaX > 0) {
nextX = x;
}
if (top - deltaY / SCROLL_SPEED > window.innerHeight / 2 && deltaY < 0) {
nextY = y;
}
if (
bottom - deltaY / SCROLL_SPEED < window.innerHeight / 2 &&
deltaY > 0
) {
nextY = y;
}
api.preview.setTranslate({ x: nextX, y: nextY });
};
document.addEventListener('wheel', onWheel, { passive: false });
return () => {
document.removeEventListener('wheel', onWheel);
};
}, [api.preview, boundingClientRect, isOpen, scale, translate]);
React.useEffect(() => {
if (!isOpen) return undefined;
const onKeyDown = (event: KeyboardEvent) => {
if (!isHotkey('escape')(event)) return;
event.stopPropagation();
api.preview.close();
};
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
};
}, [api.preview, isOpen]);
const handleDownload = () => {
if (!currentPreview?.url) return;
const link = document.createElement('a');
link.download = getImageDownloadFilename(currentPreview.url);
link.href = currentPreview.url;
link.rel = 'noopener noreferrer';
document.body.append(link);
link.click();
link.remove();
};
return (
<div
className={cn(
'fixed top-0 left-0 z-50 h-screen w-screen select-none',
!isOpen && 'hidden'
)}
onContextMenu={(e) => {
e.stopPropagation();
}}
>
<button
aria-label="Close preview"
className="absolute inset-0 size-full border-0 bg-black p-0 opacity-60"
onClick={api.preview.close}
type="button"
/>
<div className="absolute inset-0 flex items-center justify-center">
<div className="relative flex max-h-screen w-full items-center">
<PreviewImage
className={cn(
'mx-auto block max-h-[calc(100vh-4rem)] w-auto object-contain transition-transform'
)}
/>
<div className="absolute bottom-0 left-1/2 z-40 flex w-fit -translate-x-1/2 justify-center gap-4 p-2 text-center text-white">
<div className="flex gap-1">
<button
aria-label="Previous image"
className={cn(
buttonVariants({
variant: prevDisabled ? 'disabled' : 'default',
})
)}
disabled={prevDisabled}
onClick={api.preview.previous}
type="button"
>
<ArrowLeft />
</button>
{(currentPreviewIndex ?? 0) + 1}
<button
aria-label="Next image"
className={cn(
buttonVariants({
variant: nextDisabled ? 'disabled' : 'default',
})
)}
disabled={nextDisabled}
onClick={api.preview.next}
type="button"
>
<ArrowRight />
</button>
</div>
<div className="flex">
<button
aria-label="Zoom out"
className={cn(
buttonVariants({
variant: zoomOutDisabled ? 'disabled' : 'default',
})
)}
disabled={zoomOutDisabled}
onClick={api.preview.zoomOut}
type="button"
>
<Minus className="size-4" />
</button>
<div className="mx-px">
{isEditingScale ? (
<>
<ScaleInput
key={scale}
className="w-10 rounded px-1 text-slate-500 outline"
scale={scale}
onCommit={(nextScale) => {
api.preview.setScale(nextScale);
api.preview.setEditingScale(false);
}}
/>{' '}
<span>%</span>
</>
) : (
<button
aria-label="Set zoom level"
className="border-0 bg-transparent p-0 text-inherit"
onClick={() => {
api.preview.setEditingScale(true);
}}
type="button"
>
{`${scale * 100}%`}
</button>
)}
</div>
<button
aria-label="Zoom in"
className={cn(
buttonVariants({
variant: zoomInDisabled ? 'disabled' : 'default',
})
)}
disabled={zoomInDisabled}
onClick={api.preview.zoomIn}
type="button"
>
<Plus className="size-4" />
</button>
</div>
<button
aria-label="Download image"
className={cn(
buttonVariants({
variant: downloadDisabled ? 'disabled' : 'default',
})
)}
disabled={downloadDisabled}
onClick={handleDownload}
type="button"
>
<Download className="size-4" />
</button>
<button
aria-label="Close preview"
className={cn(buttonVariants())}
onClick={api.preview.close}
type="button"
>
<X className="size-4" />
</button>
</div>
</div>
</div>
</div>
);
}
function PreviewImage({
alt = '',
ref,
...props
}: React.ComponentPropsWithRef<'img'>) {
const { api, store } = useEditor().plugin(imagePlugin);
const preview = usePluginStore(imagePlugin, 'preview');
const imageRef = React.useRef<HTMLImageElement>(null);
const isZoomIn = preview.scale <= 1;
React.useEffect(() => {
if (preview.scale <= 1) return;
const boundingClientRect = imageRef.current?.getBoundingClientRect();
if (!boundingClientRect) return;
store.set({ preview: { ...store.get('preview'), boundingClientRect } });
}, [preview.scale, preview.translate.x, preview.translate.y, store]);
return (
<button
aria-label={isZoomIn ? 'Zoom in preview image' : 'Zoom out preview image'}
className="block border-0 bg-transparent p-0"
onClick={(event) => {
event.stopPropagation();
api.preview[isZoomIn ? 'zoomIn' : 'zoomOut']();
}}
type="button"
>
{/* oxlint-disable-next-line nextjs/no-img-element -- [P1 local-invariant] The preview owns a runtime URL, imperative ref, and live CSS transform that Next Image cannot preserve. */}
<img
alt={alt}
ref={useComposedRef(imageRef, ref)}
draggable={false}
src={preview.currentPreview?.url}
style={{
cursor: isZoomIn ? 'zoom-in' : 'zoom-out',
transform: `translate(${preview.translate.x}px, ${preview.translate.y}px) scale(${preview.scale})`,
}}
{...props}
/>
</button>
);
}
function ScaleInput({
onCommit,
scale,
...props
}: React.ComponentProps<'input'> & {
scale: number;
onCommit: (scale: number) => void;
}) {
const [value, setValue] = React.useState(`${scale * 100}`);
return (
<input
autoFocus
value={value}
onChange={(event) => {
setValue(event.target.value);
}}
onFocus={(event) => {
event.currentTarget.select();
}}
onKeyDown={(event) => {
if (!isHotkey('enter')(event)) return;
event.preventDefault();
const percentage = Number(value);
if (!Number.isFinite(percentage)) return;
const nextScale = Math.min(200, Math.max(50, percentage)) / 100;
onCommit(Number(nextScale.toFixed(2)));
}}
{...props}
/>
);
}
function getImageDownloadFilename(url: string) {
try {
const { pathname } = new URL(url, window.location.href);
const filename = pathname.split('/').findLast(Boolean);
return filename || DEFAULT_DOWNLOAD_FILENAME;
} catch {
return DEFAULT_DOWNLOAD_FILENAME;
}
}'use client';
import { cva } from 'class-variance-authority';
import { ArrowLeft, ArrowRight, Download, Minus, Plus, X } from 'lucide-react';
import { type NodeKey, isHotkey } from 'platejs';
import { BaseImagePlugin, type ImageElement } from 'platejs/media';
import { ImagePlugin } from 'platejs/media/react';
import { useComposedRef, useEditor, usePluginStore } from 'platejs/react';
import * as React from 'react';
import { cn } from '@/lib/utils';
const buttonVariants = cva('rounded bg-[rgba(0,0,0,0.5)] px-1'
For resizable media, compose the direct Resizable and ResizeHandle
components from platejs/react. The media renderer
commits the final width through its scoped plugin update.
Parses a media URL for plugin-specific handling.
Parses a video URL and extracts the video ID and provider-specific embed URL.
Parses a Twitter URL and extracts the tweet ID.
Parses the URL of an iframe embed.
import type { AudioElement, FileElement, ImageElement, MediaEmbedElement, VideoElement } from 'platejs/media';import type { AudioElement, FileElement, ImageElement, MediaEmbedElement, VideoElement } from 'platejs/media';Each alias is derived from its owning plugin schema. Element.children stores
the caption's direct inline content. Use
[{ text: '' }] when the caption is absent.
import type { PlaceholderElement } from 'platejs/media';import type { PlaceholderElement } from 'platejs/media';PlaceholderElement is derived from BasePlaceholderPlugin and requires a
string mediaType.
export interface EmbedUrlData {
id?: string;
provider?: string;
sourceKind?: 'allowlisted_snippet' | 'iframe' | 'url';
sourceUrl?: string;
url?: string;
}export interface EmbedUrlData {
id?: string;
provider?: string;
sourceKind?: 'allowlisted_snippet' | 'iframe' | 'url';
sourceUrl?: string;
url?: string;
}import { AudioPlugin, FilePlugin, ImagePlugin, MediaEmbedPlugin, PlaceholderPlugin, VideoPlugin } from 'platejs/media/react';
import { createEditor } from 'platejs/react';
import { AudioElement } from '@/components/editor/media-audio';
import { FileElement } from '@/components/editor/media-file';
import { ImageElement } from '@/components/editor/media-image';
import { MediaEmbedElement } from '@/components/editor/media-embed';
import { PlaceholderElement } from '@/components/editor/media-placeholder';
import { VideoElement } from '@/components/editor/media-video';
import { MediaUploadToast } from '@/components/editor/media';
const editor = createEditor({
plugins: [
// ...otherPlugins,
ImagePlugin.configure({ component: ImageElement }),
VideoPlugin.configure({ component: VideoElement }),
AudioPlugin.configure({ component: AudioElement }),
FilePlugin.configure({ component: FileElement }),
MediaEmbedPlugin.configure({ component: MediaEmbedElement }),
PlaceholderPlugin.configure({
component: PlaceholderElement,
initialState: { disableEmptyPlaceholder: true },
slots: { afterEditable: MediaUploadToast },
}),
],
});import { PlaceholderPlugin } from 'platejs/media/react';
PlaceholderPlugin.configure({
initialState: {
upload: async (file, { signal, onProgress }) => {
const body = new FormData();
body.append('file', file);
const response = await fetch('/api/upload', {
body,
method: 'POST',
signal,
});
if (!response.ok) throw new Error('Upload failed.');
const result: unknown = await response.json();
if (
!result || typeof result !== 'object' ||
!('url' in result) || typeof result.url !== 'string'
) {
throw new Error('The upload returned no URL.');
}
onProgress(100);
return { name: file.name, url: result.url };
},
},
});