Skip to content

Commit 2e576b3

Browse files
fix(mobile): resume pending code colors from the latest synchronous read
Successful synchronous reads never touched state, so a later read miss fell back to a result several appends old and newly appended completed lines rendered plain until the asynchronous result landed. The hook now remembers the newest synchronous result in a ref and seeds the pending fallback from it. The ref is cleared whenever an asynchronous result commits, so an older completion can never outrank a newer one.
1 parent ffb875d commit 2e576b3

3 files changed

Lines changed: 340 additions & 122 deletions

File tree

‎apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.tsx‎

Lines changed: 2 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createContext, memo, useContext, useEffect, useMemo, useState } from "react";
1+
import { createContext, memo, useContext, useMemo } from "react";
22
import { Image, Platform, ScrollView, Text, useColorScheme, View } from "react-native";
33
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
44

@@ -9,7 +9,6 @@ import {
99
nativeMarkdownListItemBlocks,
1010
nativeMarkdownNodePosition,
1111
} from "./nativeMarkdownText";
12-
import { pendingCodeHighlight } from "./pendingCodeHighlight";
1312
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText";
1413
import type {
1514
MarkdownCodeHighlighter,
@@ -18,15 +17,11 @@ import type {
1817
NativeMarkdownTextStyle,
1918
SelectableMarkdownSkill,
2019
} from "./SelectableMarkdownText.types";
20+
import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
2121

2222
/** Set by SelectableMarkdownText so images anywhere in the block tree can use it. */
2323
export const MarkdownImageRendererContext = createContext<MarkdownImageRenderer | null>(null);
2424

25-
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
26-
27-
const highlightedCodeCache = new Map<string, HighlightedCode>();
28-
const highlightedCodePromiseCache = new Map<string, Promise<HighlightedCode>>();
29-
const HIGHLIGHTED_CODE_CACHE_LIMIT = 64;
3025
const MONO_FONT_FAMILY = Platform.select({
3126
ios: "ui-monospace",
3227
android: "monospace",
@@ -72,121 +67,6 @@ function SelectableNode(props: {
7267
);
7368
}
7469

75-
function codeHighlightCacheKey(
76-
code: string,
77-
language: string | undefined,
78-
theme: "light" | "dark",
79-
): string {
80-
return `${theme}:${language ?? "text"}:${code}`;
81-
}
82-
83-
function cacheHighlightedCode(key: string, tokens: HighlightedCode): void {
84-
highlightedCodeCache.delete(key);
85-
highlightedCodeCache.set(key, tokens);
86-
87-
while (highlightedCodeCache.size > HIGHLIGHTED_CODE_CACHE_LIMIT) {
88-
const oldestKey = highlightedCodeCache.keys().next().value;
89-
if (oldestKey === undefined) {
90-
break;
91-
}
92-
highlightedCodeCache.delete(oldestKey);
93-
}
94-
}
95-
96-
function loadHighlightedCode(
97-
code: string,
98-
language: string | undefined,
99-
theme: "light" | "dark",
100-
highlightCode: MarkdownCodeHighlighter,
101-
session: object,
102-
): Promise<HighlightedCode> {
103-
const key = codeHighlightCacheKey(code, language, theme);
104-
const cached = highlightedCodeCache.get(key);
105-
if (cached) {
106-
return Promise.resolve(cached);
107-
}
108-
109-
const pending = highlightedCodePromiseCache.get(key);
110-
if (pending) {
111-
return pending;
112-
}
113-
114-
const promise = highlightCode({ code, language, theme, session })
115-
.then((tokens) => {
116-
cacheHighlightedCode(key, tokens);
117-
highlightedCodePromiseCache.delete(key);
118-
return tokens;
119-
})
120-
.catch((error) => {
121-
highlightedCodePromiseCache.delete(key);
122-
throw error;
123-
});
124-
highlightedCodePromiseCache.set(key, promise);
125-
return promise;
126-
}
127-
128-
function useHighlightedCode(
129-
code: string,
130-
language: string | undefined,
131-
theme: "light" | "dark",
132-
highlightCode: MarkdownCodeHighlighter,
133-
): HighlightedCode | null {
134-
const [session] = useState(() => ({}));
135-
const key = codeHighlightCacheKey(code, language, theme);
136-
const ready = useMemo(
137-
() => highlightedCodeCache.get(key) ?? highlightCode.read?.({ code, language, theme, session }),
138-
[code, language, theme, key, highlightCode, session],
139-
);
140-
const [highlighted, setHighlighted] = useState<{
141-
readonly key: string;
142-
readonly code: string;
143-
readonly language: string | undefined;
144-
readonly theme: "light" | "dark";
145-
readonly tokens: HighlightedCode | null;
146-
}>(() => ({
147-
code,
148-
language,
149-
theme,
150-
key,
151-
tokens: highlightedCodeCache.get(key) ?? null,
152-
}));
153-
154-
useEffect(() => {
155-
if (ready) return;
156-
let active = true;
157-
const cached = highlightedCodeCache.get(key);
158-
if (cached) {
159-
cacheHighlightedCode(key, cached);
160-
setHighlighted({ code, language, theme, key, tokens: cached });
161-
return () => {
162-
active = false;
163-
};
164-
}
165-
166-
void loadHighlightedCode(code, language, theme, highlightCode, session)
167-
.then((tokens) => {
168-
if (active) {
169-
setHighlighted({ code, language, theme, key, tokens });
170-
}
171-
})
172-
.catch(() => {
173-
if (active) {
174-
setHighlighted({ code, language, theme, key, tokens: null });
175-
}
176-
});
177-
return () => {
178-
active = false;
179-
};
180-
}, [code, highlightCode, key, language, theme, ready, session]);
181-
182-
if (ready) return ready;
183-
if (highlighted.key === key) return highlighted.tokens;
184-
if (highlighted.tokens && highlighted.language === language && highlighted.theme === theme) {
185-
return pendingCodeHighlight(highlighted.code, code, highlighted.tokens);
186-
}
187-
return null;
188-
}
189-
19070
const HighlightedCodeLine = memo(function HighlightedCodeLine(props: {
19171
readonly tokens: ReadonlyArray<MarkdownHighlightedToken>;
19272
readonly color: string;
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
import { act, useLayoutEffect } from "react";
2+
import { createRoot, type Root } from "react-dom/client";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4+
5+
import type { MarkdownCodeHighlighter } from "./SelectableMarkdownText.types";
6+
import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
7+
8+
type Deferred = {
9+
readonly code: string;
10+
readonly resolve: (tokens: HighlightedCode) => void;
11+
};
12+
13+
/** One colored line per newline-separated line, so a line's color proves where it came from. */
14+
function tokensFor(code: string, color: string): HighlightedCode {
15+
return code.split("\n").map((content) => [{ content, color, fontStyle: 0 }]);
16+
}
17+
18+
function lineText(tokens: HighlightedCode | null): string | null {
19+
return tokens?.map((line) => line.map((token) => token.content).join("")).join("\n") ?? null;
20+
}
21+
22+
function lineColors(tokens: HighlightedCode | null): ReadonlyArray<string | null> {
23+
return tokens?.map((line) => line[0]?.color ?? null) ?? [];
24+
}
25+
26+
const deferred: Deferred[] = [];
27+
const readResults = new Map<string, HighlightedCode>();
28+
let renders = 0;
29+
let result: HighlightedCode | null = null;
30+
let root: Root;
31+
32+
const highlightCode: MarkdownCodeHighlighter = Object.assign(
33+
vi.fn(
34+
(input: { code: string }) =>
35+
new Promise<HighlightedCode>((resolve) => {
36+
deferred.push({ code: input.code, resolve });
37+
}),
38+
),
39+
{
40+
read: vi.fn((input: { code: string }) => readResults.get(input.code)),
41+
},
42+
);
43+
44+
function Probe(props: {
45+
readonly code: string;
46+
readonly language?: string;
47+
readonly theme?: "light" | "dark";
48+
}) {
49+
const tokens = useHighlightedCode(
50+
props.code,
51+
props.language ?? "ts",
52+
props.theme ?? "dark",
53+
highlightCode,
54+
);
55+
useLayoutEffect(() => {
56+
renders += 1;
57+
result = tokens;
58+
});
59+
return null;
60+
}
61+
62+
async function render(props: Parameters<typeof Probe>[0]) {
63+
await act(() => root.render(<Probe {...props} />));
64+
}
65+
66+
async function resolveAsync(index: number, color: string) {
67+
const pending = deferred[index];
68+
if (!pending) throw new Error(`no pending highlight at ${index}`);
69+
await act(async () => {
70+
pending.resolve(tokensFor(pending.code, color));
71+
});
72+
}
73+
74+
beforeEach(async () => {
75+
// The probe has no DOM output, but ReactDOM needs an event target.
76+
const document = {
77+
nodeType: 9,
78+
addEventListener() {},
79+
removeEventListener() {},
80+
};
81+
const container = {
82+
nodeType: 1,
83+
tagName: "DIV",
84+
namespaceURI: "http://www.w3.org/1999/xhtml",
85+
ownerDocument: document,
86+
addEventListener() {},
87+
removeEventListener() {},
88+
};
89+
vi.stubGlobal("document", document);
90+
vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
91+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
92+
deferred.length = 0;
93+
readResults.clear();
94+
renders = 0;
95+
result = null;
96+
vi.mocked(highlightCode).mockClear();
97+
vi.mocked(highlightCode.read!).mockClear();
98+
root = createRoot(container as unknown as HTMLElement);
99+
});
100+
101+
afterEach(async () => {
102+
await act(() => root.unmount());
103+
vi.unstubAllGlobals();
104+
});
105+
106+
// Every test uses a distinct language so the module-level token cache from an
107+
// earlier test can never satisfy a later one.
108+
describe("useHighlightedCode", () => {
109+
it("keeps colors from the latest synchronous read when a later read misses", async () => {
110+
const language = "sync-baseline";
111+
await render({ code: "a", language });
112+
expect(result).toBeNull();
113+
await resolveAsync(0, "async");
114+
expect(lineColors(result)).toEqual(["async"]);
115+
116+
readResults.set("a\nb", tokensFor("a\nb", "sync-1"));
117+
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync-2"));
118+
const rendersBeforeAppends = renders;
119+
await render({ code: "a\nb", language });
120+
await render({ code: "a\nb\nc", language });
121+
expect(lineColors(result)).toEqual(["sync-2", "sync-2", "sync-2"]);
122+
// A synchronous hit is one render per append: no state update, no highlighter call.
123+
expect(renders - rendersBeforeAppends).toBe(2);
124+
expect(highlightCode).toHaveBeenCalledTimes(1);
125+
126+
await render({ code: "a\nb\nc\nd", language });
127+
expect(highlightCode).toHaveBeenCalledTimes(2);
128+
expect(lineText(result)).toBe("a\nb\nc\nd");
129+
// Lines before the previous code's final newline are the completed ones.
130+
expect(lineColors(result)).toEqual(["sync-2", "sync-2", null, null]);
131+
132+
await resolveAsync(1, "async-2");
133+
expect(lineColors(result)).toEqual(["async-2", "async-2", "async-2", "async-2"]);
134+
});
135+
136+
it("does not show obsolete text after a non-append edit", async () => {
137+
const language = "non-append";
138+
await render({ code: "a\nb", language });
139+
await resolveAsync(0, "async");
140+
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
141+
await render({ code: "a\nb\nc", language });
142+
expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
143+
144+
await render({ code: "x\nb\nc", language });
145+
expect(result).toBeNull();
146+
await resolveAsync(1, "async-2");
147+
expect(lineText(result)).toBe("x\nb\nc");
148+
});
149+
150+
it("never reuses colors across a language or theme change", async () => {
151+
const language = "theme-change";
152+
await render({ code: "a\nb", language });
153+
await resolveAsync(0, "async");
154+
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
155+
await render({ code: "a\nb\nc", language });
156+
expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
157+
158+
await render({ code: "a\nb\nc\nd", language, theme: "light" });
159+
expect(result).toBeNull();
160+
await render({ code: "a\nb\nc\nd", language: `${language}-other` });
161+
expect(result).toBeNull();
162+
});
163+
164+
it("ignores an asynchronous completion that is older than the current code", async () => {
165+
const language = "stale-async";
166+
await render({ code: "a\nb", language });
167+
await resolveAsync(0, "async");
168+
169+
await render({ code: "a\nb\nc", language });
170+
expect(deferred).toHaveLength(2);
171+
expect(lineColors(result)).toEqual(["async", null, null]);
172+
173+
readResults.set("a\nb\nc\nd", tokensFor("a\nb\nc\nd", "sync"));
174+
await render({ code: "a\nb\nc\nd", language });
175+
expect(lineColors(result)).toEqual(["sync", "sync", "sync", "sync"]);
176+
177+
await render({ code: "a\nb\nc\nd\ne", language });
178+
expect(deferred).toHaveLength(3);
179+
expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
180+
181+
// The older request finishes after newer synchronous results exist.
182+
await resolveAsync(1, "stale");
183+
expect(lineText(result)).toBe("a\nb\nc\nd\ne");
184+
expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
185+
186+
await resolveAsync(2, "async-3");
187+
expect(lineColors(result)).toEqual(["async-3", "async-3", "async-3", "async-3", "async-3"]);
188+
});
189+
});

0 commit comments

Comments
 (0)