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 selectionColor={props.textStyle.selectionColor}
342 selectionHandleColor={props.textStyle.selectionHandleColor}
343 style={{
344 flexShrink: 1,
345 minWidth: 0,
346 color: props.textStyle.color,
347 fontFamily: props.textStyle.fontFamily,
348 fontSize: props.textStyle.fontSize,
349 lineHeight: props.textStyle.lineHeight,
350 }}
351 >
352 {keyedRuns.map(({ key, run, text, linkIcon, chip, androidChip }) => {
353 const href = run.href;
354 const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
355 const onPress = href
356 ? () => {
357 if (props.onLinkPress) props.onLinkPress(href);
358 else void Linking.openURL(href);
359 }
360 : undefined;
361 return (
362 <MarkdownTextPrimitive
363 key={key}
364 accessibilityLabel={androidChip ? chip?.label : undefined}
365 nativeID={
366 Platform.OS === "ios"
367 ? chip
368 ? `t3-chip:${JSON.stringify(chip)}`
369 : run.fileIcon
370 ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
371 : run.skillName
372 ? "t3-skill:sf:cube"
373 : linkIcon
374 ? `t3-link:${Image.resolveAssetSource(markdownLinkIconSource(linkIcon)).uri}`
375 : undefined
376 : undefined
377 }
378 contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
379 style={[
380 runStyle(run, props.textStyle),
381 chip ? { backgroundColor: "transparent" } : undefined,
382 ]}
383 onPress={onPress}
384 onContextMenuAction={
385 contextMenu && href && menu
386 ? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
387 : undefined
388 }
389 >
390 {androidChip ? (
391 // The inline box sits on the baseline and is only as tall as the font's
392 // ascent, so it never changes the line's height. The bitmap hangs off that
393 // box (views in text are not clipped) to centre the chip on the text.
394 <View
395 accessible
396 accessibilityLabel={chip?.label}
397 accessibilityRole={onPress ? "button" : "image"}
398 accessibilityActions={onPress ? [{ name: "activate" }] : undefined}
399 onAccessibilityAction={
400 onPress
401 ? (event) => {
402 if (event.nativeEvent.actionName === "activate") onPress();
403 }
404 : undefined
405 }
406 style={{ width: androidChip.width, height: androidChip.boxHeight }}
407 >
408 <Image
409 // The bitmap is measured in whole pixels but laid out in dp, so the box can
410 // round a hair narrower than the image. `cover` would crop that difference
411 // off the right-hand border; `contain` fits the whole chip instead.
412 resizeMode="contain"
413 source={{ uri: androidChip.uri }}
414 style={{
415 position: "absolute",
416 left: 0,
417 top: androidChip.offsetY,
418 width: androidChip.width,
419 height: androidChip.height,
420 }}
421 />
422 </View>
423 ) : Platform.OS === "android" && run.fileIcon ? (
424 <Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
425 ) : Platform.OS === "android" && linkIcon ? (
426 <Image
427 source={markdownLinkIconSource(linkIcon)}
428 style={styles.inlineIcon}
429 tintColor={props.textStyle.linkColor}
430 />
431 ) : null}
432 {text}
433 </MarkdownTextPrimitive>
434 );
435 })}
436 </MarkdownTextPrimitive>
437 );
438}