Open History to see the last commit
1import { createContext, useCallback, useContext, useMemo } from "react";
2import { decodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
3import {
4 findNodeHandle,
5 Image,
6 Linking,
7 Platform,
8 StyleSheet,
9 Text as RNText,
10 type TextStyle,
11 useColorScheme,
12 View,
13} from "react-native";
14
15import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
16import { markdownFileIconSource } from "./markdownFileIcons";
17import { markdownLinkIconSource } from "./markdownLinkIcons";
18import { resolveMarkdownFileIcon, resolveMarkdownLinkIcon } from "./markdownLinks";
19import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
20import { nativeMarkdownContextCopyRanges } from "./nativeMarkdownText";
21import type {
22 MarkdownFileContextMenu,
23 NativeMarkdownTextStyle,
24} from "./SelectableMarkdownText.types";
25import {
26 installMarkdownCopySanitizer,
27 renderAndroidContextChip,
28} from "./T3MarkdownTextSelectionModule";
29import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
30import { contextChipPresentation } from "./nativeMarkdownText";
31
32export const MarkdownContextClipboardContext = createContext("");
33
34export interface MarkdownFileContextMenuHandlers {
35 readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
36 readonly onFileContextMenuAction: (href: string, actionId: string) => void;
37}
38
39/** Set by SelectableMarkdownText so file chips anywhere in the block tree get the same menu. */
40export const MarkdownFileContextMenuContext = createContext<MarkdownFileContextMenuHandlers | null>(
41 null,
42);
43
44const EXTERNAL_LINK_PREFIX = "◉ ";
45const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
46const SKILL_ICON_PLACEHOLDER = "\uFFFC";
47// React Native turns a run whose whole text is U+FFFC into a bare inline-view attachment
48// with no font or paragraph style, so a chip opening a paragraph would drop its line
49// height. Any other single character keeps the run's attributes; the native side swaps it
50// for the chip attachment either way.
51const IOS_CHIP_PLACEHOLDER = "\u200B";
52const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
53const MONO_FONT_FAMILY = Platform.select({
54 ios: "ui-monospace",
55 android: "monospace",
56 default: "monospace",
57});
58const styles = StyleSheet.create({
59 inlineIcon: {
60 width: 14,
61 height: 14,
62 marginHorizontal: 3,
63 transform: [{ translateY: 2 }],
64 },
65});
66
67function runKeySignature(run: NativeMarkdownTextRun): string {
68 return [
69 run.text,
70 run.bold,
71 run.italic,
72 run.strikethrough,
73 run.code,
74 run.href,
75 run.externalHost,
76 run.fileIcon,
77 run.skillName,
78 run.skillLabel,
79 run.sourceText,
80 run.role,
81 run.headingLevel,
82 run.depth,
83 run.spacing,
84 run.firstLineHeadIndent,
85 run.headIndent,
86 run.paragraphSpacing,
87 ].join(":");
88}
89
90const DEFAULT_BODY_FONT_SIZE = 15;
91const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
92
93function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
94 const index = Math.max(0, Math.min(5, headingLevel - 1));
95 const configured = textStyle.headingFontSizes?.[index];
96 if (typeof configured === "number" && Number.isFinite(configured)) {
97 return configured;
98 }
99
100 const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
101 return Math.max(12, Math.round((DEFAULT_HEADING_FONT_SIZES[index] ?? 15) * scale));
102}
103
104function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
105 const isFile = run.fileIcon != null;
106 const isSkill = run.skillName != null;
107 const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
108 const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
109 const isHeading = run.role === "heading";
110 const isCodeBlock = run.role === "code-block" || run.role === "code-language";
111 const hasParagraphStyle = run.headIndent !== undefined;
112 const textDecorationLine = run.strikethrough
113 ? "line-through"
114 : run.href && !isFile
115 ? "underline"
116 : "none";
117
118 return {
119 color: isFile
120 ? textStyle.fileTextColor
121 : isSkill
122 ? textStyle.skillTextColor
123 : run.href
124 ? textStyle.linkColor
125 : isHeading
126 ? textStyle.strongColor
127 : run.role === "quote-marker"
128 ? textStyle.quoteMarkerColor
129 : run.role === "divider"
130 ? textStyle.dividerColor
131 : run.role === "code-language"
132 ? textStyle.mutedColor
133 : run.role === "list-marker"
134 ? textStyle.mutedColor
135 : isCodeBlock
136 ? textStyle.codeColor
137 : run.code
138 ? textStyle.inlineCodeColor
139 : run.bold
140 ? textStyle.strongColor
141 : textStyle.color,
142 fontFamily:
143 isFile || isSkill
144 ? textStyle.boldFontFamily
145 : run.code || isCodeBlock
146 ? MONO_FONT_FAMILY
147 : isHeading
148 ? textStyle.headingFontFamily
149 : run.bold
150 ? textStyle.boldFontFamily
151 : textStyle.fontFamily,
152 fontSize:
153 run.role === "spacer"
154 ? (run.spacing ?? 10)
155 : run.role === "list-break"
156 ? textStyle.fontSize
157 : isHeading
158 ? headingFontSize
159 : run.role === "code-language"
160 ? Math.max(10, Math.round(textStyle.fontSize * 0.73))
161 : run.code || isCodeBlock
162 ? Math.max(12, textStyle.fontSize - 2)
163 : textStyle.fontSize,
164 lineHeight:
165 run.role === "spacer"
166 ? (run.spacing ?? 10)
167 : run.role === "list-break"
168 ? textStyle.lineHeight + (run.spacing ?? 0)
169 : isHeading
170 ? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
171 : isCodeBlock
172 ? Math.max(16, textStyle.lineHeight - 2)
173 : textStyle.lineHeight,
174 fontStyle: run.italic ? "italic" : "normal",
175 fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
176 textDecorationLine,
177 backgroundColor: isCodeBlock
178 ? textStyle.codeBlockBackgroundColor
179 : parseComposerContextHref(run.href ?? "")
180 ? textStyle.codeBackgroundColor
181 : undefined,
182 ...(hasParagraphStyle
183 ? {
184 shadowColor: "transparent",
185 shadowOffset: {
186 width: run.firstLineHeadIndent ?? 0,
187 height: run.headIndent,
188 },
189 shadowRadius: PARAGRAPH_STYLE_ENCODING_OFFSET + (run.paragraphSpacing ?? 0),
190 }
191 : {}),
192 };
193}
194
195export function NativeMarkdownSelectableText(props: {
196 readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
197 readonly textStyle: NativeMarkdownTextStyle;
198 readonly onLinkPress?: (href: string) => void;
199}) {
200 const colorScheme = useColorScheme();
201 const menu = useContext(MarkdownFileContextMenuContext);
202 const contextClipboardFragment = useContext(MarkdownContextClipboardContext);
203 const contextRecords = useMemo(
204 () => decodeComposerContextFragment(contextClipboardFragment)?.records ?? [],
205 [contextClipboardFragment],
206 );
207 const containsInlineIcon = props.runs.some(
208 (run) =>
209 run.fileIcon != null ||
210 run.skillName != null ||
211 parseComposerContextHref(run.href ?? "") !== null ||
212 (run.externalHost != null && resolveMarkdownLinkIcon(run.externalHost) !== null),
213 );
214 const keyedRuns = useMemo(() => {
215 const occurrences = new Map<string, number>();
216 const prefixedExternalLinks = new Set<string>();
217 return props.runs.map((run) => {
218 const signature = runKeySignature(run);
219 const occurrence = occurrences.get(signature) ?? 0;
220 occurrences.set(signature, occurrence + 1);
221
222 let text = run.text;
223 let linkIcon = null;
224 const contextReference = parseComposerContextHref(run.href ?? "");
225 const contextRecord = contextReference
226 ? contextRecords.find((record) => record.contextId === contextReference.contextId)
227 : undefined;
228 const chip =
229 contextReference || run.skillName || run.fileIcon
230 ? {
231 ...contextChipPresentation(
232 contextReference?.kind ?? (run.skillName ? "skill" : "mention"),
233 contextRecord,
234 ),
235 label: run.skillLabel ?? run.text,
236 interactive: Boolean(run.href),
237 iconUri:
238 !contextReference && run.fileIcon
239 ? Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
240 : contextRecord?.kind === "mention" && "path" in contextRecord
241 ? Image.resolveAssetSource(
242 markdownFileIconSource(resolveMarkdownFileIcon(contextRecord.path)),
243 ).uri
244 : undefined,
245 fontSize: props.textStyle.fontSize * 0.8,
246 foreground: props.textStyle.color,
247 border: props.textStyle.contextChipBorderColor ?? props.textStyle.dividerColor,
248 }
249 : null;
250 // Android sizes the chip's inline box from the paragraph font so the line box stays
251 // the height of a plain text line; see renderContextChip.
252 const androidChip =
253 Platform.OS === "android" && chip
254 ? renderAndroidContextChip(
255 JSON.stringify({
256 ...chip,
257 text: {
258 fontFamily: props.textStyle.fontFamily,
259 fontSize: props.textStyle.fontSize,
260 },
261 }),
262 )
263 : null;
264 if (androidChip) {
265 text = "";
266 } else if (chip && Platform.OS === "ios") {
267 text = IOS_CHIP_PLACEHOLDER;
268 } else if (run.fileIcon && Platform.OS === "ios") {
269 text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
270 } else if (run.skillName && run.skillLabel) {
271 text =
272 Platform.OS === "ios"
273 ? `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`
274 : `$${run.skillName}`;
275 } else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
276 prefixedExternalLinks.add(run.href);
277 linkIcon = resolveMarkdownLinkIcon(run.externalHost);
278 if (linkIcon === null) {
279 text = `${EXTERNAL_LINK_PREFIX}${text}`;
280 } else if (Platform.OS === "ios") {
281 text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
282 }
283 }
284
285 return { key: `${signature}:${occurrence}`, run, text, linkIcon, chip, androidChip };
286 });
287 }, [props.runs, props.textStyle, contextRecords]);
288 const ranges = nativeMarkdownContextCopyRanges(
289 keyedRuns.map(({ run, text, linkIcon, androidChip }) => ({
290 run,
291 text,
292 inlineImageLength:
293 Platform.OS === "android" && (androidChip || run.fileIcon || linkIcon) ? 1 : 0,
294 })),
295 );
296 const contextClipboardConfig = ranges.length
297 ? JSON.stringify({ fragment: contextClipboardFragment, ranges })
298 : "";
299 const attachAndroidText = useCallback(
300 (textView: RNText | null) => {
301 if (Platform.OS !== "android" || !containsInlineIcon || !textView) return;
302 const reactTag = findNodeHandle(textView);
303 if (reactTag !== null) installMarkdownCopySanitizer(reactTag, contextClipboardConfig);
304 },
305 [containsInlineIcon, contextClipboardConfig],
306 );
307 // T3MarkdownText only rebuilds its attributed string during native layout. A
308 // color-only child update can otherwise leave the previous appearance cached.
309 const appearanceKey = [
310 colorScheme ?? "unspecified",
311 props.textStyle.fontSize,
312 props.textStyle.lineHeight,
313 props.textStyle.headingFontSizes?.join(","),
314 props.textStyle.color,
315 props.textStyle.strongColor,
316 props.textStyle.mutedColor,
317 props.textStyle.linkColor,
318 props.textStyle.inlineCodeColor,
319 props.textStyle.codeColor,
320 props.textStyle.codeBackgroundColor,
321 props.textStyle.codeBlockBackgroundColor,
322 props.textStyle.fileTextColor,
323 props.textStyle.skillTextColor,
324 props.textStyle.quoteMarkerColor,
325 props.textStyle.dividerColor,
326 props.textStyle.contextChipBorderColor,
327 ].join(":");
328
329 return (
330 <MarkdownTextPrimitive
331 key={appearanceKey}
332 nativeTextRef={attachAndroidText}
333 contextClipboardConfig={contextClipboardConfig}
334 accessibilityLabel={
335 Platform.OS === "android" && containsInlineIcon
336 ? props.runs.map((run) => run.skillLabel ?? run.text).join("")
337 : undefined
338 }
339 uiTextView
340 selectable
341 style={{
342 flexShrink: 1,
343 minWidth: 0,
344 color: props.textStyle.color,
345 fontFamily: props.textStyle.fontFamily,
346 fontSize: props.textStyle.fontSize,
347 lineHeight: props.textStyle.lineHeight,
348 }}
349 >
350 {keyedRuns.map(({ key, run, text, linkIcon, chip, androidChip }) => {
351 const href = run.href;
352 const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
353 const onPress = href
354 ? () => {
355 if (props.onLinkPress) props.onLinkPress(href);
356 else void Linking.openURL(href);
357 }
358 : undefined;
359 return (
360 <MarkdownTextPrimitive
361 key={key}
362 accessibilityLabel={androidChip ? chip?.label : undefined}
363 nativeID={
364 Platform.OS === "ios"
365 ? chip
366 ? `t3-chip:${JSON.stringify(chip)}`
367 : run.fileIcon
368 ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
369 : run.skillName
370 ? "t3-skill:sf:cube"
371 : linkIcon
372 ? `t3-link:${Image.resolveAssetSource(markdownLinkIconSource(linkIcon)).uri}`
373 : undefined
374 : undefined
375 }
376 contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
377 style={[
378 runStyle(run, props.textStyle),
379 chip ? { backgroundColor: "transparent" } : undefined,
380 ]}
381 onPress={onPress}
382 onContextMenuAction={
383 contextMenu && href && menu
384 ? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
385 : undefined
386 }
387 >
388 {androidChip ? (
389 // The inline box sits on the baseline and is only as tall as the font's
390 // ascent, so it never changes the line's height. The bitmap hangs off that
391 // box (views in text are not clipped) to centre the chip on the text.
392 <View
393 accessible
394 accessibilityLabel={chip?.label}
395 accessibilityRole={onPress ? "button" : "image"}
396 accessibilityActions={onPress ? [{ name: "activate" }] : undefined}
397 onAccessibilityAction={
398 onPress
399 ? (event) => {
400 if (event.nativeEvent.actionName === "activate") onPress();
401 }
402 : undefined
403 }
404 style={{ width: androidChip.width, height: androidChip.boxHeight }}
405 >
406 <Image
407 // The bitmap is measured in whole pixels but laid out in dp, so the box can
408 // round a hair narrower than the image. `cover` would crop that difference
409 // off the right-hand border; `contain` fits the whole chip instead.
410 resizeMode="contain"
411 source={{ uri: androidChip.uri }}
412 style={{
413 position: "absolute",
414 left: 0,
415 top: androidChip.offsetY,
416 width: androidChip.width,
417 height: androidChip.height,
418 }}
419 />
420 </View>
421 ) : Platform.OS === "android" && run.fileIcon ? (
422 <Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
423 ) : Platform.OS === "android" && linkIcon ? (
424 <Image
425 source={markdownLinkIconSource(linkIcon)}
426 style={styles.inlineIcon}
427 tintColor={props.textStyle.linkColor}
428 />
429 ) : null}
430 {text}
431 </MarkdownTextPrimitive>
432 );
433 })}
434 </MarkdownTextPrimitive>
435 );
436}