Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/buzz-help.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/bundled/docs/DocDialogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ export function DocRevisionPreview({
<Markdown
content={revision.markdown}
scale="document"
images={{ session: workspace.session }}
session={workspace.session}
/>
) : (
Expand Down
37 changes: 37 additions & 0 deletions src/bundled/docs/DocDocument.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `[![Diagram](${remote})](${report})\n\n![Relay image][relay]\n\n![Unsafe](javascript:alert%281%29)\n\n[relay]: ${media}`;
const doc = f.seed("Images", markdown);
const props = { address: doc, workspace: f.workspace, onOpen: vi.fn() };
const view = render(<DocDocument {...props} view={{ edit: false }} />);

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(<DocDocument {...props} view={{ edit: true }} />);
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, {
Expand Down
1 change: 1 addition & 0 deletions src/bundled/docs/DocDocument.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,7 @@ export function DocDocument({
>
<DocEditor
ref={editor}
session={workspace.session}
source={source}
onSourceChange={setSource}
toolbarTarget={toolbarTarget}
Expand Down
11 changes: 10 additions & 1 deletion src/bundled/docs/DocEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import { useMemo } from "react";
import type {
DocumentEditorHandle,
DocumentEditorProps,
} from "../../plugins/author";
import type { RelaySession } from "../../features/relay/session";
import { MAX_DOC_BYTES } from "./model";
import { useDocsUi } from "./ui";

export type DocEditorHandle = DocumentEditorHandle;
export function DocEditor(props: Omit<DocumentEditorProps, "maxLength">) {
export function DocEditor({
session,
...props
}: Omit<DocumentEditorProps, "maxLength" | "images"> & {
session: RelaySession;
}) {
const Editor = useDocsUi().conversation.DocumentEditor;
const images = useMemo(() => ({ session }), [session]);
return (
<Editor
{...props}
maxLength={MAX_DOC_BYTES}
images={images}
label="Doc body"
placeholder="Write your doc…"
/>
Expand Down
1 change: 1 addition & 0 deletions src/bundled/docs/DocMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export function DocMarkdown({
<SafeMarkdown
content={text}
scale="document"
images={{ session }}
session={session}
openLink={(url) => {
const doc = parseDocUrl(url);
Expand Down
1 change: 1 addition & 0 deletions src/bundled/docs/NewDocDocument.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ export function NewDocDocument({
<div ref={body} className={source ? styles.sourceBody : styles.stack}>
<DocEditor
ref={editor}
session={workspace.session}
value={markdown}
editing
disabled={false}
Expand Down
6 changes: 6 additions & 0 deletions src/features/markdown/Markdown.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ html[data-keyboard-navigation] .document pre code:focus-visible {
.inline a:not([aria-disabled="true"]):hover {
text-decoration-thickness: 2px;
}
.image {
display: inline-block;
max-inline-size: 100%;
block-size: auto;
vertical-align: middle;
}
.imageAlt {
color: var(--text-subtle);
font-style: italic;
Expand Down
49 changes: 47 additions & 2 deletions src/features/markdown/MarkdownDocument.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
import { MessageLink } from "../conversation/MessageLink";
import { labelText } from "../messages/label-text";
import type { RelaySession } from "../relay/session";
import { safeMessageUrl } from "../relay/message-content";
import {
CodeFence,
flushOverflowChecks,
Expand All @@ -33,12 +34,47 @@ export type MarkdownCapabilities = Readonly<{
/** Routes links through `MessageLink`; without it links open externally. */
openLink?: ((url: string) => 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<CodeBlockRenderer> | undefined;
/** A copy action on code blocks. */
copy?: boolean | undefined;
}>;

export type MarkdownImageOptions = {
session?: Pick<RelaySession, "media"> | 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 ? (
<img
className={styles.image}
src={source}
alt={alt ?? ""}
title={title}
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
draggable={false}
/>
) : alt ? (
<span className={styles.imageAlt}>{alt}</span>
) : null;
}

const CapabilitiesContext = createContext<MarkdownCapabilities>({});

const SCALES: Record<HeadingScale, string | undefined> = {
Expand Down Expand Up @@ -82,8 +118,17 @@ export const sharedComponents: Components = {
</MessageLink>
);
},
img: ({ alt }) =>
alt ? <span className={styles.imageAlt}>{alt}</span> : null,
img: function SharedImage({ src, alt, title }) {
const { images } = useContext(CapabilitiesContext);
return (
<MarkdownImage
src={typeof src === "string" ? src : undefined}
alt={alt}
title={title}
images={images}
/>
);
},
pre: function SharedCode(props) {
const { codeBlocks, copy } = useContext(CapabilitiesContext);
return <CodeFence {...props} copy={copy} registry={codeBlocks} />;
Expand Down
29 changes: 29 additions & 0 deletions src/features/messages/DocumentEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,35 @@ function replaceMarkdown(h: ReturnType<typeof mount>, value: string) {
return richInput();
}

it("previews typed and pasted images while retaining their Markdown source", async () => {
const markdown = "![Chart](https://images.example/chart.png)";
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)
Expand Down
33 changes: 26 additions & 7 deletions src/features/messages/DocumentEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -127,6 +128,8 @@ export type DocumentEditorProps = {
ref?: Ref<DocumentEditorHandle>;
value: string;
editing: boolean;
/** Enables inline previews for image Markdown in formatted editing. */
images?: MarkdownImageOptions | undefined;
children?: ReactNode;
onChange(value: string): void;
disabled?: boolean;
Expand Down Expand Up @@ -177,16 +180,21 @@ 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. */
export function DocumentEditor({
ref,
value,
editing,
images,
children,
onChange,
disabled = false,
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading