An open source design system that's fully customizable and agent ready
TypeScript
test(richtext): give the playground an image plugin (#7579)
Sherry1279007ebe1a
diff --git a/apps/storybook/stories/RichTextEditor.imagePlugin.tsx b/apps/storybook/stories/RichTextEditor.imagePlugin.tsxnew file mode 100644index 0000000000..21a9458041--- /dev/null+++ b/apps/storybook/stories/RichTextEditor.imagePlugin.tsx@@ -0,0 +1,1070 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file RichTextEditor.imagePlugin.tsx+ * @input Uses Lexical's decorator node, command and selection APIs, the+ * `@lexical/react` composer context with its node-selection and editable+ * hooks, and Astryx primitives (Button, Dialog, FileInput, SegmentedControl,+ * Text, TextInput) for the insert dialog and the selected image's controls.+ * @output The playground's image plugin: `ImageNode` with `$createImageNode`,+ * `$isImageNode` and `IMAGE_NODE_TYPE`; `INSERT_IMAGE_COMMAND`;+ * `RichTextImagesPlugin`; `InsertImageProvider` with `InsertImageButton`+ * and `InsertImageDialog`; and `IMAGE_SAMPLES`.+ * @position Storybook-only, for the RichText/RichTextEditor Playground story —+ * the Astryx counterpart of the Lexical playground's images plugin. Nothing+ * here lives in `@astryxdesign/richtext`: the node arrives through the+ * editor's `nodes` prop, the behaviour through its `plugins` slot, and the+ * insert control through the toolbar's `endContent` slot, so the story+ * exercises those three extension points exactly as a product would+ * (spec:AST-061/DEC-8 — a caller extends the editor with Lexical directly).+ *+ * Images are editor content, not Markdown: RichText's default transformer+ * array is internal, and `transformers` replaces it whole rather than+ * extending it, so a caller cannot add an image transformer without giving up+ * tables, task lists and the rest of the dialect. An image therefore reaches+ * the editor state, the HTML export and `RichTextView`, and is absent from the+ * Markdown readout — which the playground says out loud rather than hiding.+ *+ * Stable hooks for browser tests: `data-playground-image` (the figure one+ * image draws), `data-playground-image-handle` (its pointer resize handle) and+ * `data-playground-image-actions` (the keyboard controls of a selected image).+ */++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';+import {FileInput} from '@astryxdesign/core/FileInput';+import {+ HStack,+ Layout,+ LayoutContent,+ LayoutFooter,+ VStack,+} from '@astryxdesign/core/Layout';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Text} from '@astryxdesign/core/Text';+import {TextInput} from '@astryxdesign/core/TextInput';+import {+ colorVars,+ focusVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {useLexicalEditable} from '@lexical/react/useLexicalEditable';+import {useLexicalNodeSelection} from '@lexical/react/useLexicalNodeSelection';+import {+ $createParagraphNode,+ $createRangeSelection,+ $getNearestNodeFromDOMNode,+ $getNodeByKey,+ $getSelection,+ $insertNodes,+ $isDecoratorNode,+ $isNodeSelection,+ $isRootOrShadowRoot,+ $setSelection,+ CLICK_COMMAND,+ COMMAND_PRIORITY_EDITOR,+ COMMAND_PRIORITY_LOW,+ COMMAND_PRIORITY_NORMAL,+ createCommand,+ DecoratorNode,+ DRAGSTART_COMMAND,+ DROP_COMMAND,+ KEY_ENTER_COMMAND,+ KEY_ESCAPE_COMMAND,+ mergeRegister,+ PASTE_COMMAND,+ type DOMConversionMap,+ type DOMConversionOutput,+ type DOMExportOutput,+ type EditorConfig,+ type LexicalCommand,+ type LexicalEditor,+ type LexicalNode,+ type NodeKey,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';++/* ------------------------------------------------------------------ *+ * Sample images+ * ------------------------------------------------------------------ */++/**+ * The samples are inline SVG data URLs rather than bundled files: the story+ * and its browser specs run with no network, and a data URL also shows what an+ * uploaded file becomes, since `FileReader` hands the plugin the same shape.+ */+function svgDataUrl(svg: string): string {+ return `data:image/svg+xml;utf8,${encodeURIComponent(svg.trim())}`;+}++export interface ImageSample {+ readonly key: string;+ readonly label: string;+ readonly altText: string;+ readonly src: string;+}++export const IMAGE_SAMPLES: ReadonlyArray<ImageSample> = [+ {+ key: 'landscape',+ label: 'Landscape (640 × 360)',+ altText:+ 'An illustration of layered hills under a rising sun, in blues and greens',+ src: svgDataUrl(`+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360" role="img">+ <defs>+ <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#0064E0"/>+ <stop offset="100%" stop-color="#9BD1FF"/>+ </linearGradient>+ </defs>+ <rect width="640" height="360" fill="url(#sky)"/>+ <circle cx="470" cy="118" r="46" fill="#FFD96B"/>+ <path d="M0 268 L150 186 L286 268 Z" fill="#0B6E3E"/>+ <path d="M196 288 L372 164 L556 288 Z" fill="#0D8626"/>+ <path d="M398 300 L540 214 L640 300 Z" fill="#115E3A"/>+ <rect y="286" width="640" height="74" fill="#09441F"/>+</svg>`),+ },+ {+ key: 'swatch',+ label: 'Square swatch (240 × 240)',+ altText: 'A square swatch of concentric rounded squares in warm colours',+ src: svgDataUrl(`+<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240" role="img">+ <rect width="240" height="240" rx="16" fill="#E9AF08"/>+ <rect x="36" y="36" width="168" height="168" rx="14" fill="#EB6E00"/>+ <rect x="78" y="78" width="84" height="84" rx="12" fill="#E3193B"/>+</svg>`),+ },+];++/* ------------------------------------------------------------------ *+ * The node+ * ------------------------------------------------------------------ */++/** The serialized `type` of an image, for readouts that walk stored state. */+export const IMAGE_NODE_TYPE = 'playground-image';++export interface ImagePayload {+ readonly src: string;+ readonly altText: string;+ /** Rendered width in pixels; `null` is the image's own size. */+ readonly width?: number | null;+}++export type SerializedImageNode = Spread<+ {src: string; altText: string; width: number | null},+ SerializedLexicalNode+>;++const styles = stylex.create({+ // The element `createDOM` makes. An image is an inline decorator, as it is+ // in the Lexical playground, so it can sit in a line of text. The block+ // margin keeps the selection ring off the line above it.+ host: {+ display: 'inline-block',+ maxWidth: '100%',+ verticalAlign: 'bottom',+ marginBlock: spacingVars['--spacing-1'],+ },+ figure: {+ display: 'inline-block',+ position: 'relative',+ margin: 0,+ maxWidth: '100%',+ lineHeight: 0,+ },+ image: {+ display: 'block',+ maxWidth: '100%',+ height: 'auto',+ },+ // A selected image wears the focus ring, like a selected rule or Markdown+ // plugin node in `editorTheme.ts`: a person has to see what Backspace will+ // delete, and a ring costs the picture nothing.+ selected: {+ outlineWidth: focusVars['--focus-outline-width'],+ outlineStyle: focusVars['--focus-outline-style'],+ outlineColor: focusVars['--focus-outline-color'],+ outlineOffset: focusVars['--focus-outline-offset'],+ },+ handle: {+ position: 'absolute',+ insetInlineEnd: 0,+ insetBlockEnd: 0,+ width: '0.875rem',+ height: '0.875rem',+ // The handle sits on the inline end, which is the image's left edge in a+ // right-to-left document, so the diagonal it drags along flips with it.+ cursor: {+ default: 'nwse-resize',+ ':is([dir="rtl"] *)': 'nesw-resize',+ },+ backgroundColor: colorVars['--color-accent'],+ borderRadius: radiusVars['--radius-inner'],+ touchAction: 'none',+ },+ actions: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-1'],+ marginBlockStart: spacingVars['--spacing-1'],+ lineHeight: 'normal',+ },+ broken: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ padding: spacingVars['--spacing-3'],+ borderWidth: 1,+ borderStyle: 'dashed',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-muted'],+ lineHeight: 'normal',+ },+ preview: {+ display: 'block',+ maxWidth: '100%',+ maxHeight: '8rem',+ borderRadius: radiusVars['--radius-container'],+ },+});++function $convertImageElement(element: HTMLElement): DOMConversionOutput {+ const image = element as HTMLImageElement;+ const src = image.getAttribute('src') ?? '';+ if (src === '') {+ return {node: null};+ }+ return {+ node: $createImageNode({+ altText: image.getAttribute('alt') ?? '',+ src,+ width: image.width > 0 ? image.width : null,+ }),+ };+}++export class ImageNode extends DecoratorNode<ReactNode> {+ __src: string;+ __altText: string;+ /** Rendered width in pixels; `null` is the image's own size. */+ __width: number | null;++ static getType(): string {+ return IMAGE_NODE_TYPE;+ }++ static clone(node: ImageNode): ImageNode {+ return new ImageNode(node.__src, node.__altText, node.__width, node.__key);+ }++ /** Stored state is read defensively, so a damaged node still loads. */+ static importJSON(+ serialized: SerializedLexicalNode & Record<string, unknown>,+ ): ImageNode {+ const {src, altText, width} = serialized;+ return $createImageNode({+ altText: typeof altText === 'string' ? altText : '',+ src: typeof src === 'string' ? src : '',+ width: typeof width === 'number' && width > 0 ? width : null,+ }).updateFromJSON(serialized);+ }++ /** Pasted HTML carrying an `<img>` becomes an image rather than nothing. */+ static importDOM(): DOMConversionMap {+ return {img: () => ({conversion: $convertImageElement, priority: 0})};+ }++ constructor(+ src: string,+ altText: string,+ width: number | null = null,+ key?: NodeKey,+ ) {+ super(key);+ this.__src = src;+ this.__altText = altText;+ this.__width = width;+ }++ exportJSON(): SerializedImageNode {+ const latest = this.getLatest();+ return {+ ...super.exportJSON(),+ altText: latest.__altText,+ src: latest.__src,+ width: latest.__width,+ };+ }++ exportDOM(): DOMExportOutput {+ const element = document.createElement('img');+ element.setAttribute('src', this.__src);+ element.setAttribute('alt', this.__altText);+ if (this.__width !== null) {+ element.setAttribute('width', String(Math.round(this.__width)));+ }+ return {element};+ }++ createDOM(_config: EditorConfig): HTMLElement {+ const element = document.createElement('span');+ element.className = stylex.props(styles.host).className ?? '';+ return element;+ }++ updateDOM(): false {+ return false;+ }++ getSrc(): string {+ return this.getLatest().__src;+ }++ getAltText(): string {+ return this.getLatest().__altText;+ }++ getWidth(): number | null {+ return this.getLatest().__width;+ }++ setWidth(width: number | null): this {+ const writable = this.getWritable();+ writable.__width = width;+ return writable;+ }++ setAltText(altText: string): this {+ const writable = this.getWritable();+ writable.__altText = altText;+ return writable;+ }++ /**+ * No text content, as the Lexical playground's image node has none: a data+ * URL is kilobytes long, and the character counter and every plain-text copy+ * would carry it. The consequence is that an image is absent from the+ * Markdown export, which the playground says where the Markdown is read.+ */++ decorate(): ReactNode {+ return (+ <ImageComponent+ altText={this.__altText}+ nodeKey={this.getKey()}+ src={this.__src}+ width={this.__width}+ />+ );+ }+}++export function $createImageNode({+ src,+ altText,+ width = null,+}: ImagePayload): ImageNode {+ return new ImageNode(src, altText, width);+}++export function $isImageNode(+ node: LexicalNode | null | undefined,+): node is ImageNode {+ return node instanceof ImageNode;+}++/* ------------------------------------------------------------------ *+ * The rendered image+ * ------------------------------------------------------------------ */++/** Narrower than this and the resize handle covers the picture. */+const MIN_WIDTH = 48;+/** One step of the keyboard size controls. */+const RESIZE_STEP = 1.25;++function ImageComponent({+ src,+ altText,+ width,+ nodeKey,+}: {+ readonly src: string;+ readonly altText: string;+ readonly width: number | null;+ readonly nodeKey: NodeKey;+}) {+ const [editor] = useLexicalComposerContext();+ const [isSelected, setSelected, clearSelection] =+ useLexicalNodeSelection(nodeKey);+ const isEditable = useLexicalEditable();+ const imageRef = useRef<HTMLImageElement | null>(null);+ const actionsRef = useRef<HTMLSpanElement | null>(null);+ const [hasLoadError, setHasLoadError] = useState(false);+ // The width being dragged, before it is committed to the node: a resize is+ // one editor update at the end, not one per pointer move.+ const [draggedWidth, setDraggedWidth] = useState<number | null>(null);++ const isActive = isSelected && isEditable;++ const writeWidth = useCallback(+ (next: number | null) => {+ editor.update(() => {+ const node = $getNodeByKey(nodeKey);+ if ($isImageNode(node)) {+ node.setWidth(next === null ? null : Math.round(next));+ }+ });+ },+ [editor, nodeKey],+ );++ const scaleBy = useCallback(+ (factor: number) => {+ const current = imageRef.current?.getBoundingClientRect().width ?? 0;+ writeWidth(Math.max(MIN_WIDTH, current * factor));+ },+ [writeWidth],+ );++ const remove = useCallback(() => {+ editor.update(() => {+ const node = $getNodeByKey(nodeKey);+ node?.remove();+ });+ editor.focus();+ }, [editor, nodeKey]);++ const onPointerDown = useCallback(+ (event: ReactPointerEvent<HTMLSpanElement>) => {+ event.preventDefault();+ event.stopPropagation();+ const handle = event.currentTarget;+ const image = imageRef.current;+ if (image === null) {+ return;+ }+ const startX = event.clientX;+ const startWidth = image.getBoundingClientRect().width;+ // The handle is on the inline end, so in a right-to-left document it is+ // the image's LEFT edge: dragging it outward lowers clientX, and the+ // width has to follow the drag rather than the axis.+ const towardsWider =+ getComputedStyle(handle).direction === 'rtl' ? -1 : 1;+ const widthAt = (clientX: number) =>+ Math.max(MIN_WIDTH, startWidth + (clientX - startX) * towardsWider);+ // The pointer owns the gesture until it is lifted, so a fast drag that+ // leaves the handle still resizes — and still ends.+ handle.setPointerCapture(event.pointerId);+ const onMove = (moveEvent: PointerEvent) => {+ setDraggedWidth(widthAt(moveEvent.clientX));+ };+ const onEnd = (endEvent: PointerEvent) => {+ handle.removeEventListener('pointermove', onMove);+ handle.releasePointerCapture(endEvent.pointerId);+ setDraggedWidth(null);+ writeWidth(widthAt(endEvent.clientX));+ };+ handle.addEventListener('pointermove', onMove);+ handle.addEventListener('pointerup', onEnd, {once: true});+ handle.addEventListener('pointercancel', onEnd, {once: true});+ },+ [writeWidth],+ );++ /**+ * Enter, on a selected image, moves focus to its controls. Tab is bound to+ * indentation inside the editor, so without this the controls would be+ * keyboard-unreachable — the same route the Lexical playground gives its+ * caption button. Enter pressed ON a control bubbles back through here, and+ * must be left alone: swallowing it would cancel the button's activation.+ */+ const $onEnter = useCallback(+ (event: KeyboardEvent | null) => {+ const target = event?.target;+ if (target instanceof Node && actionsRef.current?.contains(target)) {+ return false;+ }+ const selection = $getSelection();+ if (+ !$isNodeSelection(selection) ||+ !selection.has(nodeKey) ||+ selection.getNodes().length !== 1+ ) {+ return false;+ }+ const button = actionsRef.current?.querySelector('button');+ if (button == null) {+ return false;+ }+ event?.preventDefault();+ button.focus();+ return true;+ },+ [nodeKey],+ );++ /** Escape, from the controls, goes back to the image in the document. */+ const $onEscape = useCallback(+ (event: KeyboardEvent) => {+ const target = event.target;+ if (+ !(target instanceof Node) ||+ actionsRef.current === null ||+ !actionsRef.current.contains(target)+ ) {+ return false;+ }+ editor.update(() => {+ clearSelection();+ setSelected(true);+ // The root element, not `editor.focus()`: focus has to leave the+ // button this keystroke came from, and the editor already believes it+ // is focused, so its own focus() moves nothing.+ editor.getRootElement()?.focus();+ });+ return true;+ },+ [clearSelection, editor, setSelected],+ );++ const onClick = useCallback(+ (event: MouseEvent) => {+ if (event.target !== imageRef.current) {+ return false;+ }+ if (event.shiftKey) {+ setSelected(!isSelected);+ } else {+ clearSelection();+ setSelected(true);+ }+ return true;+ },+ [clearSelection, isSelected, setSelected],+ );++ useEffect(+ () =>+ mergeRegister(+ editor.registerCommand(CLICK_COMMAND, onClick, COMMAND_PRIORITY_LOW),+ editor.registerCommand(+ DRAGSTART_COMMAND,+ (event: DragEvent) => {+ // Dragging the image away would have the browser drop a copy of+ // the file back into the document, under the plugin's own drop+ // handler. Cancel the native drag; moving an image is a cut and+ // an insert, which the controls and the editor already do.+ if (event.target !== imageRef.current) {+ return false;+ }+ event.preventDefault();+ return true;+ },+ COMMAND_PRIORITY_LOW,+ ),+ editor.registerCommand(+ KEY_ENTER_COMMAND,+ $onEnter,+ COMMAND_PRIORITY_LOW,+ ),+ editor.registerCommand(+ KEY_ESCAPE_COMMAND,+ $onEscape,+ // Above the editor's own Escape handler, which arms the Tab exit and+ // consumes the key at COMMAND_PRIORITY_LOW. Escape inside these+ // controls means "back to the image", and the editor's own handling+ // is what the fall-through below leaves in place everywhere else.+ COMMAND_PRIORITY_NORMAL,+ ),+ ),+ [$onEnter, $onEscape, editor, onClick],+ );++ if (hasLoadError) {+ return (+ <span {...stylex.props(styles.broken)} data-playground-image="broken">+ <Text type="supporting">+ {altText === ''+ ? 'This image could not be loaded.'+ : `This image could not be loaded: ${altText}`}+ </Text>+ {isEditable && (+ <Button size="sm" label="Remove image" onClick={remove} />+ )}+ </span>+ );+ }++ const renderedWidth = draggedWidth ?? width;+ return (+ <span data-playground-image="">+ <span {...stylex.props(styles.figure)}>+ <img+ alt={altText}+ draggable={false}+ onError={() => setHasLoadError(true)}+ ref={imageRef}+ src={src}+ // A resize is a per-instance pixel width, which is what the node+ // stores; StyleX covers everything about the image that is not it.+ style={renderedWidth === null ? undefined : {width: renderedWidth}}+ {...stylex.props(styles.image, isActive && styles.selected)}+ />+ {isActive && (+ <span+ {...stylex.props(styles.handle)}+ aria-hidden="true"+ data-playground-image-handle=""+ onPointerDown={onPointerDown}+ />+ )}+ </span>+ {isActive && (+ <span+ {...stylex.props(styles.actions)}+ data-playground-image-actions=""+ ref={actionsRef}>+ <Button+ size="sm"+ label="Smaller"+ onClick={() => scaleBy(1 / RESIZE_STEP)}+ />+ <Button+ size="sm"+ label="Larger"+ onClick={() => scaleBy(RESIZE_STEP)}+ />+ <Button+ size="sm"+ label="Reset size"+ onClick={() => writeWidth(null)}+ />+ <Button+ size="sm"+ variant="destructive"+ label="Remove image"+ onClick={remove}+ />+ </span>+ )}+ </span>+ );+}++/* ------------------------------------------------------------------ *+ * The plugin+ * ------------------------------------------------------------------ */++export const INSERT_IMAGE_COMMAND: LexicalCommand<ImagePayload> = createCommand(+ 'INSERT_IMAGE_COMMAND',+);++/** Reads the image files out of a paste or a drop, as data URLs. */+function readImageFiles(files: FileList): Promise<ReadonlyArray<ImagePayload>> {+ const images = [...files].filter(file => file.type.startsWith('image/'));+ return Promise.all(+ images.map(+ file =>+ new Promise<ImagePayload>(resolve => {+ const reader = new FileReader();+ reader.onload = () =>+ resolve({+ // A dropped file carries no alt text; its name is the honest+ // placeholder, and the person can say better in the dialog.+ altText: file.name,+ src: typeof reader.result === 'string' ? reader.result : '',+ });+ reader.readAsDataURL(file);+ }),+ ),+ );+}++function hasImageFiles(files: FileList): boolean {+ return [...files].some(file => file.type.startsWith('image/'));+}++/**+ * The document position a pointer event is over, as a DOM range. Lexical's+ * own drop handling does this with `@lexical/clipboard`'s `caretFromPoint`,+ * which is not a Storybook dependency; the two browser APIs it wraps are+ * right here.+ */+function rangeFromPoint(x: number, y: number): Range | null {+ const withCaretPosition = document as Document & {+ caretPositionFromPoint?: (+ x: number,+ y: number,+ ) => {offsetNode: Node; offset: number} | null;+ };+ const position = withCaretPosition.caretPositionFromPoint?.(x, y);+ if (position != null) {+ const range = document.createRange();+ range.setStart(position.offsetNode, position.offset);+ range.collapse(true);+ return range;+ }+ const withCaretRange = document as Document & {+ caretRangeFromPoint?: (x: number, y: number) => Range | null;+ };+ return withCaretRange.caretRangeFromPoint?.(x, y) ?? null;+}++/**+ * Inserts the image files of a paste or a drop. A drop names the point it+ * landed on: this handler consumes `DROP_COMMAND` ahead of the rich-text+ * handler that would have moved the selection there, so it has to move the+ * selection itself, or the image arrives wherever the caret already was.+ */+function insertFiles(+ editor: LexicalEditor,+ files: FileList,+ point?: {readonly x: number; readonly y: number},+): void {+ void readImageFiles(files).then(payloads => {+ const usable = payloads.filter(payload => payload.src !== '');+ if (usable.length === 0) {+ return;+ }+ const range = point ? rangeFromPoint(point.x, point.y) : null;+ if (range !== null) {+ editor.update(() => {+ // A point inside a decorator — the image already in the document, a+ // Markdown plugin node — resolves to no Lexical position at all, and+ // `applyDOMRange` then leaves the fresh selection at the root's+ // offset 0, dropping the file at the top of the document. Land+ // beside the decorator instead, as Lexical's own drop handler does.+ const nearest = $getNearestNodeFromDOMNode(range.startContainer);+ if ($isDecoratorNode(nearest)) {+ const after = nearest.getIndexWithinParent() + 1;+ nearest.getParentOrThrow().select(after, after);+ return;+ }+ const selection = $createRangeSelection();+ selection.applyDOMRange(range);+ $setSelection(selection);+ });+ }+ for (const payload of usable) {+ editor.dispatchCommand(INSERT_IMAGE_COMMAND, payload);+ }+ });+}++/**+ * The editor-side half of the plugin, rendered in `RichTextEditor`'s `plugins`+ * slot: it answers `INSERT_IMAGE_COMMAND`, and takes image files pasted or+ * dropped into the editor.+ */+export function RichTextImagesPlugin() {+ const [editor] = useLexicalComposerContext();++ useEffect(+ () =>+ mergeRegister(+ editor.registerCommand(+ INSERT_IMAGE_COMMAND,+ payload => {+ const image = $createImageNode(payload);+ $insertNodes([image]);+ // An image is an inline node, so at the top level it needs a+ // paragraph of its own. `@lexical/utils`' `$wrapNodeInElement` is+ // this, and is not a dependency of the Storybook app.+ if ($isRootOrShadowRoot(image.getParentOrThrow())) {+ const paragraph = $createParagraphNode();+ image.replace(paragraph);+ paragraph.append(image);+ paragraph.selectEnd();+ }+ return true;+ },+ COMMAND_PRIORITY_EDITOR,+ ),+ editor.registerCommand(+ DROP_COMMAND,+ (event: DragEvent) => {+ const files = event.dataTransfer?.files;+ if (files == null || !hasImageFiles(files)) {+ return false;+ }+ event.preventDefault();+ insertFiles(editor, files, {x: event.clientX, y: event.clientY});+ return true;+ },+ COMMAND_PRIORITY_LOW,+ ),+ editor.registerCommand(+ PASTE_COMMAND,+ event => {+ const files =+ event instanceof ClipboardEvent+ ? event.clipboardData?.files+ : undefined;+ if (files == null || !hasImageFiles(files)) {+ return false;+ }+ event.preventDefault();+ insertFiles(editor, files);+ return true;+ },+ COMMAND_PRIORITY_LOW,+ ),+ ),+ [editor],+ );++ return null;+}++/* ------------------------------------------------------------------ *+ * The insert control+ * ------------------------------------------------------------------ */++type ImageSource = 'sample' | 'url' | 'file';++/**+ * Whether the insert dialog is open. The button lives in the toolbar's+ * `endContent` and the dialog does NOT: a `Toolbar` is a roving tab stop, so+ * everything inside it is `tabindex="-1"`, and a dialog rendered there cannot+ * be tabbed through at all. `RichTextEditorToolbar` renders its own link+ * dialog as a sibling of the toolbar for the same reason; a consumer-authored+ * control reaches that position through the editor's `plugins` slot, so the+ * two halves are joined by this context rather than by the tree.+ */+const InsertImageContext = createContext<{+ isOpen: boolean;+ setIsOpen: (open: boolean) => void;+} | null>(null);++function useInsertImage() {+ const value = useContext(InsertImageContext);+ if (value === null) {+ throw new Error(+ 'InsertImageButton and InsertImageDialog need an InsertImageProvider around the editor.',+ );+ }+ return value;+}++/** Holds the dialog's open state for the button and the dialog. */+export function InsertImageProvider({children}: {children: ReactNode}) {+ const [isOpen, setIsOpen] = useState(false);+ const value = useMemo(() => ({isOpen, setIsOpen}), [isOpen]);+ return (+ <InsertImageContext.Provider value={value}>+ {children}+ </InsertImageContext.Provider>+ );+}++/**+ * The toolbar's image button, for the toolbar's public `endContent` slot. It+ * reaches the editor through `useLexicalComposerContext()`, like any+ * consumer-authored control; `InsertImageDialog` goes in the `plugins` slot.+ */+export function InsertImageButton() {+ const isEditable = useLexicalEditable();+ const {isOpen, setIsOpen} = useInsertImage();+ return (+ <Button+ size="sm"+ variant="ghost"+ label="Image"+ isDisabled={!isEditable}+ aria-haspopup="dialog"+ aria-expanded={isOpen}+ onClick={() => setIsOpen(true)}+ />+ );+}++/**+ * The insert dialog, for the editor's `plugins` slot — outside the toolbar,+ * so its controls keep their own tab order. Three sources, as the Lexical+ * playground's image dialog has: a sample, a URL, and a file from the machine.+ */+export function InsertImageDialog() {+ const [editor] = useLexicalComposerContext();+ const {isOpen, setIsOpen} = useInsertImage();+ const [source, setSource] = useState<ImageSource>('sample');+ const [sampleKey, setSampleKey] = useState(IMAGE_SAMPLES[0].key);+ const [url, setUrl] = useState('');+ const [file, setFile] = useState<File | null>(null);+ const [fileSrc, setFileSrc] = useState('');+ const [altText, setAltText] = useState('');++ const sample =+ IMAGE_SAMPLES.find(entry => entry.key === sampleKey) ?? IMAGE_SAMPLES[0];+ const src =+ source === 'sample' ? sample.src : source === 'url' ? url.trim() : fileSrc;+ const alt =+ altText.trim() !== ''+ ? altText.trim()+ : source === 'sample'+ ? sample.altText+ : source === 'file' && file !== null+ ? file.name+ : '';++ const close = useCallback(() => {+ setIsOpen(false);+ setSource('sample');+ setSampleKey(IMAGE_SAMPLES[0].key);+ setUrl('');+ setFile(null);+ setFileSrc('');+ setAltText('');+ }, []);++ const onFileChange = useCallback((next: File | File[] | null) => {+ const picked = Array.isArray(next) ? (next[0] ?? null) : next;+ setFile(picked);+ if (picked === null) {+ setFileSrc('');+ return;+ }+ const reader = new FileReader();+ reader.onload = () =>+ setFileSrc(typeof reader.result === 'string' ? reader.result : '');+ reader.readAsDataURL(picked);+ }, []);++ const insert = useCallback(() => {+ if (src === '') {+ return;+ }+ editor.dispatchCommand(INSERT_IMAGE_COMMAND, {altText: alt, src});+ close();+ // Deferred a frame, as RichTextEditorToolbar defers it for its link+ // dialog: the dialog returns focus to its invoker as it closes, so a+ // `focus()` called before that lands on the toolbar's Image button and+ // the next keystroke reopens the dialog instead of typing.+ requestAnimationFrame(() => editor.focus());+ }, [alt, close, editor, src]);++ return (+ <Dialog+ isOpen={isOpen}+ onOpenChange={open => (open ? setIsOpen(true) : close())}+ purpose="form"+ width={460}>+ <Layout+ header={+ <DialogHeader+ title="Insert image"+ subtitle="A sample, a URL, or a file from this machine."+ onOpenChange={() => close()}+ />+ }+ content={+ <LayoutContent>+ <VStack gap={3}>+ <SegmentedControl+ size="sm"+ label="Image source"+ value={source}+ onChange={value => setSource(value as ImageSource)}>+ <SegmentedControlItem value="sample" label="Sample" />+ <SegmentedControlItem value="url" label="URL" />+ <SegmentedControlItem value="file" label="File" />+ </SegmentedControl>++ {source === 'sample' && (+ <VStack gap={2}>+ <SegmentedControl+ size="sm"+ label="Sample image"+ layout="fill"+ value={sampleKey}+ onChange={setSampleKey}>+ {IMAGE_SAMPLES.map(entry => (+ <SegmentedControlItem+ key={entry.key}+ value={entry.key}+ label={entry.label}+ />+ ))}+ </SegmentedControl>+ <img+ alt={sample.altText}+ src={sample.src}+ {...stylex.props(styles.preview)}+ />+ </VStack>+ )}++ {source === 'url' && (+ <TextInput+ size="sm"+ label="Image URL"+ description="Any URL the page can load, including a data URL."+ placeholder="https://example.com/photo.jpg"+ value={url}+ onChange={setUrl}+ hasAutoFocus+ />+ )}++ {source === 'file' && (+ <FileInput+ label="Image file"+ description="Read in the browser as a data URL; nothing is uploaded."+ accept="image/*"+ mode="dropzone"+ value={file}+ onChange={onFileChange}+ />+ )}++ <TextInput+ size="sm"+ label="Alt text"+ description="What the image says, for people who cannot see it."+ placeholder={+ source === 'sample' ? sample.altText : 'Describe the image'+ }+ value={altText}+ onChange={setAltText}+ />+ </VStack>+ </LayoutContent>+ }+ footer={+ <LayoutFooter>+ <HStack gap={2} hAlign="end">+ <Button label="Cancel" onClick={close} />+ <Button+ variant="primary"+ label="Insert image"+ isDisabled={src === ''}+ onClick={insert}+ />+ </HStack>+ </LayoutFooter>+ }+ />+ </Dialog>+ );+}diff --git a/apps/storybook/stories/RichTextEditor.playground.tsx b/apps/storybook/stories/RichTextEditor.playground.tsxindex 7825f3edd6..78683ce220 100644--- a/apps/storybook/stories/RichTextEditor.playground.tsx+++ b/apps/storybook/stories/RichTextEditor.playground.tsx@@ -4,6 +4,7 @@* @file RichTextEditor.playground.tsx* @input Uses RichTextEditor with its toolbar, autolink plugin, Markdown* serializers and plugin adapter; the Storybook demo Markdown plugins; the+ * playground image plugin (RichTextEditor.imagePlugin.tsx); the* Markdown parity fixture; Lexical's table and horizontal-rule commands; and* Astryx primitives for the settings, actions, and output panels.* @output `RichTextEditorPlayground`: ONE editor with every RichText feature@@ -71,6 +72,14 @@ import {INSERT_HORIZONTAL_RULE_COMMAND} from '@lexical/extension';import {INSERT_TABLE_COMMAND} from '@lexical/table';import {$getSelection, $isRangeSelection, type EditorState} from 'lexical';import {markdownDemoPlugins} from './Markdown.demoPlugins';+import {+ IMAGE_NODE_TYPE,+ ImageNode,+ InsertImageButton,+ InsertImageDialog,+ InsertImageProvider,+ RichTextImagesPlugin,+} from './RichTextEditor.imagePlugin';import {MARKDOWN_PARITY_SOURCE} from './RichTextEditor.markdownParityFixture';/* ------------------------------------------------------------------ *@@ -270,7 +279,7 @@ const styles = stylex.create({* on the toolbar's public `endContent` slot: it reaches the editor through* `useLexicalComposerContext()`, like any consumer-authored control would.*/-function InsertControls() {+function InsertControls({hasImages}: {readonly hasImages: boolean}) {const [editor] = useLexicalComposerContext();// Read-only and disabled editors take no edits, so these controls disable// with the editor, as RichTextEditorToolbar's own controls do.@@ -320,6 +329,7 @@ function InsertControls() {})}/>+ {hasImages && <InsertImageButton />}</>);}@@ -338,6 +348,8 @@ interface SerializedNodeLike {readonly language?: string;readonly url?: string;readonly checked?: boolean;+ readonly altText?: string;+ readonly width?: number | null;}const TEXT_FORMATS: ReadonlyArray<readonly [number, string]> = [@@ -368,6 +380,12 @@ function describeNode(node: SerializedNodeLike): string {if (node.checked != null) {parts.push(node.checked ? 'checked' : 'unchecked');}+ if (node.altText != null) {+ parts.push(`alt=${JSON.stringify(node.altText)}`);+ }+ if (node.width != null) {+ parts.push(`width=${node.width}`);+ }if (typeof node.format === 'number' && node.format > 0) {const flags = TEXT_FORMATS.filter(([bit]) => ((node.format as number) & bit) !== 0,@@ -408,6 +426,7 @@ interface ContentStats {readonly words: number;readonly nodes: number;readonly blocks: number;+ readonly images: number;}function toStats(stateJSON: string): ContentStats {@@ -415,13 +434,17 @@ function toStats(stateJSON: string): ContentStats {try {root = (JSON.parse(stateJSON) as {root: SerializedNodeLike}).root;} catch {- return {characters: 0, words: 0, nodes: 0, blocks: 0};+ return {characters: 0, words: 0, nodes: 0, blocks: 0, images: 0};}let characters = 0;let nodes = 0;+ let images = 0;const words: string[] = [];const walk = (node: SerializedNodeLike) => {nodes += 1;+ if (node.type === IMAGE_NODE_TYPE) {+ images += 1;+ }if (node.text != null) {characters += node.text.length;words.push(node.text);@@ -433,6 +456,7 @@ function toStats(stateJSON: string): ContentStats {walk(root);return {characters,+ images,words: words.join(' ').split(/\s+/)@@ -469,6 +493,7 @@ const SHORTCUTS: ReadonlyArray<{keys: string;action: string;needsLinkButton?: boolean;+ needsImages?: boolean;}> = [{keys: 'mod+b', action: 'Bold'},{keys: 'mod+i', action: 'Italic'},@@ -477,6 +502,11 @@ const SHORTCUTS: ReadonlyArray<{{keys: 'mod+z', action: 'Undo'},{keys: 'mod+shift+z', action: 'Redo'},{keys: 'mod+enter', action: 'Check the task item holding the caret'},+ {+ keys: 'enter',+ action: "Open a selected image's controls",+ needsImages: true,+ },{keys: 'tab', action: 'Indent (Escape, then Tab, leaves the editor)'},];@@ -492,6 +522,7 @@ export function RichTextEditorPlayground() {const [hasAutoLink, setHasAutoLink] = useState(true);const [hasMarkdownShortcuts, setHasMarkdownShortcuts] = useState(true);const [hasMarkdownPlugins, setHasMarkdownPlugins] = useState(true);+ const [hasImages, setHasImages] = useState(true);const [isRestricted, setIsRestricted] = useState(false);// Field@@ -520,13 +551,21 @@ export function RichTextEditorPlayground() {const extensions = hasMarkdownPlugins ? DEMO_PLUGINS.extensions : undefined;const transformers = isRestricted ? RESTRICTED_TRANSFORMERS : undefined;+ // The image plugin's node, registered through the editor's `nodes` prop. The+ // serializers and RichTextView need the same list, or state holding an image+ // will not parse.+ const nodes = useMemo(+ () => (hasImages ? [ImageNode] : undefined),+ [hasImages],+ );const serializerOptions = useMemo(() => ({...(extensions ? {extensions} : {}),...(transformers ? {transformers} : {}),+ ...(nodes ? {nodes} : {}),}),- [extensions, transformers],+ [extensions, nodes, transformers],);// `defaultValue` is read once per mount, so loading a document — or changing@@ -588,6 +627,32 @@ export function RichTextEditorPlayground() {setStateJSON(JSON.stringify(editorState.toJSON()));}, []);+ /**+ * The image node is registered at construction, like `hasAutoFocus`, so the+ * switch rebuilds the editor. Turning images ON keeps the content exactly as+ * it stands; turning them OFF cannot, because state holding an image does+ * not parse without the node registered — so the document goes out through+ * Markdown and back, where images do not survive.+ */+ const toggleImages = useCallback(+ (next: boolean) => {+ setHasImages(next);+ if (next) {+ setSeed(stateJSON);+ setMountKey(key => key + 1);+ return;+ }+ const markdown =+ editorRef.current?.getMarkdown() ??+ editorStateJSONToMarkdown(stateJSON, serializerOptions);+ reseed(markdown, {+ ...(extensions ? {extensions} : {}),+ ...(transformers ? {transformers} : {}),+ });+ },+ [extensions, reseed, serializerOptions, stateJSON, transformers],+ );+const markdown = useMemo(() => {if (tab !== 'markdown') {return '';@@ -642,44 +707,69 @@ export function RichTextEditorPlayground() {{/* ---------------------------------------------------------- */}<VStack gap={3}><div data-playground-editor="">- <RichTextEditor- key={mountKey}- ref={editorRef}- label="Playground"- isLabelHidden={isLabelHidden}- description={- hasDescription- ? 'Bold, italic, lists, task lists, quotes, links, code blocks and tables.'- : undefined- }- placeholder="Write something, or load a document below…"- defaultValue={seed}- onChange={handleChange}- size={size}- minHeight="12rem"- isReadOnly={isReadOnly}- isDisabled={isDisabled}- isRequired={isRequired}- isOptional={isOptional}- hasAutoFocus={hasAutoFocus}- status={status}- statusVariant={statusVariant}- maxLength={hasCharacterLimit ? 500 : undefined}- hasMarkdownShortcuts={hasMarkdownShortcuts}- {...(transformers ? {transformers} : {})}- {...(extensions ? {markdownExtensions: extensions} : {})}- toolbar={- hasToolbar ? (- <RichTextEditorToolbar- size={toolbarSize}- hasLink={hasLink}- hasNewTabLinks={hasNewTabLinks}- endContent={hasInsertControls ? <InsertControls /> : null}- />- ) : undefined- }- plugins={hasAutoLink ? <RichTextEditorAutoLinkPlugin /> : null}- />+ {/* The image button renders in the toolbar's endContent and its+ dialog in the plugins slot — two places the editor renders+ separately — so their shared open state comes from a provider+ around the editor that holds both. */}+ <InsertImageProvider>+ <RichTextEditor+ key={mountKey}+ ref={editorRef}+ label="Playground"+ isLabelHidden={isLabelHidden}+ description={+ hasDescription+ ? 'Bold, italic, lists, task lists, quotes, links, code blocks and tables.'+ : undefined+ }+ placeholder="Write something, or load a document below…"+ defaultValue={seed}+ onChange={handleChange}+ size={size}+ minHeight="12rem"+ isReadOnly={isReadOnly}+ isDisabled={isDisabled}+ isRequired={isRequired}+ isOptional={isOptional}+ hasAutoFocus={hasAutoFocus}+ status={status}+ statusVariant={statusVariant}+ maxLength={hasCharacterLimit ? 500 : undefined}+ hasMarkdownShortcuts={hasMarkdownShortcuts}+ {...(transformers ? {transformers} : {})}+ {...(extensions ? {markdownExtensions: extensions} : {})}+ {...(nodes ? {nodes} : {})}+ toolbar={+ hasToolbar ? (+ <RichTextEditorToolbar+ size={toolbarSize}+ hasLink={hasLink}+ hasNewTabLinks={hasNewTabLinks}+ endContent={+ hasInsertControls ? (+ <InsertControls hasImages={hasImages} />+ ) : null+ }+ />+ ) : undefined+ }+ plugins={+ <>+ {hasAutoLink && <RichTextEditorAutoLinkPlugin />}+ {hasImages && (+ <>+ <RichTextImagesPlugin />+ {/* Outside the toolbar: a Toolbar is a roving tab stop,+ so a dialog rendered in its endContent cannot be+ tabbed through. RichTextEditorToolbar puts its own+ link dialog beside the toolbar for the same reason. */}+ <InsertImageDialog />+ </>+ )}+ </>+ }+ />+ </InsertImageProvider></div><div data-playground-stats="" {...stylex.props(styles.stats)}>@@ -687,6 +777,11 @@ export function RichTextEditorPlayground() {<Text type="supporting">{stats.words} words</Text><Text type="supporting">{stats.blocks} top-level blocks</Text><Text type="supporting">{stats.nodes} nodes</Text>+ {stats.images > 0 && (+ <Text type="supporting">+ {stats.images === 1 ? '1 image' : `${stats.images} images`}+ </Text>+ )}</div><div {...stylex.props(styles.actions)}>@@ -747,20 +842,43 @@ export function RichTextEditorPlayground() {{tab === 'view' ? (<div {...stylex.props(styles.viewSurface)}><RichTextView+ // RichTextView reads `nodes` once, when it builds its own+ // editor. A view mounted while images were off cannot+ // parse state holding one, and renders its empty fallback+ // — the whole document gone — so it is rebuilt with the+ // node list, as the editor is.+ key={hasImages ? 'with-images' : 'without-images'}value={stateJSON}{...(extensions ? {markdownExtensions: extensions} : {})}+ {...(nodes ? {nodes} : {})}/></div>) : (- <pre {...stylex.props(styles.output)}>- {tab === 'markdown'- ? markdown- : tab === 'html'- ? html- : tab === 'tree'- ? tree- : stateJSON}- </pre>+ <>+ {tab === 'markdown' && stats.images > 0 && (+ <Text type="supporting">+ {stats.images === 1+ ? 'One image is'+ : `${stats.images} images are`}{' '}+ missing from this Markdown. RichText's default+ transformer array is internal, and the transformers prop+ replaces it whole rather than extending it, so a caller+ cannot add an image transformer without giving up tables,+ task lists and the rest of the dialect. An image still+ reaches the editor state, the HTML export and+ RichTextView.+ </Text>+ )}+ <pre {...stylex.props(styles.output)}>+ {tab === 'markdown'+ ? markdown+ : tab === 'html'+ ? html+ : tab === 'tree'+ ? tree+ : stateJSON}+ </pre>+ </>)}</div></div>@@ -782,7 +900,7 @@ export function RichTextEditorPlayground() {<Switchsize="sm"label="Insert controls"- description="Table, rule and mention, in the toolbar's endContent slot"+ description="Table, rule, mention and image, in the toolbar's endContent slot"value={hasInsertControls}onChange={setHasInsertControls}isDisabled={!hasToolbar}@@ -826,10 +944,17 @@ export function RichTextEditorPlayground() {<Switchsize="sm"label="Markdown plugins"- description="The demo mention and callout plugins, adopted with createRichTextExtension"+ description="The demo mention and callout plugins, adopted with createRichTextExtension. Switching re-imports the document from Markdown, where images do not survive."value={hasMarkdownPlugins}onChange={toggleMarkdownPlugins}/>+ <Switch+ size="sm"+ label="Images"+ description="A custom ImageNode through the nodes prop: insert from the toolbar, drop or paste an image file, drag the handle to resize"+ value={hasImages}+ onChange={toggleImages}+ /><Switchsize="sm"label="Restricted transformers"@@ -1006,7 +1131,9 @@ export function RichTextEditorPlayground() {<div {...stylex.props(styles.group)}>{SHORTCUTS.filter(shortcut =>- shortcut.needsLinkButton !== true || (hasToolbar && hasLink),+ (shortcut.needsLinkButton !== true ||+ (hasToolbar && hasLink)) &&+ (shortcut.needsImages !== true || hasImages),).map(shortcut => (<div key={shortcut.keys} {...stylex.props(styles.shortcutRow)}><Text type="supporting">{shortcut.action}</Text>diff --git a/packages/richtext/src/__tests__/Playground.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/Playground.a11y.chromium.spec.tsindex 0c373109e0..19267209aa 100644--- a/packages/richtext/src/__tests__/Playground.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/Playground.a11y.chromium.spec.ts@@ -42,7 +42,10 @@ test.afterAll(async () => {await storybook?.close();});-async function openStory(page: Page): Promise<string[]> {+async function openStory(+ page: Page,+ direction: 'ltr' | 'rtl' = 'ltr',+): Promise<string[]> {const errors: string[] = [];page.on('pageerror', error => errors.push(String(error)));page.on('console', message => {@@ -52,7 +55,7 @@ async function openStory(page: Page): Promise<string[]> {});await page.setViewportSize({width: 1440, height: 900});await page.goto(- `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:${direction}`,{waitUntil: 'load'},);await expect(page.locator(EDITOR)).toBeVisible();@@ -177,7 +180,7 @@ test("the endContent controls disable with the editor, like the toolbar's own",}) => {const errors = await openStory(page);const editor = page.locator(EDITOR);- const inserts = ['Table', 'Rule', 'Mention'].map(name =>+ const inserts = ['Table', 'Rule', 'Mention', 'Image'].map(name =>page.getByRole('button', {name, exact: true}),);const bold = page.getByRole('button', {name: 'Bold', exact: true});@@ -283,6 +286,440 @@ const AXE_DISABLED_RULES = ['region',];+/* ------------------------------------------------------------------ *+ * The image plugin+ * ------------------------------------------------------------------ */++/** The image the editor holds, as the plugin draws it. */+const IMAGE = '[data-playground-editor] [data-playground-image] img';++/** Inserts the dialog's default sample image into the one editor. */+async function insertSampleImage(page: Page): Promise<void> {+ await page.locator(EDITOR).click();+ await page.keyboard.press('ControlOrMeta+End');+ await page.getByRole('button', {name: 'Image', exact: true}).click();+ // The dialog opens on its sample source, so this is one click away.+ await expect(page.getByRole('heading', {name: 'Insert image'})).toBeVisible();+ await page.getByRole('button', {name: 'Insert image', exact: true}).click();+ await expect(page.locator(IMAGE)).toHaveCount(1);+}++/** The image's rendered width, which is what a resize moves. */+async function imageWidth(page: Page): Promise<number> {+ const box = await page.locator(IMAGE).boundingBox();+ return box?.width ?? 0;+}++test('the image plugin inserts an image through the editor nodes prop', async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);++ // The alt text the sample carries reaches the DOM, so the picture is not+ // silent to a screen reader.+ await expect(page.locator(IMAGE)).toHaveAttribute(+ 'alt',+ /illustration of layered hills/,+ );+ // One editor still, with the image inside the editable surface.+ await expect(+ page.locator('[role="textbox"][data-lexical-editor]'),+ ).toHaveCount(1);+ await expect(page.locator('[data-playground-stats]')).toContainText(+ '1 image',+ );+ expect(errors).toEqual([]);+});++test('a selected image resizes by its handle and by its controls, and removes itself', async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);+ const image = page.locator(IMAGE);+ // The width the image draws at before anything resizes it, which is what+ // "Reset size" must restore.+ const natural = await imageWidth(page);++ // Nothing is offered until the image is selected: the controls and the+ // resize handle belong to a selected image, like Lexical's own.+ await expect(page.locator('[data-playground-image-actions]')).toHaveCount(0);+ await image.click();+ await expect(page.locator('[data-playground-image-actions]')).toHaveCount(1);++ const started = await imageWidth(page);+ await page.getByRole('button', {name: 'Larger', exact: true}).click();+ await expect+ .poll(() => imageWidth(page), {message: 'Larger widens the image'})+ .toBeGreaterThan(started + 1);++ const widened = await imageWidth(page);+ await page.getByRole('button', {name: 'Smaller', exact: true}).click();+ await expect+ .poll(() => imageWidth(page), {message: 'Smaller narrows the image'})+ .toBeLessThan(widened - 1);++ // Dragging the handle resizes too, and commits the width to the node: the+ // editor state carries it after the pointer is lifted.+ const handle = page.locator('[data-playground-image-handle]');+ const box = await handle.boundingBox();+ const before = await imageWidth(page);+ await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);+ await page.mouse.down();+ await page.mouse.move(box!.x + box!.width / 2 + 80, box!.y, {steps: 8});+ await page.mouse.up();+ await expect+ .poll(() => imageWidth(page), {message: 'the handle widens the image'})+ .toBeGreaterThan(before + 40);++ await page.getByRole('tab', {name: 'Editor state'}).click();+ await expect(page.locator('[data-playground-output]')).toContainText(+ /"width":\s*\d+/,+ );++ // Reset size puts the image back to the width it drew at when it arrived.+ await page.getByRole('button', {name: 'Reset size', exact: true}).click();+ await expect+ .poll(() => imageWidth(page), {message: 'Reset size restores the image'})+ .toBeCloseTo(natural, 0);++ await page.getByRole('button', {name: 'Remove image', exact: true}).click();+ await expect(page.locator(IMAGE)).toHaveCount(0);+ expect(errors).toEqual([]);+});++test("Enter opens a selected image's controls, activates them, and Escape leaves", async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);+ await page.locator(IMAGE).click();++ // Tab indents inside the editor, so Enter is the keyboard route into the+ // controls of the selected image — without it they are mouse-only.+ await page.keyboard.press('Enter');+ await expect(+ page.getByRole('button', {name: 'Smaller', exact: true}),+ ).toBeFocused();++ // Enter pressed ON a control bubbles back to the editor, where the image is+ // still the selected node: the handler that opened the controls has to let+ // that keystroke through, or every control is dead to the keyboard.+ const before = await imageWidth(page);+ await page.keyboard.press('Enter');+ await expect+ .poll(() => imageWidth(page), {message: 'Enter on Smaller narrows it'})+ .toBeLessThan(before - 1);++ const narrowed = await imageWidth(page);+ await page.keyboard.press('Tab');+ await expect(+ page.getByRole('button', {name: 'Larger', exact: true}),+ ).toBeFocused();+ await page.keyboard.press('Enter');+ await expect+ .poll(() => imageWidth(page), {message: 'Enter on Larger widens it'})+ .toBeGreaterThan(narrowed + 1);++ await page.keyboard.press('Escape');+ await expect(page.locator(EDITOR)).toBeFocused();+ expect(errors).toEqual([]);+});++test('the resize handle follows the drag in a right-to-left document', async ({+ page,+}) => {+ // The handle sits on the inline end, which is the image's LEFT edge here,+ // so dragging it outward lowers clientX. A width that followed the axis+ // rather than the drag would shrink the image instead.+ const errors = await openStory(page, 'rtl');+ await insertSampleImage(page);+ await page.locator(IMAGE).click();+ // Narrow it first: at its own width the picture is already near the+ // measure, and `max-width: 100%` would absorb the drag.+ await page.getByRole('button', {name: 'Smaller', exact: true}).click();+ await page.getByRole('button', {name: 'Smaller', exact: true}).click();+ const before = await imageWidth(page);++ const handle = page.locator('[data-playground-image-handle]');+ const box = await handle.boundingBox();+ await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);+ await page.mouse.down();+ await page.mouse.move(box!.x + box!.width / 2 - 80, box!.y, {steps: 8});+ await page.mouse.up();+ await expect+ .poll(() => imageWidth(page), {message: 'dragging outward widens it'})+ .toBeGreaterThan(before + 40);+ expect(errors).toEqual([]);+});++test('an image reaches the state, the HTML and RichTextView, and says why it is not in the Markdown', async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);+ const output = page.locator('[data-playground-output]');++ await page.getByRole('tab', {name: 'Editor state'}).click();+ await expect(output).toContainText('"playground-image"');++ await page.getByRole('tab', {name: 'Node tree'}).click();+ await expect(output).toContainText('playground-image alt=');++ await page.getByRole('tab', {name: 'HTML'}).click();+ await expect(output).toContainText('<img');++ await page.getByRole('tab', {name: 'RichTextView'}).click();+ await expect(output.locator('img')).toHaveCount(1);++ // The Markdown readout does NOT carry the image, because RichText's default+ // transformer array is internal and `transformers` replaces it whole. A+ // readout that silently dropped content would read as a bug, so the+ // playground says so where the content is missing.+ await page.getByRole('tab', {name: 'Markdown'}).click();+ await expect(output).not.toContainText('![');+ await expect(output).toContainText('missing from this Markdown');+ expect(errors).toEqual([]);+});++test('turning the image node off takes the document back through Markdown', async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);+ await expect(page.locator(IMAGE)).toHaveCount(1);++ // Every switch that re-imports the document from Markdown drops the images+ // with it, so each one says so where a reader decides to flip it.+ await expect(settings(page)).toContainText(+ 'Markdown, where images do not survive',+ );++ // `nodes` is read at construction, so the switch rebuilds the editor. State+ // holding an image cannot be parsed without the node registered, so the+ // document round-trips through Markdown — and the image does not survive.+ await toggle(page, 'Images').click();+ await expect(page.locator(EDITOR)).toBeVisible();+ await expect(page.locator(IMAGE)).toHaveCount(0);+ await expect(+ page.getByRole('button', {name: 'Image', exact: true}),+ ).toHaveCount(0);+ // The document itself is still here.+ await expect(page.locator(`${EDITOR} table`)).toHaveCount(1);++ await toggle(page, 'Images').click();+ await expect(+ page.getByRole('button', {name: 'Image', exact: true}),+ ).toBeVisible();+ expect(errors).toEqual([]);+});++test('an image file dropped or pasted into the editor becomes an image', async ({+ page,+}) => {+ const errors = await openStory(page);+ await page.locator(EDITOR).click();+ await page.keyboard.press('ControlOrMeta+End');++ // A real drop and a real paste cannot be driven from the test runner, so the+ // events are built with the same shapes a browser delivers: a DragEvent and+ // a ClipboardEvent, each carrying one image file.+ const deliverFile = (type: 'drop' | 'paste') =>+ page.evaluate(async (eventType: string) => {+ const pixel =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';+ const blob = await (await fetch(pixel)).blob();+ const transfer = new DataTransfer();+ transfer.items.add(+ new File([blob], `${eventType}ped.png`, {type: 'image/png'}),+ );+ const target = document.querySelector(+ '[data-playground-editor] [role="textbox"]',+ );+ target?.dispatchEvent(+ eventType === 'drop'+ ? new DragEvent('drop', {+ bubbles: true,+ cancelable: true,+ dataTransfer: transfer,+ })+ : new ClipboardEvent('paste', {+ bubbles: true,+ cancelable: true,+ clipboardData: transfer,+ }),+ );+ }, type);++ await deliverFile('drop');+ await expect(page.locator(IMAGE)).toHaveCount(1);+ // The file's name is the alt text until someone says better.+ await expect(page.locator(IMAGE)).toHaveAttribute('alt', 'dropped.png');++ await deliverFile('paste');+ await expect(page.locator(IMAGE)).toHaveCount(2);+ expect(errors).toEqual([]);+});++test('a dropped image lands where it was dropped, not at the caret', async ({+ page,+}) => {+ const errors = await openStory(page);+ // The caret is at the very start of the document…+ await page.locator(EDITOR).click();+ await page.keyboard.press('ControlOrMeta+Home');++ // …and the file is dropped on the last paragraph, far from it. The plugin+ // consumes DROP_COMMAND ahead of the rich-text handler that would have+ // moved the selection to the drop point, so it has to do that itself.+ const target = page.locator(`${EDITOR} > p`).last();+ // The drop point is a VIEWPORT coordinate, which is what the browser gives+ // a real drop and what `caretPositionFromPoint` reads; the seeded document+ // is taller than the viewport, so the target has to be on screen first.+ await target.scrollIntoViewIfNeeded();+ const box = await target.boundingBox();+ const dropAt = {x: box!.x + box!.width / 2, y: box!.y + box!.height / 2};+ await page.evaluate(async ({x, y}: {x: number; y: number}) => {+ const pixel =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';+ const blob = await (await fetch(pixel)).blob();+ const transfer = new DataTransfer();+ transfer.items.add(new File([blob], 'placed.png', {type: 'image/png'}));+ document+ .querySelector('[data-playground-editor] [role="textbox"]')+ ?.dispatchEvent(+ new DragEvent('drop', {+ bubbles: true,+ cancelable: true,+ clientX: x,+ clientY: y,+ dataTransfer: transfer,+ }),+ );+ }, dropAt);++ await expect(page.locator(IMAGE)).toHaveCount(1);+ // Where it was dropped. Position, not block identity: inserting at a caret+ // inside a paragraph splits it, so the image lands in a paragraph of its+ // own between the halves — which is correct, and is not the element that+ // was dropped on.+ const landed = await page.locator(IMAGE).boundingBox();+ expect(+ Math.abs(landed!.y - dropAt.y),+ 'the image is at the drop point, not at the caret',+ ).toBeLessThan(80);+ // The caret was in the heading, at the top of a document taller than this.+ const heading = await page.locator(`${EDITOR} h1`).boundingBox();+ expect(landed!.y - heading!.y).toBeGreaterThan(200);+ expect(errors).toEqual([]);+});++test('a file dropped onto a decorator lands beside it, not at the top', async ({+ page,+}) => {+ const errors = await openStory(page);+ // An image to drop onto, with the caret left near it rather than at the top+ // of the document, so "landed at the top" cannot pass by accident.+ await insertSampleImage(page);+ const existing = page.locator(IMAGE);+ await existing.scrollIntoViewIfNeeded();+ const box = await existing.boundingBox();++ // A point inside a decorator resolves to no Lexical position, and a fresh+ // range selection then sits at the root's offset 0 — the top of the+ // document, nowhere near the drop.+ await page.evaluate(+ async ({x, y}: {x: number; y: number}) => {+ const pixel =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';+ const blob = await (await fetch(pixel)).blob();+ const transfer = new DataTransfer();+ transfer.items.add(new File([blob], 'beside.png', {type: 'image/png'}));+ document+ .querySelector('[data-playground-editor] [role="textbox"]')+ ?.dispatchEvent(+ new DragEvent('drop', {+ bubbles: true,+ cancelable: true,+ clientX: x,+ clientY: y,+ dataTransfer: transfer,+ }),+ );+ },+ {x: box!.x + box!.width / 2, y: box!.y + box!.height / 2},+ );++ await expect(page.locator(IMAGE)).toHaveCount(2);+ const dropped = page.locator(`${EDITOR} img[alt="beside.png"]`);+ await expect(dropped).toHaveCount(1);+ // Beside the image it was dropped on, not above the document's heading.+ const landed = await dropped.boundingBox();+ const heading = await page.locator(`${EDITOR} h1`).boundingBox();+ expect(+ landed!.y - heading!.y,+ 'the file landed beside the decorator, not at the top',+ ).toBeGreaterThan(200);+ expect(errors).toEqual([]);+});++test('the insert dialog is tabbable, outside the toolbar roving tab stop', async ({+ page,+}) => {+ const errors = await openStory(page);+ const button = page.getByRole('button', {name: 'Image', exact: true});+ await button.focus();+ await expect(button).toHaveAttribute('aria-haspopup', 'dialog');+ await page.keyboard.press('Enter');+ await expect(page.getByRole('heading', {name: 'Insert image'})).toBeVisible();++ // A Toolbar is a roving tab stop: everything inside it is tabindex="-1", so+ // a dialog rendered in its endContent could not be tabbed through at all.+ // The dialog goes in the editor's plugins slot instead, beside the toolbar+ // — which is where RichTextEditorToolbar puts its own link dialog.+ const insert = page.getByRole('button', {name: 'Insert image', exact: true});+ for (let press = 0; press < 12; press += 1) {+ if (await insert.evaluate(el => el === document.activeElement)) {+ break;+ }+ await page.keyboard.press('Tab');+ }+ await expect(insert).toBeFocused();++ await page.keyboard.press('Enter');+ await expect(page.locator(IMAGE)).toHaveCount(1);+ // And focus lands back in the editor, not on the button that opened the+ // dialog: a Dialog returns focus to its invoker as it closes, so the next+ // keystroke would otherwise reopen it instead of typing.+ await expect(page.locator(EDITOR)).toBeFocused();+ await page.keyboard.type('after the image');+ await expect(page.locator(EDITOR)).toContainText('after the image');+ expect(errors).toEqual([]);+});++test('the RichTextView readout survives the image node arriving under it', async ({+ page,+}) => {+ const errors = await openStory(page);+ const output = page.locator('[data-playground-output]');++ // The view reads `nodes` once, when it builds its own editor. Opened while+ // images are off, it would then fail to parse state holding one and render+ // its empty fallback — the whole document gone, not just the image.+ await toggle(page, 'Images').click();+ await page.getByRole('tab', {name: 'RichTextView'}).click();+ await expect(output.locator('table')).toHaveCount(1);++ await toggle(page, 'Images').click();+ await insertSampleImage(page);+ await page.getByRole('tab', {name: 'RichTextView'}).click();+ await expect(output.locator('img')).toHaveCount(1);+ // The document is still under it, not an empty fallback.+ await expect(output.locator('table')).toHaveCount(1);+ expect(errors).toEqual([]);+});+test('the story has no axe violations', async ({page}) => {const errors = await openStory(page);const results = await new AxeBuilder({page})@@ -296,3 +733,22 @@ test('the story has no axe violations', async ({page}) => {).toEqual([]);expect(errors).toEqual([]);});++test('the story has no axe violations with a selected image in it', async ({+ page,+}) => {+ const errors = await openStory(page);+ await insertSampleImage(page);+ await page.locator(IMAGE).click();+ await expect(page.locator('[data-playground-image-actions]')).toHaveCount(1);+ const results = await new AxeBuilder({page})+ .disableRules(AXE_DISABLED_RULES)+ .analyze();+ expect(+ results.violations.map(violation => [+ violation.id,+ violation.nodes.map(node => node.target.join(' ')),+ ]),+ ).toEqual([]);+ expect(errors).toEqual([]);+});