Skip to content

Commit fad507c

Browse files
Umais-Adeedclaude
andauthored
fix(mobile): chat folds stay closed until tapped, as on web and desktop (pingdotgg#28072)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 1794830 commit fad507c

4 files changed

Lines changed: 281 additions & 24 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 99 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ import { FONT_FAMILIES } from "../../lib/fontFamilies";
148148
import { scopedThreadKey } from "../../lib/scopedEntities";
149149
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
150150
import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
151+
import { splitMarkdownDetails } from "../../lib/markdownDetails";
151152
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
152153
import {
153154
SelectableMarkdownText,
@@ -1186,39 +1187,115 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11861187
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
11871188
}) {
11881189
const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
1189-
const segments = useMemo(() => splitCodexArtifactTemplateMarkdown(liveMarkdown), [liveMarkdown]);
11901190
const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
11911191
const linkHandlers: MarkdownLinkHandlers = {
11921192
...props.linkHandlers,
11931193
linkCustomization: (href) =>
11941194
withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
11951195
};
11961196

1197-
return segments.map((segment) => {
1198-
if (segment.kind === "artifact-template") {
1197+
return (
1198+
<AssistantMarkdownBlocks
1199+
markdown={liveMarkdown}
1200+
markdownStyles={props.markdownStyles}
1201+
linkHandlers={linkHandlers}
1202+
onUseArtifactTemplate={props.onUseArtifactTemplate}
1203+
renderImage={props.renderImage}
1204+
skills={props.skills}
1205+
/>
1206+
);
1207+
});
1208+
1209+
// Folds split first, so an artifact card inside a fold stays inside it.
1210+
function AssistantMarkdownBlocks(props: {
1211+
readonly markdown: string;
1212+
readonly markdownStyles: MarkdownStyleSet;
1213+
readonly linkHandlers: MarkdownLinkHandlers;
1214+
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
1215+
readonly renderImage: MarkdownImageRenderer;
1216+
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
1217+
}) {
1218+
const blocks = useMemo(
1219+
() =>
1220+
splitMarkdownDetails(props.markdown).map((block) =>
1221+
block.kind === "details"
1222+
? block
1223+
: { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) },
1224+
),
1225+
[props.markdown],
1226+
);
1227+
return blocks.map((block) => {
1228+
if (block.kind === "details") {
11991229
return (
1200-
<ArtifactTemplateCard
1201-
key={`artifact-template:${segment.sourceOffset}`}
1202-
template={segment.template}
1203-
onUse={props.onUseArtifactTemplate}
1204-
/>
1230+
<MarkdownDetailsFold
1231+
key={`details:${block.sourceOffset}`}
1232+
summary={block.summary}
1233+
initiallyOpen={block.open}
1234+
>
1235+
<AssistantMarkdownBlocks {...props} markdown={block.body} />
1236+
</MarkdownDetailsFold>
12051237
);
12061238
}
1207-
if (segment.markdown.trim().length === 0) return null;
1208-
1209-
const markdown = renderCodexInlineDirectivesAsMarkdown(segment.markdown);
1210-
return (
1211-
<SelectableMarkdownText
1212-
key={`markdown:${segment.sourceOffset}`}
1213-
markdown={markdown}
1214-
skills={props.skills}
1215-
textStyle={props.markdownStyles.nativeTextStyle}
1216-
{...linkHandlers}
1217-
renderImage={props.renderImage}
1218-
/>
1219-
);
1239+
return block.segments.map((segment) => {
1240+
const offset = block.sourceOffset + segment.sourceOffset;
1241+
if (segment.kind === "artifact-template") {
1242+
return (
1243+
<ArtifactTemplateCard
1244+
key={`artifact-template:${offset}`}
1245+
template={segment.template}
1246+
onUse={props.onUseArtifactTemplate}
1247+
/>
1248+
);
1249+
}
1250+
if (segment.markdown.trim().length === 0) return null;
1251+
return (
1252+
<SelectableMarkdownText
1253+
key={`markdown:${offset}`}
1254+
markdown={renderCodexInlineDirectivesAsMarkdown(segment.markdown)}
1255+
skills={props.skills}
1256+
textStyle={props.markdownStyles.nativeTextStyle}
1257+
{...props.linkHandlers}
1258+
renderImage={props.renderImage}
1259+
/>
1260+
);
1261+
});
12201262
});
1221-
});
1263+
}
1264+
1265+
function MarkdownDetailsFold(props: {
1266+
readonly summary: string;
1267+
readonly initiallyOpen: boolean;
1268+
readonly children: ReactNode;
1269+
}) {
1270+
const [expanded, setExpanded] = useState(props.initiallyOpen);
1271+
const iconSubtleColor = useUniwindTheme()["--color-icon-subtle"];
1272+
return (
1273+
<View className="my-2 border-y border-border">
1274+
<Pressable
1275+
accessibilityRole="button"
1276+
accessibilityLabel={props.summary}
1277+
accessibilityState={{ expanded }}
1278+
hitSlop={4}
1279+
className="min-h-10 flex-row items-center gap-2 py-2"
1280+
onPress={() => {
1281+
void Haptics.selectionAsync();
1282+
setExpanded((value) => !value);
1283+
}}
1284+
>
1285+
<ThreadDisclosureChevron
1286+
expanded={expanded}
1287+
collapsedDirection="right"
1288+
size={12}
1289+
tintColor={iconSubtleColor}
1290+
/>
1291+
<Text className="min-w-0 shrink font-t3-medium text-sm text-foreground">
1292+
{props.summary}
1293+
</Text>
1294+
</Pressable>
1295+
{expanded ? <View className="pb-3 pl-5">{props.children}</View> : null}
1296+
</View>
1297+
);
1298+
}
12221299

12231300
function useMarkdownStyles(): MarkdownStyleSets {
12241301
const { appearance } = useAppearancePreferences();
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { splitMarkdownDetails } from "./markdownDetails";
4+
5+
describe("splitMarkdownDetails", () => {
6+
// regression: #28059 mobile chat showed every <details> fold open
7+
it("splits a top-level fold into its summary and hidden body", () => {
8+
const markdown =
9+
"Short answer.\n\n<details>\n<summary>Long details</summary>\n\nA long paragraph.\n\n</details>\n\nAfter.";
10+
expect(splitMarkdownDetails(markdown)).toEqual([
11+
{ kind: "markdown", markdown: "Short answer.\n\n", sourceOffset: 0 },
12+
{
13+
kind: "details",
14+
summary: "Long details",
15+
body: "\n\nA long paragraph.\n\n",
16+
open: false,
17+
sourceOffset: 15,
18+
},
19+
{ kind: "markdown", markdown: "\n\nAfter.", sourceOffset: 87 },
20+
]);
21+
});
22+
23+
it("keeps nested folds in the body and honours the open attribute", () => {
24+
const markdown =
25+
"<details open>\n<summary>Outer &amp; <code>more</code></summary>\n\n<details>\n<summary>Inner</summary>\n\nx\n\n</details>\n\n</details>";
26+
const [fold] = splitMarkdownDetails(markdown);
27+
expect(fold).toMatchObject({ kind: "details", summary: "Outer & more", open: true });
28+
expect(fold?.kind === "details" && splitMarkdownDetails(fold.body)).toMatchObject([
29+
{ kind: "markdown" },
30+
{ kind: "details", summary: "Inner", body: "\n\nx\n\n" },
31+
{ kind: "markdown" },
32+
]);
33+
});
34+
35+
it("leaves folds in code and inline tags as markdown", () => {
36+
for (const markdown of [
37+
"```html\n<details>\n<summary>Code</summary>\n</details>\n```",
38+
"Use `<details>` for folds.",
39+
"Text <details><summary>inline</summary>body</details> more",
40+
"<!-- <details> -->\n\nVisible answer.",
41+
]) {
42+
expect(splitMarkdownDetails(markdown)).toEqual([
43+
{ kind: "markdown", markdown, sourceOffset: 0 },
44+
]);
45+
}
46+
});
47+
48+
it("ignores a closing tag inside a code example in the fold", () => {
49+
const markdown =
50+
"<details>\n<summary>Example</summary>\n```html\n</details>\n```\n</details>\n\nAfter.";
51+
expect(splitMarkdownDetails(markdown)).toMatchObject([
52+
{ kind: "details", summary: "Example", body: "\n```html\n</details>\n```\n" },
53+
{ kind: "markdown", markdown: "\n\nAfter." },
54+
]);
55+
});
56+
57+
it("closes a fold at a closing tag that ends a paragraph", () => {
58+
expect(
59+
splitMarkdownDetails("<details>\n<summary>Plan</summary>\n\nDone </details>\n\nNext step"),
60+
).toMatchObject([
61+
{ kind: "details", summary: "Plan", body: "\n\nDone " },
62+
{ kind: "markdown", markdown: "\n\nNext step" },
63+
]);
64+
});
65+
66+
it("folds the rest of a reply whose closing tag has not streamed yet", () => {
67+
expect(splitMarkdownDetails("<details>\n<summary>Plan</summary>\n\nStep one")).toEqual([
68+
{ kind: "details", summary: "Plan", body: "\n\nStep one", open: false, sourceOffset: 0 },
69+
]);
70+
expect(
71+
splitMarkdownDetails("<details>\n<summary>Plan</summary>\n\n```html\n</details>"),
72+
).toMatchObject([{ kind: "details", body: "\n\n```html\n</details>" }]);
73+
});
74+
75+
it("reads open only as an attribute name", () => {
76+
expect(
77+
splitMarkdownDetails('<details title="is open">\n<summary>Plan</summary>\n</details>'),
78+
).toMatchObject([{ kind: "details", open: false }]);
79+
});
80+
});
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import type { RootContent } from "mdast";
2+
import { unified } from "unified";
3+
import remarkParse from "remark-parse";
4+
5+
import { decodeHtmlEntities, markdownHtmlTags } from "./markdownDocument";
6+
7+
export type MarkdownDetailsSegment =
8+
| { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number }
9+
| {
10+
readonly kind: "details";
11+
readonly summary: string;
12+
readonly body: string;
13+
readonly open: boolean;
14+
readonly sourceOffset: number;
15+
};
16+
17+
type OpenFold = { start: number; openTagEnd: number; open: boolean };
18+
19+
const parser = unified().use(remarkParse);
20+
const DETAILS_TAG = /^<(\/?)details\b/i;
21+
const SUMMARY = /^\s*<summary\b[^>]*>([\s\S]*?)<\/summary\s*>/i;
22+
23+
/**
24+
* Splits top-level `<details>` blocks out of chat Markdown so they can render as folds.
25+
* Tags inside code, or a fold opened inline in a paragraph, stay Markdown. A fold whose
26+
* closing tag has not streamed yet runs to the end.
27+
*/
28+
export function splitMarkdownDetails(markdown: string): ReadonlyArray<MarkdownDetailsSegment> {
29+
if (!/<details\b/i.test(markdown)) return [{ kind: "markdown", markdown, sourceOffset: 0 }];
30+
31+
const folds: Array<OpenFold & { end: number; closeTagLength: number }> = [];
32+
let depth = 0;
33+
// Asserted so the scan closure's writes are not narrowed away after the loop.
34+
let current = null as OpenFold | null;
35+
// A fold opens only at block level; once open, a tag inside a paragraph can close it.
36+
const scan = (node: RootContent, inline: boolean) => {
37+
if (node.type !== "html") {
38+
if (depth > 0 && "children" in node) {
39+
for (const child of node.children) scan(child, true);
40+
}
41+
return;
42+
}
43+
if (node.position?.start.offset === undefined) return;
44+
const nodeStart = node.position.start.offset;
45+
for (const tag of markdownHtmlTags(node.value)) {
46+
const details = DETAILS_TAG.exec(tag[0]);
47+
if (!details || (inline && depth === 0)) continue;
48+
const start = nodeStart + tag.index;
49+
if (details[1] !== "/") {
50+
if (depth === 0) {
51+
// Quoted values are blanked so `title="is open"` does not count as the attribute.
52+
const attributes = tag[0].replace(/"[^"]*"|'[^']*'/g, '""');
53+
current = {
54+
start,
55+
openTagEnd: start + tag[0].length,
56+
open: /\sopen\b/i.test(attributes),
57+
};
58+
}
59+
depth += 1;
60+
} else if (depth > 0) {
61+
depth -= 1;
62+
if (depth === 0 && current) {
63+
folds.push({ ...current, end: start + tag[0].length, closeTagLength: tag[0].length });
64+
current = null;
65+
}
66+
}
67+
}
68+
};
69+
for (const node of parser.parse(markdown).children) scan(node, false);
70+
if (current) folds.push({ ...current, end: markdown.length, closeTagLength: 0 });
71+
if (folds.length === 0) return [{ kind: "markdown", markdown, sourceOffset: 0 }];
72+
73+
const segments: MarkdownDetailsSegment[] = [];
74+
let cursor = 0;
75+
for (const fold of folds) {
76+
if (fold.start > cursor) {
77+
segments.push({
78+
kind: "markdown",
79+
markdown: markdown.slice(cursor, fold.start),
80+
sourceOffset: cursor,
81+
});
82+
}
83+
let body = markdown.slice(fold.openTagEnd, fold.end - fold.closeTagLength);
84+
const summary = SUMMARY.exec(body);
85+
if (summary) body = body.slice(summary[0].length);
86+
const label = summary ? decodeHtmlEntities(summary[1]!.replace(/<[^>]*>/g, "")).trim() : "";
87+
segments.push({
88+
kind: "details",
89+
summary: label || "Details",
90+
body,
91+
open: fold.open,
92+
sourceOffset: fold.start,
93+
});
94+
cursor = fold.end;
95+
}
96+
if (cursor < markdown.length) {
97+
segments.push({ kind: "markdown", markdown: markdown.slice(cursor), sourceOffset: cursor });
98+
}
99+
return segments;
100+
}

‎apps/mobile/src/lib/markdownDocument.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ function decodeCodePoint(codePoint: number, entity: string): string {
3434
return String.fromCodePoint(codePoint);
3535
}
3636

37-
function decodeHtmlEntities(value: string): string {
37+
export function decodeHtmlEntities(value: string): string {
3838
return value.replace(
3939
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
4040
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
@@ -125,7 +125,7 @@ function anchorMarkdown(tags: readonly string[]): AnchorState {
125125
return { pending: replacements, open: 0 };
126126
}
127127

128-
function markdownHtmlTags(content: string): RegExpExecArray[] {
128+
export function markdownHtmlTags(content: string): RegExpExecArray[] {
129129
// An HTML block such as <details> can also contain Markdown fences and code spans.
130130
const codeRanges: Array<{ start: number; end: number }> = [];
131131
const tags = [...content.matchAll(HTML_TAG)];

0 commit comments

Comments
 (0)