Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NativeMarkdownSelectableText.ios.tsx

249 lines8.5 KB

1import { createContext, useContext } from "react";
2import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
3​
4import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
5import { markdownFileIconSource } from "./markdownFileIcons";
6import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
7import type {
8 MarkdownFileContextMenu,
9 NativeMarkdownTextStyle,
10} from "./SelectableMarkdownText.types";
11​
12export interface MarkdownFileContextMenuHandlers {
13 readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
14 readonly onFileContextMenuAction: (href: string, actionId: string) => void;
16​
17/** Set by SelectableMarkdownText so file chips anywhere in the block tree get the same menu. */
18export const MarkdownFileContextMenuContext = createContext<MarkdownFileContextMenuHandlers | null>(
19 null,
20);
21​
22const EXTERNAL_LINK_PREFIX = "◉ ";
23const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
24const SKILL_ICON_PLACEHOLDER = "\uFFFC";
25const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
26​
27function runKeySignature(run: NativeMarkdownTextRun): string {
28 return [
29 run.text,
30 run.bold,
31 run.italic,
32 run.strikethrough,
33 run.code,
34 run.href,
35 run.externalHost,
36 run.fileIcon,
37 run.skillName,
38 run.skillLabel,
39 run.role,
40 run.headingLevel,
41 run.depth,
42 run.spacing,
43 run.firstLineHeadIndent,
44 run.headIndent,
45 run.paragraphSpacing,
46 ].join(":");
48​
49const DEFAULT_BODY_FONT_SIZE = 15;
50const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
51​
52function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
53 const index = Math.max(0, Math.min(5, headingLevel - 1));
54 const configured = textStyle.headingFontSizes?.[index];
55 if (typeof configured === "number" && Number.isFinite(configured)) {
56 return configured;
57 }
58​
59 const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
60 return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
62​
63function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
64 const isFile = run.fileIcon != null;
65 const isSkill = run.skillName != null;
66 const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
67 const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
68 const isHeading = run.role === "heading";
69 const isCodeBlock = run.role === "code-block" || run.role === "code-language";
70 const hasParagraphStyle = run.headIndent !== undefined;
71 const textDecorationLine = run.strikethrough
72 ? "line-through"
73 : run.href && !isFile
74 ? "underline"
75 : "none";
76​
77 return {
78 color: isFile
79 ? textStyle.fileTextColor
80 : isSkill
81 ? textStyle.skillTextColor
82 : run.href
83 ? textStyle.linkColor
84 : isHeading
85 ? textStyle.strongColor
86 : run.role === "quote-marker"
87 ? textStyle.quoteMarkerColor
88 : run.role === "divider"
89 ? textStyle.dividerColor
90 : run.role === "code-language"
91 ? textStyle.mutedColor
92 : run.role === "list-marker"
93 ? textStyle.mutedColor
94 : isCodeBlock
95 ? textStyle.codeColor
96 : run.code
97 ? textStyle.inlineCodeColor
98 : run.bold
99 ? textStyle.strongColor
100 : textStyle.color,
101 fontFamily:
102 isFile || isSkill
103 ? textStyle.boldFontFamily
104 : run.code || isCodeBlock
105 ? "ui-monospace"
106 : isHeading
107 ? textStyle.headingFontFamily
108 : run.bold
109 ? textStyle.boldFontFamily
110 : textStyle.fontFamily,
111 fontSize:
112 run.role === "spacer"
113 ? (run.spacing ?? 10)
114 : run.role === "list-break"
115 ? textStyle.fontSize
116 : isHeading
117 ? headingFontSize
118 : run.role === "code-language"
119 ? Math.max(10, Math.round(textStyle.fontSize * 0.73))
120 : run.code || isCodeBlock
121 ? Math.max(12, textStyle.fontSize - 2)
122 : textStyle.fontSize,
123 lineHeight:
124 run.role === "spacer"
125 ? (run.spacing ?? 10)
126 : run.role === "list-break"
127 ? textStyle.lineHeight + (run.spacing ?? 0)
128 : isHeading
129 ? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
130 : isCodeBlock
131 ? Math.max(16, textStyle.lineHeight - 2)
132 : textStyle.lineHeight,
133 fontStyle: run.italic ? "italic" : "normal",
134 fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
135 textDecorationLine,
136 backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
137 ...(hasParagraphStyle
138 ? {
139 shadowColor: "transparent",
140 shadowOffset: {
141 width: run.firstLineHeadIndent ?? 0,
142 height: run.headIndent,
143 },
144 shadowRadius: PARAGRAPH_STYLE_ENCODING_OFFSET + (run.paragraphSpacing ?? 0),
145 }
146 : {}),
147 };
149​
150export function NativeMarkdownSelectableText(props: {
151 readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
152 readonly textStyle: NativeMarkdownTextStyle;
153 readonly onLinkPress?: (href: string) => void;
154}) {
155 const colorScheme = useColorScheme();
156 const menu = useContext(MarkdownFileContextMenuContext);
157 const occurrences = new Map<string, number>();
158 const prefixedExternalLinks = new Set<string>();
159 const keyedRuns = props.runs.map((run) => {
160 const signature = runKeySignature(run);
161 const occurrence = occurrences.get(signature) ?? 0;
162 occurrences.set(signature, occurrence + 1);
163​
164 let text = run.text;
165 if (run.fileIcon) {
166 text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
167 } else if (run.skillName && run.skillLabel) {
168 text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
169 } else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
170 prefixedExternalLinks.add(run.href);
171 text = `${EXTERNAL_LINK_PREFIX}${text}`;
172 }
173​
174 return { key: `${signature}:${occurrence}`, run, text };
175 });
176 // T3MarkdownText only rebuilds its attributed string during native layout. A
177 // color-only child update can otherwise leave the previous appearance cached.
178 const appearanceKey = [
179 colorScheme ?? "unspecified",
180 props.textStyle.fontSize,
181 props.textStyle.lineHeight,
182 props.textStyle.headingFontSizes?.join(","),
183 props.textStyle.color,
184 props.textStyle.strongColor,
185 props.textStyle.mutedColor,
186 props.textStyle.linkColor,
187 props.textStyle.inlineCodeColor,
188 props.textStyle.codeColor,
189 props.textStyle.codeBackgroundColor,
190 props.textStyle.codeBlockBackgroundColor,
191 props.textStyle.fileTextColor,
192 props.textStyle.skillTextColor,
193 props.textStyle.quoteMarkerColor,
194 props.textStyle.dividerColor,
195 ].join(":");
196​
197 return (
198 <MarkdownTextPrimitive
199 key={appearanceKey}
200 uiTextView
201 selectable
202 style={{
203 flexShrink: 1,
204 minWidth: 0,
205 color: props.textStyle.color,
206 fontFamily: props.textStyle.fontFamily,
207 fontSize: props.textStyle.fontSize,
208 lineHeight: props.textStyle.lineHeight,
209 }}
210 >
211 {keyedRuns.map(({ key, run, text }) => {
212 const href = run.href;
213 const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
214 return (
215 <MarkdownTextPrimitive
216 key={key}
217 nativeID={
218 run.fileIcon
219 ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
220 : run.skillName
221 ? "t3-skill:sf:cube"
222 : undefined
223 }
224 contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
225 style={runStyle(run, props.textStyle)}
226 onPress={
227 href
228 ? () => {
229 if (props.onLinkPress) {
230 props.onLinkPress(href);
231 } else {
232 void Linking.openURL(href);
233 }
234 }
235 : undefined
236 }
237 onContextMenuAction={
238 contextMenu && href && menu
239 ? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
240 : undefined
241 }
242 >
243 {text}
244 </MarkdownTextPrimitive>
245 );
246 })}
247 </MarkdownTextPrimitive>
248 );