Skip to content
TypeScript

feat(mobile): make chat text selectable on Android (#8779)

Dara Adedeji09d13de43819
diff --git a/apps/mobile/modules/t3-markdown-text/android/build.gradle b/apps/mobile/modules/t3-markdown-text/android/build.gradle
new file mode 100644
index 00000000000..13584a00be4
--- /dev/null
+++ b/apps/mobile/modules/t3-markdown-text/android/build.gradle
@@ -0,0 +1,20 @@
+apply plugin: 'com.android.library'
+apply plugin: 'org.jetbrains.kotlin.android'
+
+group = 'com.t3tools.markdowntext'
+version = '0.0.0'
+
+android {
+ namespace 'expo.modules.t3markdowntext'
+ compileSdk rootProject.ext.compileSdkVersion
+
+ defaultConfig {
+ minSdkVersion rootProject.ext.minSdkVersion
+ targetSdkVersion rootProject.ext.targetSdkVersion
+ }
+}
+
+dependencies {
+ implementation project(':expo-modules-core')
+ implementation 'com.facebook.react:react-android'
+}
diff --git a/apps/mobile/modules/t3-markdown-text/android/src/main/java/expo/modules/t3markdowntext/T3MarkdownTextSelectionModule.kt b/apps/mobile/modules/t3-markdown-text/android/src/main/java/expo/modules/t3markdowntext/T3MarkdownTextSelectionModule.kt
new file mode 100644
index 00000000000..af8675831f2
--- /dev/null
+++ b/apps/mobile/modules/t3-markdown-text/android/src/main/java/expo/modules/t3markdowntext/T3MarkdownTextSelectionModule.kt
@@ -0,0 +1,93 @@
+package expo.modules.t3markdowntext
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.text.Spanned
+import android.text.style.ReplacementSpan
+import android.view.ActionMode
+import android.view.Menu
+import android.view.MenuItem
+import android.widget.TextView
+import com.facebook.react.bridge.ReactContext
+import com.facebook.react.uimanager.UIManagerHelper
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+import kotlin.math.max
+import kotlin.math.min
+
+private const val OBJECT_REPLACEMENT_CHARACTER = "\uFFFC"
+
+private fun copyTextWithoutInlineImages(
+ text: CharSequence,
+ start: Int,
+ end: Int
+): String {
+ if (text !is Spanned) return text.subSequence(start, end).toString()
+
+ return buildString {
+ for (index in start until end) {
+ val isInlineImage =
+ text[index].toString() == OBJECT_REPLACEMENT_CHARACTER &&
+ text.getSpans(index, index + 1, ReplacementSpan::class.java).isNotEmpty()
+ if (!isInlineImage) append(text[index])
+ }
+ }
+}
+
+private class SanitizingSelectionActionModeCallback(
+ private val textView: TextView,
+ private val delegate: ActionMode.Callback?
+) : ActionMode.Callback {
+ override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean =
+ delegate?.onCreateActionMode(mode, menu) ?: true
+
+ override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean =
+ delegate?.onPrepareActionMode(mode, menu) ?: false
+
+ override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
+ if (item.itemId == android.R.id.copy) {
+ val start = min(textView.selectionStart, textView.selectionEnd)
+ val end = max(textView.selectionStart, textView.selectionEnd)
+ if (start >= 0 && end > start) {
+ val originalText = textView.text.subSequence(start, end).toString()
+ val selectedText = copyTextWithoutInlineImages(textView.text, start, end)
+ if (selectedText != originalText) {
+ val clipboard =
+ textView.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
+ clipboard.setPrimaryClip(ClipData.newPlainText(null, selectedText))
+ mode.finish()
+ return true
+ }
+ }
+ }
+ return delegate?.onActionItemClicked(mode, item) ?: false
+ }
+
+ override fun onDestroyActionMode(mode: ActionMode) {
+ delegate?.onDestroyActionMode(mode)
+ }
+}
+
+class T3MarkdownTextSelectionModule : Module() {
+ override fun definition() = ModuleDefinition {
+ Name("T3MarkdownTextSelection")
+
+ Function("installCopySanitizer") { reactTag: Int ->
+ val reactContext = appContext.reactContext as? ReactContext ?: return@Function
+ reactContext.runOnUiQueueThread {
+ val textView =
+ runCatching {
+ UIManagerHelper.getUIManagerForReactTag(reactContext, reactTag)?.resolveView(reactTag)
+ }
+ .getOrNull() as? TextView ?: return@runOnUiQueueThread
+ val currentCallback = textView.customSelectionActionModeCallback
+ if (currentCallback is SanitizingSelectionActionModeCallback) {
+ return@runOnUiQueueThread
+ }
+ textView.customSelectionActionModeCallback =
+ SanitizingSelectionActionModeCallback(textView, currentCallback)
+ }
+ }
+ }
+}
diff --git a/apps/mobile/modules/t3-markdown-text/expo-module.config.json b/apps/mobile/modules/t3-markdown-text/expo-module.config.json
new file mode 100644
index 00000000000..f41f760ee7c
--- /dev/null
+++ b/apps/mobile/modules/t3-markdown-text/expo-module.config.json
@@ -0,0 +1,6 @@
+{
+ "platforms": ["android"],
+ "android": {
+ "modules": ["expo.modules.t3markdowntext.T3MarkdownTextSelectionModule"]
+ }
+}
diff --git a/apps/mobile/modules/t3-markdown-text/package.json b/apps/mobile/modules/t3-markdown-text/package.json
index 7ab3f1fbde8..1e52d7695ec 100644
--- a/apps/mobile/modules/t3-markdown-text/package.json
+++ b/apps/mobile/modules/t3-markdown-text/package.json
@@ -4,7 +4,9 @@
"private": true,
"source": "./index.ts",
"files": [
+ "android",
"assets",
+ "expo-module.config.json",
"ios",
"src",
"index.ts",
@@ -28,6 +30,7 @@
"peerDependencies": {
"@t3tools/client-runtime": "*",
"@t3tools/shared": "*",
+ "expo": "*",
"expo-asset": "*",
"expo-clipboard": "*",
"expo-haptics": "*",
diff --git a/apps/mobile/modules/t3-markdown-text/src/MarkdownTextPrimitive.tsx b/apps/mobile/modules/t3-markdown-text/src/MarkdownTextPrimitive.tsx
index 36e87ee9415..0ae9a0f7b17 100644
--- a/apps/mobile/modules/t3-markdown-text/src/MarkdownTextPrimitive.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/MarkdownTextPrimitive.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { type Ref } from "react";
import { Platform, StyleSheet, Text as RNText, type TextProps, type ViewStyle } from "react-native";
import T3MarkdownTextRunNativeComponent from "./T3MarkdownTextRunNativeComponent";
import T3MarkdownTextNativeComponent from "./T3MarkdownTextNativeComponent";
@@ -33,6 +33,7 @@ export type ContextMenuActionEvent = {
* while the React Native Text fallback reports measured `TextLayoutLine`s.
*/
export type MarkdownTextPrimitiveProps = Omit<TextProps, "onTextLayout"> & {
+ nativeTextRef?: Ref<RNText>;
uiTextView?: boolean;
contextMenuConfig?: string;
onContextMenuAction?: (event: ContextMenuActionEvent) => void;
@@ -45,7 +46,12 @@ export type MarkdownTextPrimitiveProps = Omit<TextProps, "onTextLayout"> & {
onSelectionChange?: (event: SelectionChangeEvent) => void;
};
-function MarkdownTextPrimitiveChild({ style, children, ...rest }: MarkdownTextPrimitiveProps) {
+function MarkdownTextPrimitiveChild({
+ style,
+ children,
+ nativeTextRef: _nativeTextRef,
+ ...rest
+}: MarkdownTextPrimitiveProps) {
const [isAncestor, rootStyle] = useTextAncestorContext();
// Flatten the styles, and apply the root styles when needed
@@ -97,21 +103,22 @@ function MarkdownTextPrimitiveChild({ style, children, ...rest }: MarkdownTextPr
return <>{nativeChildren}</>;
}
-function MarkdownTextPrimitiveInner(props: MarkdownTextPrimitiveProps) {
+function MarkdownTextPrimitiveInner({ nativeTextRef, ...props }: MarkdownTextPrimitiveProps) {
const [isAncestor] = useTextAncestorContext();
// Even if the uiTextView prop is set, we can still default to using
// normal selection (i.e. base RN text) if the text doesn't need to be
// selectable
if ((!props.selectable || !props.uiTextView) && !isAncestor) {
- return <RNText {...props} />;
+ return <RNText ref={nativeTextRef} {...props} />;
}
return <MarkdownTextPrimitiveChild {...props} />;
}
export function MarkdownTextPrimitive(props: MarkdownTextPrimitiveProps) {
if (Platform.OS !== "ios") {
- return <RNText {...props} />;
+ const { nativeTextRef, ...textProps } = props;
+ return <RNText ref={nativeTextRef} {...textProps} />;
}
return <MarkdownTextPrimitiveInner {...props} />;
}
diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
index b0934e873a7..348a3c489a2 100644
--- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownBlock.ios.tsx
@@ -1,5 +1,5 @@
import { createContext, useContext, useEffect, useState } from "react";
-import { Image, ScrollView, Text, useColorScheme, View } from "react-native";
+import { Image, Platform, ScrollView, Text, useColorScheme, View } from "react-native";
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import { CopyTextButton } from "./CopyTextButton";
@@ -22,6 +22,11 @@ type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
const highlightedCodeCache = new Map<string, HighlightedCode>();
const highlightedCodePromiseCache = new Map<string, Promise<HighlightedCode>>();
const HIGHLIGHTED_CODE_CACHE_LIMIT = 64;
+const MONO_FONT_FAMILY = Platform.select({
+ ios: "ui-monospace",
+ android: "monospace",
+ default: "monospace",
+});
function nodeKey(node: MarkdownNode, index: number): string {
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
@@ -171,7 +176,7 @@ function HighlightedCodeText(props: {
selectable
style={{
color: props.textStyle.codeColor,
- fontFamily: "ui-monospace",
+ fontFamily: MONO_FONT_FAMILY,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
@@ -206,7 +211,7 @@ function HighlightedCodeText(props: {
selectable
style={{
color: props.textStyle.codeColor,
- fontFamily: "ui-monospace",
+ fontFamily: MONO_FONT_FAMILY,
fontSize: codeBlockFontSize(props.textStyle),
lineHeight: codeBlockLineHeight(props.textStyle),
}}
@@ -218,7 +223,7 @@ function HighlightedCodeText(props: {
key={key}
style={{
color: token.color ?? props.textStyle.codeColor,
- fontFamily: "ui-monospace",
+ fontFamily: MONO_FONT_FAMILY,
fontStyle:
token.fontStyle !== null && (token.fontStyle & 1) === 1 ? "italic" : "normal",
fontWeight: token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
@@ -274,7 +279,7 @@ function NativeCodeBlock(props: {
style={{
flex: 1,
color: props.textStyle.mutedColor,
- fontFamily: "ui-monospace",
+ fontFamily: MONO_FONT_FAMILY,
fontSize: codeBlockFontSize(props.textStyle),
}}
>
@@ -294,6 +299,7 @@ function NativeCodeBlock(props: {
<ScrollView
horizontal
bounces={false}
+ nestedScrollEnabled={Platform.OS === "android"}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
>
@@ -330,7 +336,12 @@ function NativeTable(props: {
}) {
const rows = collectTableRows(props.node);
return (
- <ScrollView horizontal bounces={false} showsHorizontalScrollIndicator={false}>
+ <ScrollView
+ horizontal
+ bounces={false}
+ nestedScrollEnabled={Platform.OS === "android"}
+ showsHorizontalScrollIndicator={false}
+ >
<View
style={{
borderColor: props.textStyle.dividerColor,
diff --git a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
index ea4bd0f2488..590a2fb1bd1 100644
--- a/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
+++ b/apps/mobile/modules/t3-markdown-text/src/NativeMarkdownSelectableText.ios.tsx
@@ -1,5 +1,14 @@
-import { createContext, useContext } from "react";
-import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
+import { createContext, useCallback, useContext } from "react";
+import {
+ findNodeHandle,
+ Image,
+ Linking,
+ Platform,
+ StyleSheet,
+ Text as RNText,
+ type TextStyle,
+ useColorScheme,
+} from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource } from "./markdownFileIcons";
@@ -8,6 +17,7 @@ import type {
MarkdownFileContextMenu,
NativeMarkdownTextStyle,
} from "./SelectableMarkdownText.types";
+import { installMarkdownCopySanitizer } from "./T3MarkdownTextSelectionModule";
export interface MarkdownFileContextMenuHandlers {
readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
@@ -23,6 +33,19 @@ const EXTERNAL_LINK_PREFIX = "◉ ";
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
+const MONO_FONT_FAMILY = Platform.select({
+ ios: "ui-monospace",
+ android: "monospace",
+ default: "monospace",
+});
+const styles = StyleSheet.create({
+ inlineIcon: {
+ width: 14,
+ height: 14,
+ marginHorizontal: 3,
+ transform: [{ translateY: 2 }],
+ },
+});
function runKeySignature(run: NativeMarkdownTextRun): string {
return [
@@ -102,7 +125,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
isFile || isSkill
? textStyle.boldFontFamily
: run.code || isCodeBlock
- ? "ui-monospace"
+ ? MONO_FONT_FAMILY
: isHeading
? textStyle.headingFontFamily
: run.bold
@@ -154,6 +177,19 @@ export function NativeMarkdownSelectableText(props: {
}) {
const colorScheme = useColorScheme();
const menu = useContext(MarkdownFileContextMenuContext);
+ const containsInlineFileIcon = props.runs.some((run) => run.fileIcon != null);
+ const attachAndroidText = useCallback(
+ (textView: RNText | null) => {
+ if (Platform.OS !== "android" || !containsInlineFileIcon || textView === null) {
+ return;
+ }
+ const reactTag = findNodeHandle(textView);
+ if (reactTag !== null) {
+ installMarkdownCopySanitizer(reactTag);
+ }
+ },
+ [containsInlineFileIcon],
+ );
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
const keyedRuns = props.runs.map((run) => {
@@ -162,10 +198,13 @@ export function NativeMarkdownSelectableText(props: {
occurrences.set(signature, occurrence + 1);
let text = run.text;
- if (run.fileIcon) {
+ if (run.fileIcon && Platform.OS === "ios") {
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
} else if (run.skillName && run.skillLabel) {
- text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
+ text =
+ Platform.OS === "ios"
+ ? `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`
+ : `$${run.skillName}`;
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
prefixedExternalLinks.add(run.href);
text = `${EXTERNAL_LINK_PREFIX}${text}`;
@@ -197,6 +236,7 @@ export function NativeMarkdownSelectableText(props: {
return (
<MarkdownTextPrimitive
key={appearanceKey}
+ nativeTextRef={attachAndroidText}
uiTextView
selectable
style={{
@@ -215,11 +255,13 @@ export function NativeMarkdownSelectableText(props: {
<MarkdownTextPrimitive
key={key}
nativeID={
- run.fileIcon
- ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
- : run.skillName
- ? "t3-skill:sf:cube"
- : undefined
+ Platform.OS === "ios"
+ ? run.fileIcon
+ ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
+ : run.skillName
+ ? "t3-skill:sf:cube"
+ : undefined
+ : undefined
}
contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
style={runStyle(run, props.textStyle)}
@@ -240,6 +282,9 @@ export function NativeMarkdownSelectableText(props: {
: undefined
}
>
+ {Platform.OS === "android" && run.fileIcon ? (
+ <Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
+ ) : null}
{text}
</MarkdownTextPrimitive>
);
diff --git a/apps/mobile/modules/t3-markdown-text/src/T3MarkdownTextSelectionModule.ts b/apps/mobile/modules/t3-markdown-text/src/T3MarkdownTextSelectionModule.ts
new file mode 100644
index 00000000000..4df810abd35
--- /dev/null
+++ b/apps/mobile/modules/t3-markdown-text/src/T3MarkdownTextSelectionModule.ts
@@ -0,0 +1,12 @@
+import { requireOptionalNativeModule } from "expo";
+
+interface T3MarkdownTextSelectionNativeModule {
+ readonly installCopySanitizer: (reactTag: number) => void;
+}
+
+const nativeModule =
+ requireOptionalNativeModule<T3MarkdownTextSelectionNativeModule>("T3MarkdownTextSelection");
+
+export function installMarkdownCopySanitizer(reactTag: number): void {
+ nativeModule?.installCopySanitizer(reactTag);
+}
diff --git a/apps/mobile/src/native/SelectableMarkdownText.android.tsx b/apps/mobile/src/native/SelectableMarkdownText.android.tsx
new file mode 100644
index 00000000000..a59a039cbc9
--- /dev/null
+++ b/apps/mobile/src/native/SelectableMarkdownText.android.tsx
@@ -0,0 +1,24 @@
+import {
+ SelectableMarkdownText as T3SelectableMarkdownText,
+ type SelectableMarkdownTextProps,
+} from "@t3tools/mobile-markdown-text/renderer";
+
+import { highlightCodeSnippet } from "../features/review/shikiReviewHighlighter";
+
+type MobileSelectableMarkdownTextProps = Omit<SelectableMarkdownTextProps, "highlightCode">;
+
+export type {
+ MarkdownImageRequest,
+ NativeMarkdownTextStyle,
+ SelectableMarkdownSkill,
+} from "@t3tools/mobile-markdown-text/types";
+
+// The renderer falls back to React Native Text outside iOS, so Android can use
+// the same Markdown chunking while retaining native text selection.
+export function hasNativeSelectableMarkdownText(): boolean {
+ return true;
+}
+
+export function SelectableMarkdownText(props: MobileSelectableMarkdownTextProps) {
+ return <T3SelectableMarkdownText {...props} highlightCode={highlightCodeSnippet} />;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 032a1e05ff6..2a7e45ca857 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -278,7 +278,7 @@ importers:
version: link:../../packages/contracts
'@t3tools/mobile-markdown-text':
specifier: file:./modules/t3-markdown-text
- version: file:apps/mobile/modules/t3-markdown-text(cd0d4cdec0d5bee3af406af520908919)
+ version: file:apps/mobile/modules/t3-markdown-text(eb96cd030e772ab91fe21f812240338a)
'@t3tools/mobile-review-diff-native':
specifier: file:./modules/t3-review-diff
version: file:apps/mobile/modules/t3-review-diff
@@ -4513,6 +4513,7 @@ packages:
peerDependencies:
'@t3tools/client-runtime': '*'
'@t3tools/shared': '*'
+ expo: '*'
expo-asset: '*'
expo-clipboard: '*'
expo-haptics: '*'
@@ -14372,10 +14373,11 @@ snapshots:
dependencies:
defer-to-connect: 2.0.1
- '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(cd0d4cdec0d5bee3af406af520908919)':
+ '@t3tools/mobile-markdown-text@file:apps/mobile/modules/t3-markdown-text(eb96cd030e772ab91fe21f812240338a)':
dependencies:
'@t3tools/client-runtime': link:packages/client-runtime
'@t3tools/shared': link:packages/shared
+ expo: 57.0.18(f9c992a5d7c53d81398568d3950992dc)
expo-haptics: 57.0.2([email protected])