diff --git a/docs/buzz-help.md b/docs/buzz-help.md
index 20e02c0384..a11e41e5f8 100644
--- a/docs/buzz-help.md
+++ b/docs/buzz-help.md
@@ -355,7 +355,8 @@ Conflicting edits preserve the draft until you reconcile the newer revision.
Doc references open beside the conversation, with normal Back/Forward and tab
close behavior. Choose **Open in Docs** from the tab’s context menu or Doc
actions to see the same doc in the main Docs view. Tables display as grids in
-Viewing and formatted Editing. Use Markdown source to change table cells.
+Viewing and formatted Editing. HTTPS Markdown images display inline in both modes.
+Use Markdown source to edit image URLs, alt text, and table cells.
Agents can call `doc_help`, create and verify a Doc,
post its returned reference, then update the same document on follow-ups. The execution
host must have Docs enabled. Saving requires relay support for NIP-AR doc
diff --git a/src/bundled/docs/DocDialogs.tsx b/src/bundled/docs/DocDialogs.tsx
index 956baf945a..b3a2b2cabe 100644
--- a/src/bundled/docs/DocDialogs.tsx
+++ b/src/bundled/docs/DocDialogs.tsx
@@ -279,6 +279,7 @@ export function DocRevisionPreview({
) : (
diff --git a/src/bundled/docs/DocDocument.test.tsx b/src/bundled/docs/DocDocument.test.tsx
index 350def8694..f66d5582d2 100644
--- a/src/bundled/docs/DocDocument.test.tsx
+++ b/src/bundled/docs/DocDocument.test.tsx
@@ -719,6 +719,43 @@ it("keeps formatted Buzz conversation links and Page navigation through the shar
}
});
+it("shows HTTPS images in a saved doc and while editing its Markdown", async () => {
+ const remote = "https://images.example/diagram.png";
+ const proxy = "https://media.example/authorized.png";
+ const f = await workspaceFixture(undefined, (session) => ({
+ ...session,
+ media: (url) => (url === remote ? url : proxy),
+ }));
+ const media = `${f.origin}/media/${"a".repeat(64)}.png`;
+ const report = "https://example.com/report";
+ const markdown = `[](${report})\n\n![Relay image][relay]\n\n\n\n[relay]: ${media}`;
+ const doc = f.seed("Images", markdown);
+ const props = { address: doc, workspace: f.workspace, onOpen: vi.fn() };
+ const view = render();
+
+ expect(await screen.findByRole("img", { name: "Diagram" })).toHaveAttribute(
+ "src",
+ remote,
+ );
+ expect(screen.getByRole("link", { name: "Diagram" })).toHaveAttribute(
+ "href",
+ report,
+ );
+ expect(screen.getByRole("img", { name: "Relay image" })).toHaveAttribute(
+ "src",
+ proxy,
+ );
+ expect(screen.getByText("Unsafe")).toBeVisible();
+ expect(screen.queryByRole("img", { name: "Unsafe" })).toBeNull();
+
+ view.rerender();
+ const editor = screen.getByRole("textbox", { name: "Doc body" });
+ expect(within(editor).getByRole("img", { name: "Diagram" })).toBeVisible();
+ expect(
+ within(editor).getByRole("img", { name: "Relay image" }),
+ ).toBeVisible();
+});
+
it("does not let an older head replace a newer one after a slow authority read", async () => {
const f = await fixture();
const older = await f.edit(f.viewer, f.doc, {
diff --git a/src/bundled/docs/DocDocument.tsx b/src/bundled/docs/DocDocument.tsx
index bd1018df18..0586d12da7 100644
--- a/src/bundled/docs/DocDocument.tsx
+++ b/src/bundled/docs/DocDocument.tsx
@@ -887,6 +887,7 @@ export function DocDocument({
>
) {
+export function DocEditor({
+ session,
+ ...props
+}: Omit & {
+ session: RelaySession;
+}) {
const Editor = useDocsUi().conversation.DocumentEditor;
+ const images = useMemo(() => ({ session }), [session]);
return (
diff --git a/src/bundled/docs/DocMarkdown.tsx b/src/bundled/docs/DocMarkdown.tsx
index 576c90cfe0..ff10a31a36 100644
--- a/src/bundled/docs/DocMarkdown.tsx
+++ b/src/bundled/docs/DocMarkdown.tsx
@@ -22,6 +22,7 @@ export function DocMarkdown({
{
const doc = parseDocUrl(url);
diff --git a/src/bundled/docs/NewDocDocument.tsx b/src/bundled/docs/NewDocDocument.tsx
index 508d78497b..fa265038fc 100644
--- a/src/bundled/docs/NewDocDocument.tsx
+++ b/src/bundled/docs/NewDocDocument.tsx
@@ -285,6 +285,7 @@ export function NewDocDocument({
boolean) | undefined;
session?: RelaySession | undefined;
+ /** Enables HTTPS images, using the session for authenticated relay media. */
+ images?: MarkdownImageOptions | undefined;
/** Plugin code-block renderers; without them blocks stay plain. */
codeBlocks?: ContributionReader | undefined;
/** A copy action on code blocks. */
copy?: boolean | undefined;
}>;
+export type MarkdownImageOptions = {
+ session?: Pick | undefined;
+};
+
+export function MarkdownImage({
+ src,
+ alt,
+ title,
+ images,
+}: {
+ src?: string | undefined;
+ alt?: string | undefined;
+ title?: string | undefined;
+ images?: MarkdownImageOptions | undefined;
+}) {
+ const safe = images && src ? safeMessageUrl(src) : undefined;
+ const source = safe && (images?.session ? images.session.media(safe) : safe);
+ return source ? (
+
+ ) : alt ? (
+ {alt}
+ ) : null;
+}
+
const CapabilitiesContext = createContext({});
const SCALES: Record = {
@@ -82,8 +118,17 @@ export const sharedComponents: Components = {
);
},
- img: ({ alt }) =>
- alt ? {alt} : null,
+ img: function SharedImage({ src, alt, title }) {
+ const { images } = useContext(CapabilitiesContext);
+ return (
+
+ );
+ },
pre: function SharedCode(props) {
const { codeBlocks, copy } = useContext(CapabilitiesContext);
return ;
diff --git a/src/features/messages/DocumentEditor.test.tsx b/src/features/messages/DocumentEditor.test.tsx
index 41fbe19e70..6d7cae0881 100644
--- a/src/features/messages/DocumentEditor.test.tsx
+++ b/src/features/messages/DocumentEditor.test.tsx
@@ -540,6 +540,35 @@ function replaceMarkdown(h: ReturnType, value: string) {
return richInput();
}
+it("previews typed and pasted images while retaining their Markdown source", async () => {
+ const markdown = "";
+ const images = {};
+ const h = mount({ images }, { initialValue: "" });
+ act(() => h.ref.current?.focusEnd());
+ await userEvent.setup().keyboard(markdown.replace("[", "[["));
+ expect(screen.getByRole("img", { name: "Chart" })).toBeVisible();
+ expect(h.change).toHaveBeenLastCalledWith(markdown);
+
+ const copied = copySelection(richInput());
+ expect(copied.text).toBe(markdown);
+ for (const html of ["", copied.html]) {
+ h.rerender({ source: true, images });
+ fireEvent.change(screen.getByRole("textbox", { name: "Markdown" }), {
+ target: { value: "Before:" },
+ });
+ h.rerender({ source: false, images });
+ act(() => h.ref.current?.focusEnd());
+ pasteDocument(richInput(), copied.text, html);
+ expect(screen.getByRole("img", { name: "Chart" })).toBeVisible();
+ expect(h.change).toHaveBeenLastCalledWith(`Before:${markdown}`);
+ }
+
+ h.rerender({ source: true, images });
+ expect(screen.getByRole("textbox", { name: "Markdown" })).toHaveValue(
+ `Before:${markdown}`,
+ );
+});
+
const clipboardTree = (value: unknown): unknown =>
Array.isArray(value)
? value.map(clipboardTree)
diff --git a/src/features/messages/DocumentEditor.tsx b/src/features/messages/DocumentEditor.tsx
index 2f250ae505..4c242b3a6d 100644
--- a/src/features/messages/DocumentEditor.tsx
+++ b/src/features/messages/DocumentEditor.tsx
@@ -30,6 +30,7 @@ import {
documentEditorMarkdown,
} from "./document-editor-markdown";
import { MAX_MARKDOWN_LENGTH } from "../relay/message-content";
+import type { MarkdownImageOptions } from "../markdown/MarkdownDocument";
import markdownStyles from "../markdown/Markdown.module.css";
import styles from "./DocumentEditor.module.css";
@@ -127,6 +128,8 @@ export type DocumentEditorProps = {
ref?: Ref;
value: string;
editing: boolean;
+ /** Enables inline previews for image Markdown in formatted editing. */
+ images?: MarkdownImageOptions | undefined;
children?: ReactNode;
onChange(value: string): void;
disabled?: boolean;
@@ -177,9 +180,13 @@ function DocumentFormattingToolbar({
);
}
-function documentContent(value: string, field: boolean) {
- const draft = documentEditorDraft(value);
- return { draft, literal: field && documentEditorMarkdown(draft) !== value };
+function documentContent(value: string, field: boolean, renderImages: boolean) {
+ const draft = documentEditorDraft(value, renderImages);
+ return {
+ draft,
+ renderImages,
+ literal: field && documentEditorMarkdown(draft) !== value,
+ };
}
/** A document body using the composer's editing engine, without chat behavior. */
@@ -187,6 +194,7 @@ export function DocumentEditor({
ref,
value,
editing,
+ images,
children,
onChange,
disabled = false,
@@ -205,8 +213,11 @@ export function DocumentEditor({
onSourceChange,
}: DocumentEditorProps) {
const field = variant === "field";
- const [content, setContent] = useState(() => documentContent(value, field));
+ const [content, setContent] = useState(() =>
+ documentContent(value, field, !!images),
+ );
const { draft, literal } = content;
+ const renderImages = !!images;
const source = sourceMode || literal;
const [localLinkOpen, setLocalLinkOpen] = useState(false);
const linkOpen = controlledLinkOpen ?? localLinkOpen;
@@ -276,6 +287,13 @@ export function DocumentEditor({
useLayoutEffect(() => {
syncing.current = false;
if (sourceMode) return;
+ if (content.renderImages !== renderImages) {
+ accepted.current = undefined;
+ emitted.current = value;
+ syncing.current = true;
+ setContent(documentContent(value, field, renderImages));
+ return;
+ }
if (value === emitted.current) {
rememberAccepted();
return;
@@ -287,8 +305,8 @@ export function DocumentEditor({
// Restore the accepted document, selection and undo state without an edit
// transaction that could normalize Markdown or notify the plugin again.
previous.restore();
- setContent({ draft: previous.draft, literal: false });
- } else setContent(documentContent(value, field));
+ setContent({ ...content, draft: previous.draft, literal: false });
+ } else setContent(documentContent(value, field, renderImages));
});
useLayoutEffect(() => {
// The engine emits native select events even when formatting is unchanged.
@@ -425,11 +443,12 @@ export function DocumentEditor({
aria-invalid={invalid || undefined}
maxLength={Math.min(maxLength, MAX_MARKDOWN_LENGTH)}
markdownMode="document"
+ images={editing ? images : undefined}
preservePlainTextLineBreaks={field}
decorationsFor={noDecorations}
onDraftChange={(next) => {
if (syncing.current) return;
- setContent({ draft: next, literal: false });
+ setContent({ draft: next, literal: false, renderImages });
const markdown = documentEditorMarkdown(next);
if (markdown !== value) {
emitted.current = markdown;
diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx
index 729556391a..180084caee 100644
--- a/src/features/messages/EditableInput.tsx
+++ b/src/features/messages/EditableInput.tsx
@@ -93,6 +93,7 @@ import {
plainChatLength,
} from "./composer-markdown";
import {
+ applyDocumentImageInput,
documentEditorDraft,
documentEditorMarkdown,
} from "./document-editor-markdown";
@@ -102,8 +103,10 @@ import {
} from "../markdown/document-profile";
import {
MarkdownDocument,
+ MarkdownImage,
MarkdownTable,
sharedComponents,
+ type MarkdownImageOptions,
} from "../markdown/MarkdownDocument";
import {
annotationAt,
@@ -436,14 +439,17 @@ const tableComponents: typeof sharedComponents = {
};
const DocumentTable = memo(function DocumentTable({
source,
+ images,
}: {
source: string;
+ images: MarkdownImageOptions | undefined;
}) {
return (
);
@@ -460,6 +466,7 @@ export function EditableInput({
placeholder,
maxLength,
markdownMode = "chat",
+ images,
preservePlainTextLineBreaks = false,
onDraftChange,
onFormatsChange,
@@ -473,6 +480,7 @@ export function EditableInput({
...events
}: EditableInputProps & {
draft: MentionDraft;
+ images?: MarkdownImageOptions | undefined;
decorationsFor(draft: MentionDraft): readonly EditorDecoration[];
}) {
const serializeDraft =
@@ -486,6 +494,7 @@ export function EditableInput({
decorationsFor,
maxLength,
markdownMode,
+ images,
preservePlainTextLineBreaks,
serializeDraft,
onDraftChange,
@@ -507,6 +516,7 @@ export function EditableInput({
decorationsFor,
maxLength,
markdownMode,
+ images,
preservePlainTextLineBreaks,
serializeDraft,
onDraftChange,
@@ -543,6 +553,9 @@ export function EditableInput({
const tableHosts = useRef(
new Map(),
);
+ const imageHosts = useRef(
+ new Map(),
+ );
const scrollAfterTokens = useRef(false);
const composing = useRef(false);
/** Pending-chip settles and extensions that landed during an IME
@@ -1826,8 +1839,16 @@ export function EditableInput({
}
if (!sourceLink)
text = source.draft.text.slice(source.source(from), source.source(to));
+ // Image links are authored in source mode. Treating a preview as a
+ // text label would escape the syntax and replace the image.
+ let containsImage = false;
+ doc.nodesBetween(from, to, (node) => {
+ if (node.type === composerSchema.nodes.markdown_image)
+ containsImage = true;
+ });
// Inline code is literal, not a nested hyperlink. Block syntax stays source.
if (
+ containsImage ||
source.blocks.some(
(block) => block.code && from < block.to && to > block.from,
) ||
@@ -2344,6 +2365,21 @@ export function EditableInput({
},
};
},
+ markdown_image(node, view) {
+ const dom = view.dom.ownerDocument.createElement("span");
+ dom.contentEditable = "false";
+ dom.dataset.source = node.attrs.source;
+ imageHosts.current.set(dom, { key: ++tokenHosts, node });
+ tokenViews();
+ return {
+ dom,
+ ignoreMutation: (mutation) => mutation.type !== "selection",
+ destroy() {
+ imageHosts.current.delete(dom);
+ tokenViews();
+ },
+ };
+ },
// Tokens also come and go in transactions the normalizer appends,
// which report no change of their own; render each new host's artwork.
token(node, _view, getPos) {
@@ -2432,7 +2468,8 @@ export function EditableInput({
!markdownAsTyped() &&
(composerFenceDelimiters.has(text) ||
composerPrefixDelimiters.has(text) ||
- composerInlineDelimiters.has(text)) &&
+ composerInlineDelimiters.has(text) ||
+ (text === ")" && current.current.images)) &&
!composing.current &&
!editor.composing &&
editor.state !== previous
@@ -2445,7 +2482,12 @@ export function EditableInput({
current.current.markdownMode,
);
const conversion = block ?? editor.state.tr;
- if (block || applyComposerInlineInput(conversion, text)) {
+ if (
+ block ||
+ (text === ")"
+ ? applyDocumentImageInput(conversion)
+ : applyComposerInlineInput(conversion, text))
+ ) {
const unconverted = editor.state;
editor.dispatch(closeHistory(conversion).scrollIntoView());
// Generated delimiters or escapes in the serialized form can
@@ -2771,13 +2813,18 @@ export function EditableInput({
!!plain || event.clipboardData?.types?.includes("text/plain");
const copy = code
? undefined
- : buzzCopyDocument(html, current.current.markdownMode);
+ : buzzCopyDocument(
+ html,
+ current.current.markdownMode,
+ !!current.current.images,
+ );
// Unformatted prose takes the text path: it inherits the caret's
// marks and the link spacing below. Structure pastes as nodes.
const paragraph = copy?.childCount === 1 ? copy.firstChild : null;
const prose =
paragraph?.type === composerSchema.nodes.paragraph &&
paragraph.childCount <= 1 &&
+ (paragraph.firstChild?.isText ?? true) &&
!paragraph.firstChild?.marks.length
? paragraph.textContent
: undefined;
@@ -2871,7 +2918,10 @@ export function EditableInput({
current.current.markdownMode === "document" &&
value.trim()
) {
- const draft = documentEditorDraft(value);
+ const draft = documentEditorDraft(
+ value,
+ !!current.current.images,
+ );
if (draft.document) {
const parsed = readComposerDocument(draft, [], "document");
const paragraph =
@@ -2881,6 +2931,7 @@ export function EditableInput({
if (
paragraph?.type === composerSchema.nodes.paragraph &&
paragraph.childCount <= 1 &&
+ (paragraph.firstChild?.isText ?? true) &&
!paragraph.firstChild?.marks.length
)
return !!insertPastedText(
@@ -3463,11 +3514,27 @@ export function EditableInput({
/>
{[...tableHosts.current].map(([element, { key, source }]) =>
createPortal(
- ,
+ ,
element,
`table-${key}`,
),
)}
+ {[...imageHosts.current].map(([element, { key, node }]) =>
+ createPortal(
+ images && !composerSchema.marks.code.isInSet(node.marks) ? (
+
+ ) : (
+ node.attrs.source
+ ),
+ element,
+ `image-${key}`,
+ ),
+ )}
{[...hosts.current].map(([element, host]) => {
const position = host.position();
const source =
diff --git a/src/features/messages/PluginMarkdown.tsx b/src/features/messages/PluginMarkdown.tsx
index f3bfd5be6a..92839e3b25 100644
--- a/src/features/messages/PluginMarkdown.tsx
+++ b/src/features/messages/PluginMarkdown.tsx
@@ -7,6 +7,7 @@ import {
MarkdownDocument,
MarkdownSource,
sharedComponents,
+ type MarkdownImageOptions,
} from "../markdown/MarkdownDocument";
import { buzzLinkTarget } from "../navigation/buzz-links";
import type { Navigation } from "../navigation/controller";
@@ -18,6 +19,8 @@ import { openFromPanel, PanelPane } from "../panels/opening-pane";
export type MarkdownProps = {
content: string;
session?: RelaySession | undefined;
+ /** Enables HTTPS images for this document. */
+ images?: MarkdownImageOptions | undefined;
/** Heading roles: message by default, document for a page's hierarchy. */
scale?: "message" | "document" | undefined;
/** True handles the link locally; false falls through to the host. */
@@ -28,6 +31,7 @@ export type MarkdownProps = {
export function PluginMarkdown({
content,
session,
+ images,
scale = "message",
openLink,
navigation,
@@ -45,6 +49,7 @@ export function PluginMarkdown({
scale={scale}
capabilities={{
session,
+ images,
openLink: (url) => {
if (openLink?.(url)) return true;
const scope = session?.viewer
diff --git a/src/features/messages/composer-clipboard.ts b/src/features/messages/composer-clipboard.ts
index 41dfd3049c..08c33982c7 100644
--- a/src/features/messages/composer-clipboard.ts
+++ b/src/features/messages/composer-clipboard.ts
@@ -158,6 +158,11 @@ export function composerClipboard(
{
...serializer.nodes,
heading: (node) => [`h${node.attrs.level}`, 0],
+ markdown_image: (node) => [
+ "span",
+ { "data-source": node.attrs.source },
+ node.attrs.source,
+ ],
markdown_table: (node) => ["p", node.attrs.source],
bullet_list: (node) => ["ul", spread(node), 0],
ordered_list: (node) => [
@@ -219,22 +224,44 @@ export function composerClipboard(
export function buzzCopyDocument(
html: string,
mode: ComposerMarkdownMode = "chat",
+ renderImages = false,
): EditorNode | undefined {
if (!html.includes("data-buzz-copy")) return;
const copy = new DOMParser()
.parseFromString(html, "text/html")
.querySelector("[data-buzz-copy]");
return (
- (copy && sourced(copyDocument(copy, undefined, mode), mode)) ?? undefined
+ (copy &&
+ sourced(copyDocument(copy, undefined, mode), mode, renderImages)) ??
+ undefined
);
}
function sourced(
node: EditorNode,
mode: ComposerMarkdownMode,
+ renderImages: boolean,
): EditorNode | null {
if (node.isText || (mode === "document" && node.type.name === "hard_break"))
return node;
+ if (
+ mode === "document" &&
+ renderImages &&
+ node.type === composerSchema.nodes.token &&
+ node.textContent.includes("![")
+ ) {
+ const parsed = readComposerSnapshot(
+ documentEditorDraft(node.textContent, true).document,
+ mode,
+ );
+ const paragraph = parsed?.childCount === 1 ? parsed.firstChild : null;
+ const image = paragraph?.childCount === 1 ? paragraph.firstChild : null;
+ if (
+ image?.type === composerSchema.nodes.markdown_image &&
+ image.attrs.source === node.textContent
+ )
+ return image.mark(node.marks);
+ }
const first = node.firstChild;
if (
mode === "document" &&
@@ -260,7 +287,9 @@ function sourced(
: null;
return node.copy(
Fragment.fromArray(
- node.content.content.flatMap((child) => sourced(child, mode) ?? []),
+ node.content.content.flatMap(
+ (child) => sourced(child, mode, renderImages) ?? [],
+ ),
),
);
}
diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts
index b860c5bea2..e6853b06d6 100644
--- a/src/features/messages/composer-document.ts
+++ b/src/features/messages/composer-document.ts
@@ -28,6 +28,7 @@ export const composerSchema = new Schema<
| "blockquote"
| "code_block"
| "markdown_table"
+ | "markdown_image"
| "bullet_list"
| "ordered_list"
| "list_item"
@@ -110,6 +111,23 @@ export const composerSchema = new Schema<
leafText: (node) => node.attrs.source,
toDOM: (node) => ["div", { contenteditable: "false" }, node.attrs.source],
},
+ markdown_image: {
+ group: "inline",
+ inline: true,
+ atom: true,
+ attrs: {
+ source: { validate: "string" },
+ url: { validate: "string" },
+ alt: { validate: "string" },
+ title: { default: null, validate: "string|null" },
+ },
+ leafText: (node) => node.attrs.source,
+ toDOM: (node) => [
+ "span",
+ { contenteditable: "false" },
+ node.attrs.source,
+ ],
+ },
bullet_list: {
...bulletList,
attrs: {
@@ -632,10 +650,11 @@ export function composerMarkdownContext(
return false;
}
if (
- node.isInline &&
- (["code", "link", "literal"] as const).some((name) =>
- composerSchema.marks[name].isInSet(node.marks),
- )
+ node.type.name === "markdown_image" ||
+ (node.isInline &&
+ (["code", "link", "literal"] as const).some((name) =>
+ composerSchema.marks[name].isInSet(node.marks),
+ ))
)
mask(position, position + node.nodeSize);
});
@@ -689,14 +708,20 @@ function read(
return;
if (
mode === "chat" &&
- (node.type === "heading" || node.type === "markdown_table")
+ (node.type === "heading" ||
+ node.type === "markdown_table" ||
+ node.type === "markdown_image")
)
return;
if (node.type === "text") {
if (typeof node.text !== "string") return;
length += node.text.length;
}
- if (node.type === "token" || node.type === "markdown_table") {
+ if (
+ node.type === "token" ||
+ node.type === "markdown_table" ||
+ node.type === "markdown_image"
+ ) {
if (
!node.attrs ||
typeof node.attrs !== "object" ||
diff --git a/src/features/messages/document-editor-markdown.ts b/src/features/messages/document-editor-markdown.ts
index 37e793cf6b..5a2a416d1f 100644
--- a/src/features/messages/document-editor-markdown.ts
+++ b/src/features/messages/document-editor-markdown.ts
@@ -5,21 +5,28 @@ import { gfmTable } from "micromark-extension-gfm-table";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import type { Mark, Node as EditorNode } from "prosemirror-model";
import type { RootContent } from "mdast";
+import { TextSelection, type Transaction } from "prosemirror-state";
import {
+ composerMarkdownContext,
composerSchema as schema,
projectComposerDocument,
+ readComposerSnapshot,
} from "./composer-document";
import { composerLinkUrl } from "./composer-link";
import { mentionDraft, type MentionDraft } from "./mention-draft";
import { composerMarkdown } from "./composer-markdown";
-import { MAX_MARKDOWN_LENGTH, scanMarkdown } from "../relay/message-content";
+import {
+ MAX_MARKDOWN_LENGTH,
+ safeMessageUrl,
+ scanMarkdown,
+} from "../relay/message-content";
import { fitsDocumentRenderBudget } from "../markdown/document-profile";
/** Use the existing editor schema; unsupported syntax remains editable source. */
-export function documentEditorDraft(markdown: string) {
+export function documentEditorDraft(markdown: string, renderImages = false) {
if (markdown.length > MAX_MARKDOWN_LENGTH) return mentionDraft(markdown);
const scan = scanMarkdown(markdown);
- const { tooDeep } = scan;
+ const { definitions, tooDeep } = scan;
if (tooDeep) return mentionDraft(markdown);
const tree = fromMarkdown(markdown, {
extensions: [gfmStrikethrough(), gfmTable()],
@@ -58,6 +65,35 @@ export function documentEditorDraft(markdown: string) {
: text(node.value, [schema.marks.code.create()]);
if (node.type === "break")
return [schema.nodes.hard_break.create(null, null, marks)];
+ if (renderImages) {
+ // The editor keeps the whole link when it wraps a single image.
+ const image =
+ (node.type === "link" || node.type === "linkReference") &&
+ node.children.length === 1
+ ? node.children[0]
+ : node;
+ if (image?.type === "image" || image?.type === "imageReference") {
+ const source = raw(node);
+ const url = safeMessageUrl(
+ image.type === "image"
+ ? image.url
+ : (definitions.get(image.identifier.toLowerCase()) ?? ""),
+ );
+ if (url && !/[\r\n]/.test(source))
+ return [
+ schema.nodes.markdown_image.create(
+ {
+ source,
+ url,
+ alt: image.alt ?? "",
+ title: image.type === "image" ? image.title : null,
+ },
+ null,
+ marks,
+ ),
+ ];
+ }
+ }
const mark =
node.type === "strong"
? schema.marks.bold
@@ -169,6 +205,39 @@ export function documentEditorDraft(markdown: string) {
return projectComposerDocument(doc).draft;
}
+/** Preview the image just completed in formatted editing. */
+export function applyDocumentImageInput(tr: Transaction) {
+ const { $from, empty } = tr.selection;
+ const before = $from.nodeBefore;
+ if (!empty || $from.parent.type.spec.code || !before?.text?.includes("!["))
+ return false;
+
+ const projection = projectComposerDocument(tr.doc);
+ const context = composerMarkdownContext(tr.doc, projection);
+ const end = projection.source($from.pos);
+ const minimum = end - before.text.length;
+ const { images, tooDeep } = scanMarkdown(context.text);
+ const match =
+ !tooDeep &&
+ images.find(
+ (image) =>
+ image.type === "image" &&
+ image.position?.end.offset === end &&
+ (image.position.start.offset ?? -1) >= minimum,
+ );
+ const start = match ? match.position?.start.offset : undefined;
+ if (start === undefined) return false;
+
+ const image = documentEditorDraft(context.text.slice(start, end), true);
+ const doc = readComposerSnapshot(image.document, "document");
+ const atom = doc?.firstChild?.firstChild;
+ if (atom?.type !== schema.nodes.markdown_image) return false;
+ const from = $from.pos - (end - start);
+ tr.replaceWith(from, $from.pos, atom.mark(before.marks));
+ tr.setSelection(TextSelection.create(tr.doc, from + atom.nodeSize));
+ return true;
+}
+
/** CommonMark document structure; bounded-parser fallbacks stay exact source. */
export function documentEditorMarkdown(draft: MentionDraft) {
return composerMarkdown(draft, {
diff --git a/src/features/messages/label-text.ts b/src/features/messages/label-text.ts
index ea655ca7e5..8ca6908f2e 100644
--- a/src/features/messages/label-text.ts
+++ b/src/features/messages/label-text.ts
@@ -4,8 +4,8 @@ import { Children, isValidElement, type ReactNode } from "react";
export const labelText = (children: ReactNode): string =>
Children.toArray(children)
.map((child) =>
- isValidElement<{ children?: ReactNode }>(child)
- ? labelText(child.props.children)
+ isValidElement<{ children?: ReactNode; alt?: string }>(child)
+ ? (child.props.alt ?? labelText(child.props.children))
: String(child),
)
.join("");