Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(markdown): put images inside list items without splitting the list (#9361)
Eric Hayes210ec2d9ce25
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.mdindex 18f0600ecf..b5e1032062 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md@@ -48,3 +48,15 @@ unquoted paragraphs retain normal paste behavior.Screenshots: [desktop](proof/quotes-desktop.png), [phone](proof/quotes-mobile.png),and [multi-paragraph paste](proof/quote-paste.png).++## Images in lists++`list-images.browser.e2e.ts` mounts the production Markdown editor with media+and file drop over a numbered list. It inserts an image from an item, from the+empty item Enter leaves (the image joins the item above, and a second Enter+leaves the list), presses Enter after an item with an image, and drops a file on+an item. It checks that the list stays one list with continuous numbering, that+images align with their item's text, and that the saved Markdown indents each+image under its item and renders back as one list, on desktop, tablet touch, and+phone touch. Run just this case by adding `list-images.browser.e2e.ts` to the+command above.diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.browser.e2e.tsnew file mode 100644index 0000000000..a793ae6b80--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.browser.e2e.ts@@ -0,0 +1,129 @@+import { expect, type Locator, type Page, test } from '@playwright/test';++async function placeCaretAtEnd(page: Page, index: number) {+ await page.getByRole('spinbutton', { name: 'Item' }).fill(String(index));+ await page.getByRole('button', { name: 'Select item text end' }).click();+}++/** Each top-level list item's value and whether an image sits inside it. */+function listOutline(editor: Locator) {+ return editor.evaluate((element) =>+ [...element.querySelectorAll(':scope > ol > li')].map((item) => ({+ value: item instanceof HTMLLIElement ? item.value : 0,+ text: item.textContent ?? '',+ images: item.querySelectorAll('[data-lexical-decorator]').length,+ }))+ );+}++test('images join list items without breaking the list or its numbering', async ({+ page,+ context,+}, testInfo) => {+ await context.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.includes('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({ status: 401, body: '{}' });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(+ '/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.html'+ );+ const editor = page.getByRole('textbox', { name: 'Document' });+ await expect(editor).toBeVisible({ timeout: 60_000 });+ const items = editor.locator(':scope > ol > li');+ await expect(items).toHaveCount(3);++ // Insert with the caret in an item: the image goes under that item.+ await placeCaretAtEnd(page, 0);+ await page.getByRole('button', { name: 'Insert image' }).click();+ await expect(items.nth(0).locator('[data-lexical-decorator]')).toHaveCount(1);+ expect(await listOutline(editor)).toEqual([+ { value: 1, text: 'First step', images: 1 },+ { value: 2, text: 'Second step', images: 0 },+ { value: 3, text: 'Third step', images: 0 },+ ]);+ const image = await items.nth(0).locator('img').boundingBox();+ const text = await items.nth(0).locator('span').first().boundingBox();+ expect(image && text && image.y).toBeGreaterThan(text?.y ?? 0);+ expect(Math.abs((image?.x ?? 0) - (text?.x ?? 0))).toBeLessThan(2);++ // Enter after the item's text starts the next item below the image.+ await placeCaretAtEnd(page, 0);+ await page.keyboard.press('Enter');+ await page.keyboard.type('Between');+ expect(await listOutline(editor)).toEqual([+ { value: 1, text: 'First step', images: 1 },+ { value: 2, text: 'Between', images: 0 },+ { value: 3, text: 'Second step', images: 0 },+ { value: 4, text: 'Third step', images: 0 },+ ]);++ // On the empty item Enter leaves, an image joins the item above; a second+ // Enter leaves the list and the next image sits below it.+ await placeCaretAtEnd(page, 3);+ await page.keyboard.press('Enter');+ await page.getByRole('button', { name: 'Insert image' }).click();+ await expect(items.nth(3).locator('[data-lexical-decorator]')).toHaveCount(1);+ await expect(items).toHaveCount(5);+ await placeCaretAtEnd(page, 4);+ await page.keyboard.press('Enter');+ await expect(items).toHaveCount(4);+ await page.getByRole('button', { name: 'Insert image' }).click();+ await expect(editor.locator(':scope > ol')).toHaveCount(1);+ await expect(+ editor.locator(':scope > ol [data-lexical-decorator]')+ ).toHaveCount(2);+ await expect(editor.locator('[data-lexical-decorator]')).toHaveCount(3);++ // A file dropped on an item's lower half joins that item.+ const second = await items.nth(2).boundingBox();+ if (!second) throw new Error('Missing second item');+ await editor.evaluate(+ (element, point) => {+ const transfer = new DataTransfer();+ transfer.items.add(+ new File([new Uint8Array([137, 80, 78, 71])], 'drop.png', {+ type: 'image/png',+ })+ );+ for (const type of ['dragover', 'drop']) {+ element.dispatchEvent(+ new DragEvent(type, {+ bubbles: true,+ cancelable: true,+ clientX: point.x,+ clientY: point.y,+ dataTransfer: transfer,+ })+ );+ }+ },+ { x: second.x + 20, y: second.y + second.height * 0.75 }+ );+ await expect(items.nth(2).locator('[data-lexical-decorator]')).toHaveCount(1);+ expect((await listOutline(editor)).map((item) => item.value)).toEqual([+ 1, 2, 3, 4,+ ]);++ await page.getByRole('button', { name: 'Save' }).click();+ const markdown = await page.getByTestId('saved-markdown').textContent();+ expect(markdown).toMatch(/^1\. First step\n {3}!\[Screenshot\]\(data:/);+ const saved = page.getByTestId('saved');+ await expect(saved.locator('ol')).toHaveCount(1);+ await expect(saved.locator('ol img')).toHaveCount(2);++ await page.screenshot({+ path: testInfo.outputPath('list-images.png'),+ fullPage: true,+ });+ expect(errors).toEqual([]);+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.html b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.htmlnew file mode 100644index 0000000000..84720e13d4--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>List images</title></head>+ <body><div id="root"></div><script type="module" src="./list-images.tsx"></script></body>+</html>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.tsxnew file mode 100644index 0000000000..ffd9134acb--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/list-images.tsx@@ -0,0 +1,95 @@+import '@app/index.css';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { $isListNode } from '@lexical/list';+import { $getRoot, $isElementNode, $isTextNode } from 'lexical';+import { createSignal } from 'solid-js';+import { render } from 'solid-js/web';+import { buildConfig } from '../../../builder/MarkdownConfigBuilder';+import { MarkdownShell } from '../../../builder/MarkdownShell';+import { initializeLexical } from '../../../init';+import { INSERT_MEDIA_COMMAND } from '../../../plugins/media';+import { StaticMarkdown, StaticMarkdownContext } from '../StaticMarkdown';++function imageUrl() {+ const canvas = document.createElement('canvas');+ canvas.width = 320;+ canvas.height = 180;+ const context = canvas.getContext('2d');+ if (context) {+ context.fillStyle = '#4f7cff';+ context.fillRect(0, 0, 320, 180);+ }+ return canvas.toDataURL('image/png');+}++initializeLexical();++function Fixture() {+ document.documentElement.dataset.touchDevice = String(isTouchDevice());+ const [saved, setSaved] = createSignal('');+ const [itemIndex, setItemIndex] = createSignal(0);+ const editor = buildConfig('markdown')+ .namespace('list-images')+ .withHistory()+ .withMedia({ fileDrop: true });+ return (+ <StaticMarkdownContext>+ <main class="h-dvh overflow-y-auto p-6 bg-page text-ink max-w-2xl space-y-6">+ <h1 class="text-xl font-medium">Images in lists</h1>+ <MarkdownShell+ config={editor}+ initialValue={'1. First step\n2. Second step\n3. Third step'}+ ariaLabel="Document"+ />+ <label class="flex gap-2">+ Item+ <input+ aria-label="Item"+ type="number"+ class="w-16 border border-edge"+ value={itemIndex()}+ onInput={(event) => setItemIndex(event.currentTarget.valueAsNumber)}+ />+ </label>+ <button+ onClick={() => {+ editor.lexical.update(() => {+ // Where a tap at the end of the item's text puts the caret.+ const list = $getRoot().getFirstChild();+ if (!$isListNode(list)) return;+ const item = list.getChildAtIndex(itemIndex());+ if (!$isElementNode(item)) return;+ const text = item.getChildren().filter($isTextNode).at(-1);+ if (text) text.select();+ else item.selectEnd();+ });+ editor.lexical.focus();+ }}+ >+ Select item text end+ </button>+ <button+ onClick={() =>+ editor.lexical.dispatchCommand(INSERT_MEDIA_COMMAND, {+ type: 'url',+ url: imageUrl(),+ alt: 'Screenshot',+ mediaType: 'image',+ })+ }+ >+ Insert image+ </button>+ <button onClick={() => setSaved(editor.controls.getMarkdown())}>+ Save+ </button>+ <pre data-testid="saved-markdown">{saved()}</pre>+ <section data-testid="saved">+ <StaticMarkdown markdown={saved()} />+ </section>+ </main>+ </StaticMarkdownContext>+ );+}++render(() => <Fixture />, document.getElementById('root')!);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsxindex 633d1dda6b..b233a1763b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx@@ -288,7 +288,9 @@ export function MarkdownImage(props: ImageDecoratorProps) {state() === 'error' && 'pattern-edge-muted pattern-diagonal-8',state() === 'error' && !effectiveDims()[0] && 'min-h-44',// If there are no constrained dimensions, center the image- !props.constrainedWidth && !props.constrainedHeight && 'mx-auto'+ !props.constrainedWidth && !props.constrainedHeight && 'mx-auto',+ // Under a list item, sit at the item's text like Notion+ 'in-[li]:mx-0 in-[li]:my-2')}style={{width: effectiveDims()[0] ? '100%' : undefined,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/drag-insert/dragInsertPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/drag-insert/dragInsertPlugin.tsindex 890416a7c3..7eec70dc7d 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/drag-insert/dragInsertPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/drag-insert/dragInsertPlugin.ts@@ -1,5 +1,11 @@+import {+ $isListItemNode,+ $isListNode,+ type ListItemNode,+ type ListNode,+} from '@lexical/list';import { DRAG_DROP_PASTE } from '@lexical/rich-text';-import { mergeRegister } from '@lexical/utils';+import { $dfs, mergeRegister } from '@lexical/utils';import {$getNodeByKey,$getRoot,@@ -82,18 +88,57 @@ function elementKeyToDomRect(editor: LexicalEditor, key: NodeKey) {}}+type InsertPoint = {+ key: NodeKey | null;+ position: InsertionMarker | null;+ domRect: DOMRect | null;+};+/**- * Get an insertion point from a drag event.DOMRect+ * The end of the list item a drop at `clientY` belongs under: the item over+ * the pointer's lower half, else the item above. Media inserted there joins+ * that item instead of splitting the list.+ */+function $listItemInsertPoint(+ editor: LexicalEditor,+ list: ListNode,+ clientY: number+): InsertPoint | null {+ const items = $dfs(list)+ .map(({ node }) => node)+ .filter(+ (node): node is ListItemNode =>+ $isListItemNode(node) && !$isListNode(node.getFirstChild())+ );+ const index = items.findIndex(+ (item) =>+ clientY <=+ (elementKeyToDomRect(editor, item.getKey())?.bottom ?? -Infinity)+ );+ if (index === -1) return null;+ const rect = elementKeyToDomRect(editor, items[index].getKey());+ const target =+ rect && clientY >= rect.top + rect.height * 0.5+ ? items[index]+ : items[index - 1];+ if (!target) return null;+ return {+ key: target.getKey(),+ position: 'after',+ domRect: elementKeyToDomRect(editor, target.getKey()) ?? null,+ };+}++/**+ * Get an insertion point from a drag event. Top-level blocks only, unless+ * `intoListItems` lets a drop over a list target one of its items.*/export function calculateInsertPoint(editor: LexicalEditor,event: DragEvent | { clientX: number; clientY: number },- collisionPadding = 0-): {- key: NodeKey | null;- position: InsertionMarker | null;- domRect: DOMRect | null;-} {+ collisionPadding = 0,+ intoListItems = false+): InsertPoint {return editor.read(() => {const editorRect = editor.getRootElement()?.getBoundingClientRect();if (@@ -141,6 +186,11 @@ export function calculateInsertPoint(const rect = elem.getBoundingClientRect();if (containsY(rect, event.clientY, collisionPadding)) {+ const listItemPoint =+ intoListItems && $isListNode(childNode)+ ? $listItemInsertPoint(editor, childNode, event.clientY)+ : null;+ if (listItemPoint) return listItemPoint;if (event.clientY < rect.top + rect.height * 0.5) {const priorSibling = childNode.getPreviousSibling();if (priorSibling) {@@ -164,6 +214,11 @@ export function calculateInsertPoint(});}+// Files dropped into a list (images, attachments) join the item under the pointer.+function carriesFiles(event: DragEvent) {+ return event.dataTransfer?.types.includes('Files') ?? false;+}+function registerDragInsert(editor: LexicalEditor,props: DragInsertPluginProps@@ -175,7 +230,8 @@ function registerDragInsert(const { key, position } = calculateInsertPoint(editor,event,- collisionPadding+ collisionPadding,+ carriesFiles(event));if (!key || !position) {@@ -210,7 +266,8 @@ function registerDragInsert(const { key, position } = calculateInsertPoint(editor,event,- collisionPadding+ collisionPadding,+ carriesFiles(event));if (!key || !position) {return;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.test.tsnew file mode 100644index 0000000000..d16cf96340--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.test.ts@@ -0,0 +1,169 @@+import {+ $createListItemNode,+ $createListNode,+ $isListItemNode,+ $isListNode,+ registerList,+} from '@lexical/list';+import { mergeRegister } from '@lexical/utils';+import { $createImageNode, SupportedNodeTypes } from '@macro-inc/lexical-core';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+ INSERT_PARAGRAPH_COMMAND,+ type LexicalEditor,+} from 'lexical';+import { afterEach, describe, expect, it } from 'vitest';+import {+ $insertImageIntoListItem,+ registerListItemImages,+} from './listItemImages';++const unmounts: Array<() => void> = [];++afterEach(() => {+ for (const unmount of unmounts.splice(0)) unmount();+});++/** A numbered list from `items`; `''` is an empty item. The caret ends on `caretItem`. */+function mountList(items: string[], caretItem: number) {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ const unregister = mergeRegister(+ registerList(editor),+ registerListItemImages(editor)+ );+ const element = document.createElement('div');+ element.contentEditable = 'true';+ document.body.append(element);+ editor.setRootElement(element);+ unmounts.push(() => {+ unregister();+ editor.setRootElement(null);+ element.remove();+ });+ editor.update(+ () => {+ const list = $createListNode('number');+ for (const text of items) {+ const item = $createListItemNode();+ if (text) item.append($createTextNode(text));+ list.append(item);+ }+ $getRoot().clear().append(list);+ list.getChildAtIndex(caretItem)?.selectEnd();+ },+ { discrete: true }+ );+ return editor;+}++function insertImage(editor: LexicalEditor) {+ let inserted = false;+ editor.update(+ () => {+ inserted = $insertImageIntoListItem(+ $createImageNode({ srcType: 'url', url: 'https://example.com/a.png' })+ );+ },+ { discrete: true }+ );+ return inserted;+}++function pressEnter(editor: LexicalEditor) {+ editor.update(+ () => {+ editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);+ },+ { discrete: true }+ );+}++/** Each top-level block, with each list item's value and child types. */+function outline(editor: LexicalEditor) {+ return editor.read(() =>+ $getRoot()+ .getChildren()+ .map((block) =>+ $isListNode(block)+ ? block+ .getChildren()+ .filter($isListItemNode)+ .map((item) => [+ item.getValue(),+ ...item.getChildren().map((child) => child.getType()),+ ])+ : block.getType()+ )+ );+}++function caretItemIndex(editor: LexicalEditor) {+ return editor.read(() => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return null;+ const node = selection.anchor.getNode();+ return $isListItemNode(node) ? node.getIndexWithinParent() : null;+ });+}++describe('images in lists', () => {+ it('puts an image under the item the caret is in without splitting the list', () => {+ const editor = mountList(['first', 'second'], 0);++ expect(insertImage(editor)).toBe(true);++ expect(outline(editor)).toEqual([+ [+ [1, 'text', 'image'],+ [2, 'text'],+ ],+ ]);+ });++ it('attaches an image on the empty item Enter left to the item above, and a second Enter still leaves the list', () => {+ const editor = mountList(['first', ''], 1);++ expect(insertImage(editor)).toBe(true);++ expect(outline(editor)).toEqual([[[1, 'text', 'image'], [2]]]);+ expect(caretItemIndex(editor)).toBe(1);++ pressEnter(editor);++ expect(outline(editor)).toEqual([[[1, 'text', 'image']], 'paragraph']);+ });++ it('leaves an image outside a list when the caret is not in one', () => {+ const editor = mountList(['first'], 0);+ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ $getRoot().append(paragraph);+ paragraph.select();+ },+ { discrete: true }+ );++ expect(insertImage(editor)).toBe(false);+ });++ it('starts the next item below the images on Enter', () => {+ const editor = mountList(['first', 'second'], 0);+ insertImage(editor);++ pressEnter(editor);++ expect(outline(editor)).toEqual([[[1, 'text', 'image'], [2], [3, 'text']]]);+ expect(caretItemIndex(editor)).toBe(1);+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.tsnew file mode 100644index 0000000000..c4def3a002--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/listItemImages.ts@@ -0,0 +1,81 @@+import { $isListItemNode, type ListItemNode } from '@lexical/list';+import { $isImageNode, type ImageNode } from '@macro-inc/lexical-core';+import {+ $findMatchingParent,+ $getSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_NORMAL,+ INSERT_PARAGRAPH_COMMAND,+ type LexicalEditor,+} from 'lexical';++function $selectedListItem(): ListItemNode | null {+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return null;+ return $findMatchingParent(selection.anchor.getNode(), $isListItemNode);+}++/** The item whose text ends right above `item`: its previous sibling, or that sibling's last nested item. */+function $itemAbove(item: ListItemNode): ListItemNode | null {+ const previous = item.getPreviousSibling();+ if (!$isListItemNode(previous)) return null;+ const last = previous.getLastDescendant();+ if (!last) return previous;+ return $findMatchingParent(last, $isListItemNode);+}++/**+ * Inserts an image into the list the caret is in, under the current item,+ * without splitting the list. On the empty item Enter leaves after an item,+ * the image goes under the item above and the caret stays on the empty item,+ * so a second Enter leaves the list as usual and an image inserted then sits+ * below the list. Returns false when the caret is not in a list.+ */+export function $insertImageIntoListItem(image: ImageNode): boolean {+ const item = $selectedListItem();+ if (!item) return false;+ if (!item.isEmpty()) {+ item.append(image);+ return true;+ }+ const above = $itemAbove(item);+ if (!above) return false;+ above.append(image);+ return true;+}++function $trailingImages(item: ListItemNode): ImageNode[] {+ const images: ImageNode[] = [];+ let child = item.getLastChild();+ while (child && $isImageNode(child)) {+ images.unshift(child);+ child = child.getPreviousSibling();+ }+ return images;+}++/**+ * Enter in an item with images under it starts the next item below the+ * images, keeping them with the item they belong to. Lexical would otherwise+ * carry the images into the new item.+ */+function $insertParagraphAboveImages(): boolean {+ const item = $selectedListItem();+ if (!item) return false;+ const images = $trailingImages(item);+ if (images.length === 0) return false;+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return false;+ for (const image of images) image.remove();+ selection.insertParagraph();+ item.append(...images);+ return true;+}++export function registerListItemImages(editor: LexicalEditor) {+ return editor.registerCommand(+ INSERT_PARAGRAPH_COMMAND,+ $insertParagraphAboveImages,+ COMMAND_PRIORITY_NORMAL+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/mediaPlugin.tsindex b2144291be..bd1f31f38a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts@@ -46,6 +46,10 @@ import {import { ok, type Result, ResultAsync } from 'neverthrow';import { $insertNodesAndSplitList } from '../../utils';import { mapRegisterDelete } from '../shared';+import {+ $insertImageIntoListItem,+ registerListItemImages,+} from './listItemImages';type DSSMedia = {type: 'dss';@@ -258,6 +262,8 @@ function $safeInsertMediaNode(node: ImageNode | VideoNode) {return;}+ if ($isImageNode(node) && $insertImageIntoListItem(node)) return;+if ($isRangeSelection(selection)) {if (selection.isCollapsed()) {const { focus } = selection;@@ -394,6 +400,7 @@ function registerMediaPlugin(editor: LexicalEditor) {return mergeRegister(followCreated(ImageNode, 'image'),followCreated(VideoNode, 'video'),+ registerListItemImages(editor),editor.registerCommand(INSERT_MEDIA_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/fileUploadUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/fileUploadUtils.tsindex f1c72f717c..4f271cbab0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/fileUploadUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/fileUploadUtils.ts@@ -83,7 +83,12 @@ export const getDragDropPosition = (e: DragEvent | { clientX: number; clientY: number },setSelection = false) => {- const { key, position } = calculateInsertPoint(editor, e, DRAG_EVENT_PADDING);+ const { key, position } = calculateInsertPoint(+ editor,+ e,+ DRAG_EVENT_PADDING,+ true+ );if (setSelection && key !== null && position !== null) {editor.dispatchCommand(SET_SELECTION_AT_INSERTION, [key, position]);}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex 737a45668e..9178475534 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -36,5 +36,6 @@* Version 8.0 - Oct 2026. Added BookingLinkMentionNode for Macro `/app/book/…` URLs.* Version 9.0 - Oct 2026. Added AgentActivityNode: the steps of an agent's reply between two passages, with a snapshot of its rows and live rendering where the session is readable.* Version 9.1 - Oct 2026. Markdown m-link payloads preserve explicit unlinking; bare URLs import as links.+ * Version 9.2 - Nov 2026. ImageNode may be a child of ListItemNode; Markdown stores it as an indented line under its item.*/-export const MARKDOWN_VERSION_COUNTER = 9.1;+export const MARKDOWN_VERSION_COUNTER = 9.2;diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 33abad28ac..30d766690f 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -306,6 +306,19 @@ When an editor's selection spans two or more checklist items, the button reads**N tasks** and creates one task per item without opening the composer; eachitem is replaced by its task mention and a **Created N tasks** toast appears.+## Images in lists++An image inserted or dropped while the caret is in a list item goes under that+item's text, left-aligned with it, and stays resizable; the list is not split+and numbered items keep counting. On the empty item Enter leaves after an item,+the image goes under the item above and the caret stays on the empty item;+pressing Enter again leaves the list, and an image inserted then sits below it.+Enter at the end of an item's text starts the next item below its images.+Dropped files target the item under the pointer's lower half, or the item+above. Markdown saves the image as an indented line under its item. Verify+with `list-images.browser.e2e.ts` in+`apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test`.+## Markdown outlineOn desktop, Markdown documents with at least three headings show a tick rail indiff --git a/packages/lexical-core/AGENTS.md b/packages/lexical-core/AGENTS.mdindex 2eeb9fa321..17ff48a6d1 100644--- a/packages/lexical-core/AGENTS.md+++ b/packages/lexical-core/AGENTS.md@@ -31,3 +31,9 @@ composer imports the URL matcher from this package; do not duplicate it.Keep URLs protected from inline formatting during import; matching renderedtext is too late. Preserve code, mention payloads, existing links, and escapedliteral URLs. Keep unlink state through both Markdown and Lexical JSON saves.++An image under a list item is a child of that `ListItemNode`. Lexical runs+element transformers only on top-level nodes, so `listItemImage` exports it as+an indented line, and the image importers attach an indented image line after a+list to its last item. Add it to any new transformer set that has image+transformers.diff --git a/packages/lexical-core/tests/list-images.test.ts b/packages/lexical-core/tests/list-images.test.tsnew file mode 100644index 0000000000..285d9d6291--- /dev/null+++ b/packages/lexical-core/tests/list-images.test.ts@@ -0,0 +1,93 @@+import { $isListItemNode, $isListNode } from '@lexical/list';+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+ type Transformer,+} from '@lexical/markdown';+import { $getRoot, createEditor } from 'lexical';+import { describe, expect, it } from 'vitest';+import { SupportedNodeTypes } from '../node-list';+import { $isImageNode } from '../nodes/ImageNode';+import { EXTERNAL_TRANSFORMERS, INTERNAL_TRANSFORMERS } from '../transformers';++function roundTrip(markdown: string, transformers: Transformer[]) {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError: (error) => {+ throw error;+ },+ });+ editor.update(+ () => {+ $convertFromMarkdownString(markdown, transformers);+ },+ { discrete: true }+ );+ return editor.getEditorState().read(() => {+ const root = $getRoot();+ const list = root.getFirstChild();+ const items = $isListNode(list) ? list.getChildren() : [];+ return {+ topLevelTypes: root.getChildren().map((node) => node.getType()),+ itemChildTypes: items.map((item) =>+ $isListItemNode(item)+ ? item.getChildren().map((child) => child.getType())+ : []+ ),+ values: items.map((item) =>+ $isListItemNode(item) ? item.getValue() : 0+ ),+ imageUrls: items.map((item) =>+ $isListItemNode(item)+ ? item+ .getChildren()+ .filter($isImageNode)+ .map((image) => image.getUrl())+ : []+ ),+ markdown: $convertToMarkdownString(transformers),+ };+ });+}++describe('images inside list items', () => {+ it('keeps a numbered list in one list with its numbering', () => {+ const markdown = [+ '1. first',+ ' ',+ '2. second',+ ].join('\n');++ const result = roundTrip(markdown, EXTERNAL_TRANSFORMERS);++ expect(result.topLevelTypes).toEqual(['list']);+ expect(result.itemChildTypes).toEqual([['text', 'image'], ['text']]);+ expect(result.values).toEqual([1, 2]);+ expect(result.imageUrls).toEqual([['https://example.com/a.png'], []]);+ expect(result.markdown).toBe(markdown);+ });++ it('round-trips a resized image under a nested bullet', () => {+ const image =+ '<m-image>{"url":"https://example.com/b.png","alt":"","srcType":"sfs","id":"b","width":800,"height":600,"scale":1,"constrainedWidth":200}</m-image>';+ const markdown = ['- outer', ' - inner', ` ${image}`, '- next'].join(+ '\n'+ );++ const result = roundTrip(markdown, INTERNAL_TRANSFORMERS);++ expect(result.topLevelTypes).toEqual(['list']);+ expect(result.markdown).toBe(markdown);+ });++ it('keeps an unindented image after a list outside the list', () => {+ const markdown = ['- item', ''].join(+ '\n'+ );++ const result = roundTrip(markdown, EXTERNAL_TRANSFORMERS);++ expect(result.topLevelTypes).toEqual(['list', 'image']);+ expect(result.itemChildTypes).toEqual([['text']]);+ });+});diff --git a/packages/lexical-core/transformers/image.ts b/packages/lexical-core/transformers/image.tsindex a5511c0843..fde9b9c124 100644--- a/packages/lexical-core/transformers/image.ts+++ b/packages/lexical-core/transformers/image.ts@@ -1,5 +1,13 @@-import type { ElementTransformer } from '@lexical/markdown';-import type { ElementNode, LexicalNode } from 'lexical';+import { $isListItemNode, $isListNode, ListItemNode } from '@lexical/list';+import type {+ ElementTransformer,+ TextMatchTransformer,+} from '@lexical/markdown';+import {+ $findMatchingParent,+ type ElementNode,+ type LexicalNode,+} from 'lexical';import { $createImageNode, $isImageNode, ImageNode } from '../nodes/ImageNode';import {replaceElementWithUnknownMention,@@ -10,7 +18,7 @@ import {export const I_IMAGE_CONSTRAINED: ElementTransformer = {dependencies: [ImageNode, UnknownMentionNode],type: 'element',- regExp: /^<m-image>(.*?)<\/m-image>\s*$/,+ regExp: /^\s*<m-image>(.*?)<\/m-image>\s*$/,export: (node: LexicalNode) => {if (!$isImageNode(node)) return null;if (node.getSrcType() === 'local') return null;@@ -36,7 +44,7 @@ export const I_IMAGE_CONSTRAINED: ElementTransformer = {return `<m-image>${data}</m-image>`;},- replace: (parent: ElementNode, _, match: string[]) => {+ replace: (parent: ElementNode, _, match: string[], isImport: boolean) => {try {const data = JSON.parse(match[1] ?? '');if (!data.url) throw new Error('Missing url field');@@ -52,6 +60,9 @@ export const I_IMAGE_CONSTRAINED: ElementTransformer = {constrainedWidth: data.constrainedWidth ?? undefined,constrainedHeight: data.constrainedHeight ?? undefined,});+ if (isImport && $appendToPrecedingListItem(parent, imageNode, match)) {+ return;+ }parent.replace(imageNode);} catch (e) {console.error('Failed to parse m-image:', e);@@ -74,7 +85,7 @@ export const IMAGE: ElementTransformer = {return ``;},regExp: /!\[([^\]]*)\]\(([^)\s]+)(?:\s"([^"]*)"\s*)?\)$/,- replace: (node, _, match) => {+ replace: (node, _, match, isImport) => {const [, altText, imageUrl] = match;const imageNode = $createImageNode({srcType: 'url',@@ -84,6 +95,82 @@ export const IMAGE: ElementTransformer = {height: 0,id: '',});+ if (isImport && $appendToPrecedingListItem(node, imageNode, match)) return;node.replace(imageNode);},};++/**+ * An image line indented under a list belongs to the list item above it, as+ * {@link listItemImage} exports it. Moves the image into that item and drops+ * the line's paragraph, so the list stays one list.+ */+function $appendToPrecedingListItem(+ paragraph: ElementNode,+ image: ImageNode,+ match: string[]+): boolean {+ // Lexical passes the RegExp match, which keeps the whole line.+ if (!('input' in match) || typeof match.input !== 'string') return false;+ const line = match.input;+ const imageStart = line.length - line.trimStart().length;+ if (imageStart === 0 || imageStart !== line.indexOf(match[0].trimStart())) {+ return false;+ }+ const list = paragraph.getPreviousSibling();+ if (!$isListNode(list)) return false;+ const lastDescendant = list.getLastDescendant();+ const item = lastDescendant+ ? $findMatchingParent(lastDescendant, $isListItemNode)+ : list.getLastChild();+ if (!$isListItemNode(item)) return false;+ item.append(image);+ paragraph.remove();+ return true;+}++/**+ * Exports an image inside a list item on its own line, indented to the item's+ * text, so Markdown keeps it in the item and the list unbroken. Lexical runs+ * element transformers only on top-level nodes, so list children need a+ * text-match export.+ */+export function listItemImage(+ ...imageTransformers: ElementTransformer[]+): TextMatchTransformer {+ return {+ dependencies: [ImageNode, ListItemNode],+ type: 'text-match',+ regExp: /$^/,+ export: (node) => {+ if (!$isImageNode(node)) return null;+ const item = node.getParent();+ if (!$isListItemNode(item)) return null;+ for (const transformer of imageTransformers) {+ const markdown = transformer.export?.(node, () => '');+ if (markdown != null) {+ return `\n${' '.repeat(listItemTextIndent(item))}${markdown}`;+ }+ }+ return null;+ },+ };+}++// Lexical's list export indents each nesting level by this many spaces.+const LIST_INDENT_SIZE = 2;++/** Columns before a list item's text in Lexical's list export. */+function listItemTextIndent(item: ListItemNode): number {+ const list = item.getParent();+ if (!$isListNode(list)) return 0;+ let depth = 0;+ let ancestor = list.getParent();+ while ($isListItemNode(ancestor)) {+ depth++;+ ancestor = ancestor.getParent()?.getParent() ?? null;+ }+ const marker =+ list.getListType() === 'number' ? `${item.getValue()}. ` : '- ';+ return depth * LIST_INDENT_SIZE + marker.length;+}diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex 0781d9de50..be446e17e8 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -8,7 +8,7 @@ import { I_CURSOR_SYSTEM_NOTIFICATION } from './cursorSystemNotification';import { CUSTOM_TRANSFORMERS } from './customTransformers';import { I_DATABASE_QUERY, I_DATABASE_QUERY_BLOCK } from './databaseQuery';import { I_HTML_RENDER } from './htmlRender';-import { I_IMAGE_CONSTRAINED, IMAGE } from './image';+import { I_IMAGE_CONSTRAINED, IMAGE, listItemImage } from './image';import {E_BLOCK_EQUATION_NODE,E_INLINE_EQUATION_NODE,@@ -83,6 +83,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [I_VIDEO,I_IMAGE_CONSTRAINED,IMAGE, // Standard markdown images (fallback)+ listItemImage(I_IMAGE_CONSTRAINED, IMAGE),I_USER_MENTION,I_GROUP_MENTION,I_DOCUMENT_MENTION,@@ -125,6 +126,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [VIDEO_LINK,I_VIDEO,IMAGE,+ listItemImage(IMAGE),BR_TAG_TO_LINE_BREAK,E_TABLE_NODE,HTML_BLOCKQUOTE,@@ -178,6 +180,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [I_VIDEO,I_IMAGE_CONSTRAINED,IMAGE,+ listItemImage(I_IMAGE_CONSTRAINED, IMAGE),BR_TAG_TO_LINE_BREAK,I_TABLE_NODE,E_TABLE_NODE,