{
expect(screen.getByRole("link", { name: "preview" })).toBe(link);
});
+ it.each([false, true])(
+ "keeps links and inline code mounted when link routing and thread mentions change identity (incrementalBlocks=%s)",
+ (incrementalBlocks) => {
+ const content =
+ "See [docs](https://example.com/docs) and `inline_code` here.";
+ const routing = (): MarkdownLinkRouting => ({
+ onOpenLink: () => true,
+ localImage: {
+ absolutePaths: { kind: "trusted-host" },
+ resolveSrc: ({ path }) => `/files${path}`,
+ },
+ });
+ const { container, rerender } = render(
+
,
+ );
+ const link = screen.getByRole("link", { name: "docs" });
+ const code = container.querySelector("code");
+
+ rerender(
+
,
+ );
+
+ expect(screen.getByRole("link", { name: "docs" })).toBe(link);
+ expect(container.querySelector("code")).toBe(code);
+ },
+ );
+
+ it("routes a link through the latest handler after routing changes", () => {
+ const content = "See [docs](https://example.com/docs).";
+ const first = vi.fn(() => true);
+ const second = vi.fn(() => true);
+ const { rerender } = render(
+
,
+ );
+
+ rerender(
+
,
+ );
+ fireEvent.click(screen.getByRole("link", { name: "docs" }));
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
it("renders inline LaTeX math with KaTeX", async () => {
const { container } = render(
,
diff --git a/apps/app/src/components/ui/markdown-preview.tsx b/apps/app/src/components/ui/markdown-preview.tsx
index 246b71b8179..6211994cfa1 100644
--- a/apps/app/src/components/ui/markdown-preview.tsx
+++ b/apps/app/src/components/ui/markdown-preview.tsx
@@ -6,6 +6,7 @@ import {
import {
Children,
cloneElement,
+ createContext,
isValidElement,
memo,
useLayoutEffect,
@@ -88,16 +89,20 @@ import {
type MarkdownLocalImageRouting,
} from "./markdown-link-routing.js";
import {
- buildThreadMentionComponent,
+ EMPTY_THREAD_MENTIONS,
+ ThreadMentionElement,
+ ThreadMentionsContext,
remarkThreadMentions,
splitRawThreadIdsInText,
} from "./markdown-thread-mentions.js";
import {
- buildPromptMentionComponent,
+ EMPTY_PROMPT_MENTIONS,
+ PromptMentionElement,
+ PromptMentionsContext,
remarkPromptMentions,
substitutePromptMentions,
- type IndexedPromptMention,
type MarkdownPromptMentions,
+ type PromptMentionsContextValue,
} from "./markdown-prompt-mentions.js";
import {
MessageDirectiveElement,
@@ -122,7 +127,6 @@ import {
import { normalizePromptBlockquoteBoundaries } from "./markdown-prompt-blockquote-boundaries.js";
import { MarkdownMermaidDiagram } from "./markdown-mermaid-diagram.js";
import type { PromptTextMention } from "@bb/domain";
-import type { PromptMentionLinkResolver } from "@bb/client-core";
import { usePreferredTheme, type Theme } from "@/hooks/useTheme";
import {
rewriteLocalhostLinkHref,
@@ -171,20 +175,19 @@ interface IsMarkdownAppRouteHrefArgs {
interface BuildMarkdownComponentsArgs {
tableLayout: "breakout" | "contained";
+ hasThreadMentions: boolean;
+ hasPromptMentions: boolean;
+ hasMessageDirectives: boolean;
+}
+
+interface MarkdownRenderOptions {
imagePolicy: MarkdownImagePolicy;
imageSourceOffset: number;
- linkRouting?: MarkdownLinkRouting;
+ linkRouting: MarkdownLinkRouting | undefined;
preferredTheme: Theme;
rewriteLocalhostLinks: boolean;
setExpandedImage: ExpandedMarkdownImageSetter;
- threadMentions?: MarkdownThreadMentions;
- promptMentions?: ResolvedPromptMentions;
- hasMessageDirectives: boolean;
-}
-
-interface ResolvedPromptMentions {
- mentions: readonly IndexedPromptMention[];
- resolveMentionLink?: PromptMentionLinkResolver;
+ threadMentions: MarkdownThreadMentions | undefined;
}
interface BuildLocalAwareUrlTransformArgs {
@@ -1198,173 +1201,129 @@ function resolveMarkdownSourceMedia({
const EMPTY_THREAD_IDS: readonly string[] = [];
-function buildMarkdownComponents({
- tableLayout,
- imagePolicy,
- imageSourceOffset,
- linkRouting,
- preferredTheme,
- rewriteLocalhostLinks,
- setExpandedImage,
- threadMentions,
- promptMentions,
- hasMessageDirectives,
-}: BuildMarkdownComponentsArgs): Components {
- interface RawThreadIdLabelCandidate {
- end: number;
- start: number;
- threadId: string;
- }
+const MarkdownRenderOptionsContext =
+ createContext
(null);
- function flattenMarkdownLinkLabel(node: ReactNode): {
- codeRanges: ReadonlyArray<{ end: number; start: number }>;
- text: string;
- } {
- const codeRanges: Array<{ end: number; start: number }> = [];
- let text = "";
- const append = (child: ReactNode): void => {
- if (typeof child === "string" || typeof child === "number") {
- text += String(child);
- return;
- }
- if (!isValidElement(child)) {
- Children.forEach(child, append);
- return;
- }
- const element = child as ReactElement<{ children?: ReactNode }>;
- const isCode =
- element.type === "code" || element.type === MarkdownCodeRenderer;
- const start = text.length;
- append(element.props.children);
- if (isCode && text.length > start) {
- codeRanges.push({ start, end: text.length });
- }
- };
- append(node);
- return { codeRanges, text };
+function useMarkdownRenderOptions(): MarkdownRenderOptions {
+ const options = useContext(MarkdownRenderOptionsContext);
+ if (options === null) {
+ throw new Error("Markdown components must render inside MarkdownPreview");
}
+ return options;
+}
- function rawThreadIdLabelCandidates(
- node: ReactNode,
- ): RawThreadIdLabelCandidate[] {
- const flattened = flattenMarkdownLinkLabel(node);
- const candidates: RawThreadIdLabelCandidate[] = [];
- let offset = 0;
- for (const segment of splitRawThreadIdsInText(flattened.text)) {
- const start = offset;
- const end = start + segment.text.length;
- offset = end;
- if (
- segment.rawThreadId === null ||
- flattened.codeRanges.some(
- (range) => start < range.end && end > range.start,
- )
- ) {
- continue;
- }
- candidates.push({ start, end, threadId: segment.rawThreadId });
+interface RawThreadIdLabelCandidate {
+ end: number;
+ start: number;
+ threadId: string;
+}
+
+function flattenMarkdownLinkLabel(node: ReactNode): {
+ codeRanges: ReadonlyArray<{ end: number; start: number }>;
+ text: string;
+} {
+ const codeRanges: Array<{ end: number; start: number }> = [];
+ let text = "";
+ const append = (child: ReactNode): void => {
+ if (typeof child === "string" || typeof child === "number") {
+ text += String(child);
+ return;
+ }
+ if (!isValidElement(child)) {
+ Children.forEach(child, append);
+ return;
+ }
+ const element = child as ReactElement<{ children?: ReactNode }>;
+ const isCode =
+ element.type === "code" || element.type === MarkdownCodeRenderer;
+ const start = text.length;
+ append(element.props.children);
+ if (isCode && text.length > start) {
+ codeRanges.push({ start, end: text.length });
+ }
+ };
+ append(node);
+ return { codeRanges, text };
+}
+
+function rawThreadIdLabelCandidates(
+ node: ReactNode,
+): RawThreadIdLabelCandidate[] {
+ const flattened = flattenMarkdownLinkLabel(node);
+ const candidates: RawThreadIdLabelCandidate[] = [];
+ let offset = 0;
+ for (const segment of splitRawThreadIdsInText(flattened.text)) {
+ const start = offset;
+ const end = start + segment.text.length;
+ offset = end;
+ if (
+ segment.rawThreadId === null ||
+ flattened.codeRanges.some(
+ (range) => start < range.end && end > range.start,
+ )
+ ) {
+ continue;
}
- return candidates;
+ candidates.push({ start, end, threadId: segment.rawThreadId });
}
+ return candidates;
+}
- function renderLiftedMarkdownLinkLabel(
- node: ReactNode,
- anchorProps: Omit,
- candidates: readonly RawThreadIdLabelCandidate[],
- resourceById: ReadonlyMap,
- cursor: { value: number },
- ): ReactNode {
- if (typeof node === "string" || typeof node === "number") {
- const text = String(node);
- const start = cursor.value;
- const end = start + text.length;
- cursor.value = end;
- const containedCandidates = candidates.filter(
- (candidate) => candidate.start >= start && candidate.end <= end,
- );
- if (containedCandidates.length === 0) {
- return (
-
- {text}
-
+function renderLiftedMarkdownLinkLabel(
+ node: ReactNode,
+ anchorProps: Omit,
+ candidates: readonly RawThreadIdLabelCandidate[],
+ resourceById: ReadonlyMap,
+ cursor: { value: number },
+): ReactNode {
+ if (typeof node === "string" || typeof node === "number") {
+ const text = String(node);
+ const start = cursor.value;
+ const end = start + text.length;
+ cursor.value = end;
+ const containedCandidates = candidates.filter(
+ (candidate) => candidate.start >= start && candidate.end <= end,
+ );
+ if (containedCandidates.length === 0) {
+ return {text};
+ }
+ const rendered: ReactNode[] = [];
+ let localCursor = 0;
+ for (const candidate of containedCandidates) {
+ const candidateStart = candidate.start - start;
+ const candidateEnd = candidate.end - start;
+ if (candidateStart > localCursor) {
+ rendered.push(
+
+ {text.slice(localCursor, candidateStart)}
+ ,
);
}
- const rendered: ReactNode[] = [];
- let localCursor = 0;
- for (const candidate of containedCandidates) {
- const candidateStart = candidate.start - start;
- const candidateEnd = candidate.end - start;
- if (candidateStart > localCursor) {
- rendered.push(
-
- {text.slice(localCursor, candidateStart)}
- ,
- );
- }
- const resource = resourceById.get(candidate.threadId);
- if (resource !== undefined) {
- rendered.push(
- ,
- );
- }
- localCursor = candidateEnd;
- }
- if (localCursor < text.length) {
+ const resource = resourceById.get(candidate.threadId);
+ if (resource !== undefined) {
rendered.push(
-
- {text.slice(localCursor)}
- ,
+ ,
);
}
- return rendered;
+ localCursor = candidateEnd;
}
- if (!isValidElement(node)) {
- return Children.map(node, (child) =>
- renderLiftedMarkdownLinkLabel(
- child,
- anchorProps,
- candidates,
- resourceById,
- cursor,
- ),
+ if (localCursor < text.length) {
+ rendered.push(
+
+ {text.slice(localCursor)}
+ ,
);
}
- if (node.type === "code" || node.type === MarkdownCodeRenderer) {
- cursor.value += flattenMarkdownLinkLabel(node).text.length;
- return (
-
- {node}
-
- );
- }
- const element = node as ReactElement<{ children?: ReactNode }>;
- return cloneElement(
- element,
- undefined,
+ return rendered;
+ }
+ if (!isValidElement(node)) {
+ return Children.map(node, (child) =>
renderLiftedMarkdownLinkLabel(
- element.props.children,
+ child,
anchorProps,
candidates,
resourceById,
@@ -1372,144 +1331,175 @@ function buildMarkdownComponents({
),
);
}
-
- function MarkdownLink(props: MarkdownAnchorProps) {
- const { children, ...anchorProps } = props;
- const candidates = useMemo(
- () =>
- threadMentions === undefined
- ? []
- : rawThreadIdLabelCandidates(children),
- [children],
- );
- const candidateThreadIds = useMemo(
- () =>
- candidates.length === 0
- ? EMPTY_THREAD_IDS
- : [...new Set(candidates.map((candidate) => candidate.threadId))],
- [candidates],
- );
- const resourceById = useRawThreadMentionResources(candidateThreadIds);
- const resolvedCandidates = candidates.filter((candidate) =>
- resourceById.has(candidate.threadId),
- );
- if (resolvedCandidates.length > 0) {
- return (
- <>
- {renderLiftedMarkdownLinkLabel(
- children,
- anchorProps,
- resolvedCandidates,
- resourceById,
- { value: 0 },
- )}
- >
- );
- }
- return (
-
- {children}
-
- );
+ if (node.type === "code" || node.type === MarkdownCodeRenderer) {
+ cursor.value += flattenMarkdownLinkLabel(node).text.length;
+ return {node};
}
+ const element = node as ReactElement<{ children?: ReactNode }>;
+ return cloneElement(
+ element,
+ undefined,
+ renderLiftedMarkdownLinkLabel(
+ element.props.children,
+ anchorProps,
+ candidates,
+ resourceById,
+ cursor,
+ ),
+ );
+}
- function MarkdownCodeRenderer(props: MarkdownCodeProps) {
+function MarkdownLink(props: MarkdownAnchorProps) {
+ const { linkRouting, rewriteLocalhostLinks, threadMentions } =
+ useMarkdownRenderOptions();
+ const { children, ...elementProps } = props;
+ const anchorProps = {
+ ...elementProps,
+ linkRouting,
+ rewriteLocalhostLinks,
+ };
+ const candidates = useMemo(
+ () =>
+ threadMentions === undefined ? [] : rawThreadIdLabelCandidates(children),
+ [children, threadMentions],
+ );
+ const candidateThreadIds = useMemo(
+ () =>
+ candidates.length === 0
+ ? EMPTY_THREAD_IDS
+ : [...new Set(candidates.map((candidate) => candidate.threadId))],
+ [candidates],
+ );
+ const resourceById = useRawThreadMentionResources(candidateThreadIds);
+ const resolvedCandidates = candidates.filter((candidate) =>
+ resourceById.has(candidate.threadId),
+ );
+ if (resolvedCandidates.length > 0) {
return (
-
+ <>
+ {renderLiftedMarkdownLinkLabel(
+ children,
+ anchorProps,
+ resolvedCandidates,
+ resourceById,
+ { value: 0 },
+ )}
+ >
);
}
+ return {children};
+}
- function MarkdownImage({
- src,
- alt,
- className: _className,
- node,
- "data-markdown-image-offset": pieceOffset,
- ...imageAttributes
- }: MarkdownImageProps) {
- if (imagePolicy === "alt-text") {
- return (
-
- [Image: {typeof alt === "string" && alt.length > 0 ? alt : "image"}]
-
- );
- }
- const sourceOffset = pieceOffset ?? node?.position?.start.offset;
+function MarkdownCodeRenderer(props: MarkdownCodeProps) {
+ const {
+ imagePolicy,
+ imageSourceOffset,
+ linkRouting,
+ preferredTheme,
+ rewriteLocalhostLinks,
+ } = useMarkdownRenderOptions();
+ return (
+
+ );
+}
+
+function MarkdownImage({
+ src,
+ alt,
+ className: _className,
+ node,
+ "data-markdown-image-offset": pieceOffset,
+ ...imageAttributes
+}: MarkdownImageProps) {
+ const { imagePolicy, imageSourceOffset, setExpandedImage } =
+ useMarkdownRenderOptions();
+ if (imagePolicy === "alt-text") {
return (
-
+
+ [Image: {typeof alt === "string" && alt.length > 0 ? alt : "image"}]
+
);
}
+ const sourceOffset = pieceOffset ?? node?.position?.start.offset;
+ return (
+
+ );
+}
- function MarkdownVideo({
- node: _node,
- children,
- src,
- poster,
- controls = true,
- playsInline = true,
- preload = "metadata",
- width,
- height,
- title,
- "aria-label": label,
- }: ComponentPropsWithoutRef<"video"> & ExtraProps) {
- if (imagePolicy === "alt-text") {
- return [Video: {label || title || "video"}];
- }
- return (
-
- );
+function MarkdownVideo({
+ node: _node,
+ children,
+ src,
+ poster,
+ controls = true,
+ playsInline = true,
+ preload = "metadata",
+ width,
+ height,
+ title,
+ "aria-label": label,
+}: ComponentPropsWithoutRef<"video"> & ExtraProps) {
+ const { imagePolicy } = useMarkdownRenderOptions();
+ if (imagePolicy === "alt-text") {
+ return [Video: {label || title || "video"}];
}
+ return (
+
+ );
+}
- function MarkdownSource({
- media,
- node: _node,
- ...sourceProps
- }: MarkdownSourceProps) {
- if (imagePolicy === "alt-text") {
- return null;
- }
- return (
-
- );
+function MarkdownSource({
+ media,
+ node: _node,
+ ...sourceProps
+}: MarkdownSourceProps) {
+ const { imagePolicy, preferredTheme } = useMarkdownRenderOptions();
+ if (imagePolicy === "alt-text") {
+ return null;
}
+ return (
+
+ );
+}
+function buildMarkdownComponents({
+ tableLayout,
+ hasThreadMentions,
+ hasPromptMentions,
+ hasMessageDirectives,
+}: BuildMarkdownComponentsArgs): Components {
const components: Components = {
a: MarkdownLink,
blockquote: MarkdownBlockquote,
@@ -1535,17 +1525,12 @@ function buildMarkdownComponents({
ul: MarkdownUnorderedList,
};
- if (threadMentions !== undefined) {
- components["bb-thread-mention"] = buildThreadMentionComponent({
- mentions: threadMentions.mentions,
- });
+ if (hasThreadMentions) {
+ components["bb-thread-mention"] = ThreadMentionElement;
}
- if (promptMentions !== undefined) {
- components["bb-prompt-mention"] = buildPromptMentionComponent({
- mentions: promptMentions.mentions,
- resolveMentionLink: promptMentions.resolveMentionLink,
- });
+ if (hasPromptMentions) {
+ components["bb-prompt-mention"] = PromptMentionElement;
}
if (hasMessageDirectives) {
@@ -1868,7 +1853,9 @@ function MarkdownPreviewComponent({
: null,
[content, promptMentions],
);
- const resolvedPromptMentions = useMemo(
+ const resolvedPromptMentions = useMemo<
+ PromptMentionsContextValue | undefined
+ >(
() =>
promptMentions && promptMentionSubstitution
? {
@@ -1912,33 +1899,38 @@ function MarkdownPreviewComponent({
registry: messageDirectives.registry,
};
}, [messageDirectives]);
+ const hasMessageDirectives = messageDirectiveMounts !== null;
+ const hasThreadMentions = threadMentions !== undefined;
+ const hasPromptMentions = resolvedPromptMentions !== undefined;
const markdownComponents = useMemo(
() =>
buildMarkdownComponents({
tableLayout,
- imagePolicy,
- imageSourceOffset,
- linkRouting,
- preferredTheme,
- rewriteLocalhostLinks,
- setExpandedImage,
- threadMentions,
- promptMentions: resolvedPromptMentions,
- hasMessageDirectives: messageDirectiveMounts !== null,
+ hasThreadMentions,
+ hasPromptMentions,
+ hasMessageDirectives,
}),
- [
- tableLayout,
+ [tableLayout, hasThreadMentions, hasPromptMentions, hasMessageDirectives],
+ );
+ const markdownRenderOptions = useMemo(
+ () => ({
+ imagePolicy,
+ imageSourceOffset,
linkRouting,
+ preferredTheme,
+ rewriteLocalhostLinks,
+ setExpandedImage,
+ threadMentions,
+ }),
+ [
imagePolicy,
imageSourceOffset,
+ linkRouting,
preferredTheme,
rewriteLocalhostLinks,
threadMentions,
- resolvedPromptMentions,
- messageDirectiveMounts,
],
);
- const hasMessageDirectives = messageDirectiveMounts !== null;
const baseRemarkPlugins = useMemo((): MarkdownRemarkPlugins => {
const plugins: MarkdownRemarkPlugins = [
remarkGfm,
@@ -2083,13 +2075,23 @@ function MarkdownPreviewComponent({
render: messageDirectiveMounts,
}}
>
- {threadMentions === undefined ? (
- renderedMarkdown
- ) : (
-
- {renderedMarkdown}
-
- )}
+
+
+
+ {threadMentions === undefined ? (
+ renderedMarkdown
+ ) : (
+
+ {renderedMarkdown}
+
+ )}
+
+
+
diff --git a/apps/app/src/components/ui/markdown-prompt-mentions.tsx b/apps/app/src/components/ui/markdown-prompt-mentions.tsx
index 78f1758c927..fb06df9e6ff 100644
--- a/apps/app/src/components/ui/markdown-prompt-mentions.tsx
+++ b/apps/app/src/components/ui/markdown-prompt-mentions.tsx
@@ -1,5 +1,5 @@
import { normalizePromptTextMentions } from "@bb/client-core";
-import type { ComponentType } from "react";
+import { createContext, useContext } from "react";
import type { Nodes, Parent, PhrasingContent, Text } from "mdast";
import type {} from "mdast-util-to-hast";
import { visit } from "unist-util-visit";
@@ -99,7 +99,7 @@ export interface MarkdownPromptMentions {
resolveMentionLink?: PromptMentionLinkResolver;
}
-interface BuildPromptMentionComponentArgs {
+export interface PromptMentionsContextValue {
mentions: readonly IndexedPromptMention[];
resolveMentionLink?: PromptMentionLinkResolver;
}
@@ -116,27 +116,29 @@ declare module "react" {
}
}
-export function buildPromptMentionComponent({
- mentions,
- resolveMentionLink,
-}: BuildPromptMentionComponentArgs): ComponentType