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 type TextInstance,
10 type TextStyle,
11 useColorScheme,
12 View,
13} from "react-native";
14
15import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
16import { markdownFileIconSource, markdownIconAssetUri } 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 ? markdownIconAssetUri(markdownFileIconSource(run.fileIcon))
240 : contextRecord?.kind === "mention" && "path" in contextRecord
241 ? markdownIconAssetUri(
242 markdownFileIconSource(resolveMarkdownFileIcon(contextRecord.path)),
243 )
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: TextInstance | null) => {
301 if (Platform.OS !== "android" || !containsInlineIcon || !textView) return;
302 const reactTag = findNodeHandle(textView);
303 if (typeof reactTag === "number") {
304 installMarkdownCopySanitizer(reactTag, contextClipboardConfig);
305 }
306 },
307 [containsInlineIcon, contextClipboardConfig],
308 );
309 // T3MarkdownText only rebuilds its attributed string during native layout. A
310 // color-only child update can otherwise leave the previous appearance cached.
311 const appearanceKey = [
312 colorScheme ?? "unspecified",
313 props.textStyle.fontSize,
314 props.textStyle.lineHeight,
315 props.textStyle.headingFontSizes?.join(","),
316 props.textStyle.color,
317 props.textStyle.strongColor,
318 props.textStyle.mutedColor,
319 props.textStyle.linkColor,
320 props.textStyle.inlineCodeColor,
321 props.textStyle.codeColor,
322 props.textStyle.codeBackgroundColor,
323 props.textStyle.codeBlockBackgroundColor,
324 props.textStyle.fileTextColor,
325 props.textStyle.skillTextColor,
326 props.textStyle.quoteMarkerColor,
327 props.textStyle.dividerColor,
328 props.textStyle.contextChipBorderColor,
329 ].join(":");
330
331 return (
332 <MarkdownTextPrimitive
333 key={appearanceKey}
334 nativeTextRef={attachAndroidText}
335 contextClipboardConfig={contextClipboardConfig}
336 accessibilityLabel={
337 Platform.OS === "android" && containsInlineIcon
338 ? props.runs.map((run) => run.skillLabel ?? run.text).join("")
339 : undefined
340 }
341 uiTextView
342 selectable
343 selectionColor={props.textStyle.selectionColor}
344 selectionHandleColor={props.textStyle.selectionHandleColor}
345 style={{
346 flexShrink: 1,
347 minWidth: 0,
348 color: props.textStyle.color,
349 fontFamily: props.textStyle.fontFamily,
350 fontSize: props.textStyle.fontSize,
351 lineHeight: props.textStyle.lineHeight,
352 }}
353 >
354 {keyedRuns.map(({ key, run, text, linkIcon, chip, androidChip }) => {
355 const href = run.href;
356 const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
357 const onPress = href
358 ? () => {
359 if (props.onLinkPress) props.onLinkPress(href);
360 else void Linking.openURL(href);
361 }
362 : undefined;
363 const fileIconUri = run.fileIcon
364 ? markdownIconAssetUri(markdownFileIconSource(run.fileIcon))
365 : undefined;
366 const linkIconUri = linkIcon
367 ? markdownIconAssetUri(markdownLinkIconSource(linkIcon))
368 : undefined;
369 return (
370 <MarkdownTextPrimitive
371 key={key}
372 accessibilityLabel={androidChip ? chip?.label : undefined}
373 nativeID={
374 Platform.OS === "ios"
375 ? chip
376 ? `t3-chip:${JSON.stringify(chip)}`
377 : fileIconUri
378 ? `t3-file:${fileIconUri}`
379 : run.skillName
380 ? "t3-skill:sf:cube"
381 : linkIconUri
382 ? `t3-link:${linkIconUri}`
383 : undefined
384 : undefined
385 }
386 contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
387 style={[
388 runStyle(run, props.textStyle),
389 chip ? { backgroundColor: "transparent" } : undefined,
390 ]}
391 onPress={onPress}
392 onContextMenuAction={
393 contextMenu && href && menu
394 ? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
395 : undefined
396 }
397 >
398 {androidChip ? (
399 // The inline box sits on the baseline and is only as tall as the font's
400 // ascent, so it never changes the line's height. The bitmap hangs off that
401 // box (views in text are not clipped) to centre the chip on the text.
402 <View
403 accessible
404 accessibilityLabel={chip?.label}
405 accessibilityRole={onPress ? "button" : "image"}
406 accessibilityActions={onPress ? [{ name: "activate" }] : undefined}
407 onAccessibilityAction={
408 onPress
409 ? (event) => {
410 if (event.nativeEvent.actionName === "activate") onPress();
411 }
412 : undefined
413 }
414 style={{ width: androidChip.width, height: androidChip.boxHeight }}
415 >
416 <Image
417 // The bitmap is measured in whole pixels but laid out in dp, so the box can
418 // round a hair narrower than the image. `cover` would crop that difference
419 // off the right-hand border; `contain` fits the whole chip instead.
420 resizeMode="contain"
421 source={{ uri: androidChip.uri }}
422 style={{
423 position: "absolute",
424 left: 0,
425 top: androidChip.offsetY,
426 width: androidChip.width,
427 height: androidChip.height,
428 }}
429 />
430 </View>
431 ) : Platform.OS === "android" && run.fileIcon ? (
432 <Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
433 ) : Platform.OS === "android" && linkIcon ? (
434 <Image
435 source={markdownLinkIconSource(linkIcon)}
436 style={styles.inlineIcon}
437 tintColor={props.textStyle.linkColor}
438 />
439 ) : null}
440 {text}
441 </MarkdownTextPrimitive>
442 );
443 })}
444 </MarkdownTextPrimitive>
445 );
446}