feat(mobile): replace custom Markdown rendering with Enriched (#16979)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-10-11 17:22:00 -07:00
1 parent 6ba6a0daf4
commit c5d7309152
177 files changed
+3039 -8567

No files matched your search

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 870 B

After

Width:  |  Height:  |  Size: 870 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 534 B

After

Width:  |  Height:  |  Size: 534 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 620 B

After

Width:  |  Height:  |  Size: 620 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 497 B

After

Width:  |  Height:  |  Size: 497 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 676 B

After

Width:  |  Height:  |  Size: 676 B

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

+3
View File
@@ -0,0 +1,3 @@
The Enriched Markdown tarball comes from the [`fork/t3-mobile` branch](https://github.com/juliusmarminge/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. File/skill link recognition, back navigation from horizontal blocks, table-image presses, and code-block headers use upstream implementations. The remaining fork adds clipboard metadata, parsed asset manifests, signed image source resolution, React media slots, and development-host autolinks.
To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Bump the fork package version for each replacement, update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
@@ -20,7 +20,6 @@ android {
dependencies {
implementation project(':expo-modules-core')
implementation project(':t3tools-mobile-markdown-text')
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
}
@@ -29,7 +29,6 @@ import android.widget.EditText
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
import expo.modules.t3markdowntext.T3ContextChip
import org.json.JSONObject
import kotlin.math.max
@@ -1,4 +1,4 @@
package expo.modules.t3markdowntext
package expo.modules.t3composereditor
import android.graphics.Canvas
import android.graphics.Color
@@ -1,32 +0,0 @@
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
testOptions {
unitTests.includeAndroidResources = true
}
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
dependencies {
implementation project(':expo-modules-core')
implementation 'com.facebook.react:react-android'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
}
tasks.withType(Test).configureEach {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(21)
}
}
@@ -1,302 +0,0 @@
package expo.modules.t3markdowntext
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Build
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ReplacementSpan
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import android.util.Base64
import android.util.LruCache
import com.facebook.react.bridge.ReactContext
import com.facebook.react.common.assets.ReactFontManager
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
import org.json.JSONObject
import org.json.JSONArray
import java.net.URLEncoder
import java.io.ByteArrayOutputStream
import kotlin.math.ceil
private const val OBJECT_REPLACEMENT_CHARACTER = "\uFFFC"
// Match React Native's measurement buffer. Android orders tied line-height
// spans differently in SpannableString, shifting inline images once RN's
// span priorities are exhausted.
private object MarkdownSpannableFactory : Spannable.Factory() {
override fun newSpannable(source: CharSequence): Spannable =
SpannableStringBuilder(source)
}
internal fun copyTextWithoutInlineImages(
text: CharSequence,
start: Int,
end: Int
): String {
if (text !is Spanned) return text.subSequence(start, end).toString()
fun isInlineImage(index: Int): Boolean =
index >= 0 && text[index].toString() == OBJECT_REPLACEMENT_CHARACTER &&
text.getSpans(index, index + 1, ReplacementSpan::class.java).isNotEmpty()
return buildString {
for (index in start until end) {
// The renderer inserts one NBSP after each image to keep its label on the same line.
// Inspect the original text even when selection starts after the image.
val isIconSpacer = text[index] == '\u00A0' && isInlineImage(index - 1)
if (!isInlineImage(index) && !isIconSpacer) append(text[index])
}
}
}
private fun canonicalSelection(
originalText: String,
start: Int,
end: Int,
ranges: JSONArray?
): String? {
if (ranges == null) return null
val canonical = StringBuilder(originalText)
var hasContext = false
for (index in ranges.length() - 1 downTo 0) {
val range = ranges.optJSONObject(index) ?: continue
val first = max(start, range.optInt("start"))
val last = min(end, range.optInt("end"))
if (last > first) {
canonical.replace(first - start, last - start, range.optString("text"))
hasContext = true
}
}
return if (hasContext) canonical.toString().replace(OBJECT_REPLACEMENT_CHARACTER, "") else null
}
private fun selectedContextRecords(records: JSONArray, selectedText: String): JSONArray {
val ids = mutableSetOf<String>()
for (index in 0 until records.length()) {
val record = records.getJSONObject(index)
if (selectedText.contains("/${record.optString("contextId")})")) {
ids.add(record.optString("contextId"))
if (record.has("screenshotContextId")) ids.add(record.getString("screenshotContextId"))
}
}
val copied = JSONArray()
for (index in 0 until records.length()) {
val record = records.getJSONObject(index)
if (ids.contains(record.optString("contextId"))) copied.put(record)
}
return copied
}
private fun contextClipData(selectedText: String, fragment: String): ClipData {
val payload = runCatching { JSONObject(fragment) }.getOrNull()
val records = payload?.optJSONArray("records")
val copied = records?.let { selectedContextRecords(it, selectedText) }
if (payload == null || copied == null || copied.length() == 0) {
return ClipData.newPlainText(null, selectedText)
}
payload.put("records", copied)
val attribute = URLEncoder.encode(payload.toString(), "UTF-8").replace("+", "%20")
val escaped = selectedText.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
return ClipData.newHtmlText(
null,
selectedText,
"<pre data-t3-context-fragment=\"$attribute\">$escaped</pre>"
)
}
private class SanitizingSelectionActionModeCallback(
private val textView: TextView,
private val delegate: ActionMode.Callback?,
var contextClipboardConfig: String
) : 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 && copySelection()) {
mode.finish()
return true
}
return delegate?.onActionItemClicked(mode, item) ?: false
}
private fun copySelection(): Boolean {
val start = min(textView.selectionStart, textView.selectionEnd)
val end = max(textView.selectionStart, textView.selectionEnd)
if (start < 0 || end <= start) return false
val originalText = textView.text.subSequence(start, end).toString()
val config = runCatching { JSONObject(contextClipboardConfig) }.getOrNull()
val canonical = canonicalSelection(originalText, start, end, config?.optJSONArray("ranges"))
val selectedText = canonical ?: copyTextWithoutInlineImages(textView.text, start, end)
val handled = canonical != null || selectedText != originalText
if (handled) {
val clipboard =
textView.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = if (canonical != null) {
contextClipData(selectedText, config?.optString("fragment") ?: "")
} else {
ClipData.newPlainText(null, selectedText)
}
clipboard.setPrimaryClip(clip)
}
return handled
}
override fun onDestroyActionMode(mode: ActionMode) {
delegate?.onDestroyActionMode(mode)
}
}
internal fun applySelectionHandleColor(textView: TextView, color: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
textView.textSelectHandle?.mutate()?.apply { setTint(color) }?.let(textView::setTextSelectHandle)
textView.textSelectHandleLeft?.mutate()?.apply {
setTint(color)
}?.let(textView::setTextSelectHandleLeft)
textView.textSelectHandleRight?.mutate()?.apply {
setTint(color)
}?.let(textView::setTextSelectHandleRight)
}
class T3MarkdownTextSelectionModule : Module() {
private val chipImages = LruCache<String, Map<String, Any>>(128)
/**
* Metrics of the paragraph font a chip sits in, so the inline box it reports can be sized
* from the same ascent and descent the surrounding text lays out with.
*/
private fun paragraphFontMetrics(text: JSONObject?, scale: Float): Paint.FontMetricsInt =
TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = (text?.optDouble("fontSize", 15.0)?.toFloat() ?: 15f).coerceIn(6f, 80f) * scale
val fontFamily = text?.optString("fontFamily").orEmpty()
typeface = if (fontFamily.isEmpty()) {
Typeface.DEFAULT
} else {
ReactFontManager.getInstance()
.getTypeface(fontFamily, Typeface.NORMAL, appContext.reactContext?.assets)
}
}.fontMetricsInt
private fun setSelectionHandleColor(reactTag: Int, color: Int) {
val reactContext = appContext.reactContext as? ReactContext ?: return
reactContext.runOnUiQueueThread {
val textView = runCatching {
UIManagerHelper.getUIManagerForReactTag(reactContext, reactTag)?.resolveView(reactTag)
}.getOrNull() as? TextView ?: return@runOnUiQueueThread
applySelectionHandleColor(textView, color)
}
}
override fun definition() = ModuleDefinition {
Name("T3MarkdownTextSelection")
Function("setSelectionHandleColor") { reactTag: Int, color: Int ->
setSelectionHandleColor(reactTag, color)
}
Function("renderContextChip") { payloadJson: String ->
val resources = appContext.reactContext?.resources ?: return@Function null
val metrics = resources.displayMetrics
val fontScale = resources.configuration.fontScale
val key = "${metrics.density}:$fontScale:${metrics.widthPixels}:$payloadJson"
chipImages.get(key)?.let { return@Function it }
val payload = JSONObject(payloadJson)
val chip = T3ContextChip(
content = T3ContextChip.Content(
label = payload.optString("label").take(4096),
symbol = payload.optString("symbol", "doc")
),
// The line box around the chip is measured with `fontScale` below, so the chip has to
// carry it too, or it shrinks against the words beside it at a larger text size.
fontSize =
payload.optDouble("fontSize", 12.0).toFloat().coerceIn(10f, 40f) *
metrics.density * fontScale,
colors = T3ContextChip.Colors(
accent = T3ContextChip.color(payload.optString("accent"), Color.GRAY),
foreground = T3ContextChip.color(payload.optString("foreground"), Color.BLACK),
border = T3ContextChip.color(payload.optString("border"), Color.GRAY)
),
maximumWidth = (metrics.widthPixels - 80 * metrics.density).coerceAtLeast(100f),
density = metrics.density,
)
// toInt() truncates, so a fractional pixel of the chip would fall outside the bitmap
// and take the right-hand border with it. Round up: a spare column costs nothing.
// One spare pixel of transparency on each side. Whatever rounding happens between the
// bitmap's pixels and the box's dp then falls on padding instead of on the border.
val bleed = 1
val bitmap = Bitmap.createBitmap(
ceil(chip.width).toInt() + bleed * 2,
ceil(chip.height).toInt() + bleed * 2,
Bitmap.Config.ARGB_8888
)
chip.draw(Canvas(bitmap), bleed.toFloat(), bleed.toFloat())
val bytes = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes)
bitmap.recycle()
// React Native sits an inline view's box on the text baseline and grows the line's
// ascent to fit it, so a box as tall as the chip lifts the chip above the words and
// pushes the baseline down. Report a box no taller than the paragraph font's ascent,
// which leaves the line exactly as tall as a line of plain text, plus where inside
// that box the bitmap must sit so the chip centres on the font's ascent/descent box:
// the same rule the composer's ReplacementSpan uses to draw its chips.
val lineMetrics = paragraphFontMetrics(
payload.optJSONObject("text"),
fontScale * metrics.density,
)
val ascent = -lineMetrics.ascent
val descent = lineMetrics.descent
val bitmapWidth = ceil(chip.width) + bleed * 2
val bitmapHeight = ceil(chip.height) + bleed * 2
val result = mapOf<String, Any>(
"uri" to
"data:image/png;base64,${Base64.encodeToString(bytes.toByteArray(), Base64.NO_WRAP)}",
// Layout rounds dp back to whole pixels. Reporting a hair less than the bitmap lets
// that rounding land inside the image and crop its right-hand border, so round the
// box up: an extra fraction of a pixel is invisible, a missing border is not.
"width" to bitmapWidth / metrics.density,
"height" to bitmapHeight / metrics.density,
"boxHeight" to ascent / metrics.density,
"offsetY" to (ascent + descent - bitmapHeight) / 2f / metrics.density,
)
chipImages.put(key, result)
result
}
Function("installCopySanitizer") { reactTag: Int, contextClipboardConfig: String ->
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) {
currentCallback.contextClipboardConfig = contextClipboardConfig
return@runOnUiQueueThread
}
textView.setSpannableFactory(MarkdownSpannableFactory)
textView.customSelectionActionModeCallback =
SanitizingSelectionActionModeCallback(textView, currentCallback, contextClipboardConfig)
}
}
}
}
@@ -1,67 +0,0 @@
package expo.modules.t3markdowntext
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.widget.TextView
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [36], manifest = Config.NONE)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class MarkdownSelectionColorTest {
private fun textView() = TextView(RuntimeEnvironment.getApplication()).apply {
setTextSelectHandle(ColorDrawable(Color.WHITE))
setTextSelectHandleLeft(ColorDrawable(Color.WHITE))
setTextSelectHandleRight(ColorDrawable(Color.WHITE))
}
private fun renderedColor(drawable: Drawable?): Int {
requireNotNull(drawable)
val bitmap = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)
drawable.setBounds(0, 0, 4, 4)
drawable.draw(Canvas(bitmap))
val color = bitmap.getPixel(2, 2)
bitmap.recycle()
return color
}
@Test
fun retintsAllHandlesWhenTheThemeChangesWithoutChangingTheHighlight() {
val text = textView()
val highlight = 0x52FF0088
text.highlightColor = highlight
for (color in listOf(Color.MAGENTA, Color.GREEN, Color.MAGENTA)) {
applySelectionHandleColor(text, color)
assertEquals(color, renderedColor(text.textSelectHandle))
assertEquals(color, renderedColor(text.textSelectHandleLeft))
assertEquals(color, renderedColor(text.textSelectHandleRight))
assertEquals(highlight, text.highlightColor)
}
}
@Test
fun doesNotTintOtherTextViewsSharingDrawableState() {
val original = ColorDrawable(Color.WHITE)
val first = textView().apply {
setTextSelectHandleLeft(original.constantState!!.newDrawable())
}
val second = textView().apply {
setTextSelectHandleLeft(original.constantState!!.newDrawable())
}
applySelectionHandleColor(first, Color.MAGENTA)
assertEquals(Color.MAGENTA, renderedColor(first.textSelectHandleLeft))
assertEquals(Color.WHITE, renderedColor(second.textSelectHandleLeft))
}
}
@@ -1,48 +0,0 @@
package expo.modules.t3markdowntext
import android.graphics.drawable.ColorDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ImageSpan
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [36], manifest = Config.NONE)
class MarkdownSelectionCopyTest {
private fun withIcon(value: String): SpannableString = SpannableString(value).apply {
val index = value.indexOf('\uFFFC')
setSpan(ImageSpan(ColorDrawable()), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
@Test
fun removesIconAndInjectedSpacer() {
val text = withIcon("\uFFFC\u00A0main.go:12 starts the server.")
assertEquals("main.go:12 starts the server.", copyTextWithoutInlineImages(text, 0, text.length))
}
@Test
fun removesSpacerWhenSelectionStartsAfterIcon() {
val text = withIcon("\uFFFC\u00A0main.go:12 starts the server.")
assertEquals("main.go:12", copyTextWithoutInlineImages(text, 1, 12))
}
@Test
fun preservesAuthoredWhitespaceAndLiteralObjectCharacters() {
val text = withIcon("before\u00A0 \uFFFC\u00A0\u00A0 main.go after\u00A0\uFFFC\u00A0")
assertEquals(
"before\u00A0 \u00A0 main.go after\u00A0\uFFFC\u00A0",
copyTextWithoutInlineImages(text, 0, text.length)
)
}
@Test
fun preservesTextWithoutImageSpans() {
val text = "\uFFFC\u00A0main.go"
assertEquals(text, copyTextWithoutInlineImages(text, 0, text.length))
assertEquals(text, copyTextWithoutInlineImages(SpannableString(text), 0, text.length))
}
}
@@ -1,6 +0,0 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.t3markdowntext.T3MarkdownTextSelectionModule"]
}
}
@@ -1,29 +0,0 @@
export { markdownFileIconSource } from "./src/markdownFileIcons";
export {
resolveMarkdownFileIcon,
resolveMarkdownLinkPresentation,
type MarkdownFileIcon,
type MarkdownLinkPresentation,
} from "./src/markdownLinks";
export {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
type NativeMarkdownDocumentChunk,
type NativeMarkdownTextRun,
} from "./src/nativeMarkdownText";
export { MarkdownTextPrimitive } from "./src/MarkdownTextPrimitive";
export {
SelectableMarkdownText,
type MarkdownCodeHighlighter,
type MarkdownHighlightedToken,
} from "./src/SelectableMarkdownText";
export type {
MarkdownFileContextMenu,
MarkdownFileContextMenuAction,
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
SelectableMarkdownTextProps,
} from "./src/SelectableMarkdownText.types";
@@ -1,162 +0,0 @@
#pragma once
#import <UIKit/UIKit.h>
// Used by both the shadow measurement and UITextView rendering paths.
static NSDictionary *T3ContextChipPayload(NSString *uri)
{
if (![uri hasPrefix:@"chip:"]) return nil;
NSData *data = [[uri substringFromIndex:5] dataUsingEncoding:NSUTF8StringEncoding];
id payload = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (![payload isKindOfClass:NSDictionary.class]) return nil;
// Every consumer draws or substitutes `label`; a missing or non-string one would raise inside
// `replaceCharactersInRange:withString:` while a message is rendering.
if (![payload[@"label"] isKindOfClass:NSString.class]) return nil;
return payload;
}
static UIColor *T3ContextChipColor(NSString *hex)
{
unsigned int rgb = 0;
if (![hex isKindOfClass:NSString.class] || hex.length != 7) return UIColor.labelColor;
[[NSScanner scannerWithString:[hex substringFromIndex:1]] scanHexInt:&rgb];
return [UIColor colorWithRed:((rgb >> 16) & 255) / 255.0
green:((rgb >> 8) & 255) / 255.0
blue:(rgb & 255) / 255.0 alpha:1];
}
static UIColor *T3ContextChipBlend(UIColor *accent, UIColor *base, CGFloat weight)
{
CGFloat ar = 0, ag = 0, ab = 0, aa = 0, br = 0, bg = 0, bb = 0, ba = 0;
[accent getRed:&ar green:&ag blue:&ab alpha:&aa];
[base getRed:&br green:&bg blue:&bb alpha:&ba];
return [UIColor colorWithRed:ar * weight + br * (1 - weight)
green:ag * weight + bg * (1 - weight)
blue:ab * weight + bb * (1 - weight)
alpha:aa * weight + ba * (1 - weight)];
}
// Some chip glyphs have no SF Symbol that reads correctly: the pull request one would land on
// `arrow.triangle.branch`, a road-sign fork that says "branch", not "pull request". Draw those
// from the same lucide geometry web and Android use so one chip looks alike on every surface.
static UIImage *T3ContextChipVectorIcon(NSString *symbol, CGFloat size, UIColor *color)
{
if (![symbol isEqualToString:@"git-pull-request"]) return nil;
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc]
initWithSize:CGSizeMake(size, size)];
return [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
CGFloat s = size / 24.0; // lucide authors on a 24pt grid.
UIBezierPath *path = [UIBezierPath bezierPath];
[path appendPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(18 * s, 18 * s)
radius:3 * s startAngle:0
endAngle:M_PI * 2 clockwise:YES]];
[path appendPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(6 * s, 6 * s)
radius:3 * s startAngle:0
endAngle:M_PI * 2 clockwise:YES]];
[path moveToPoint:CGPointMake(13 * s, 6 * s)];
[path addLineToPoint:CGPointMake(16 * s, 6 * s)];
[path addCurveToPoint:CGPointMake(18 * s, 8 * s)
controlPoint1:CGPointMake(17.1 * s, 6 * s)
controlPoint2:CGPointMake(18 * s, 6.9 * s)];
[path addLineToPoint:CGPointMake(18 * s, 15 * s)];
[path moveToPoint:CGPointMake(6 * s, 9 * s)];
[path addLineToPoint:CGPointMake(6 * s, 21 * s)];
path.lineWidth = 2 * s;
path.lineCapStyle = kCGLineCapRound;
path.lineJoinStyle = kCGLineJoinRound;
[color setStroke];
[path stroke];
}];
}
// Centres the chip on the run font's ascent/descent box, the rule the composer span and
// Android use, so the chip lands in the same place beside the words on every surface.
static inline CGRect T3ContextChipBounds(UIFont *font, CGSize size)
{
CGFloat y = font != nil ? (font.ascender + font.descender - size.height) / 2 : -3;
return CGRectMake(0, y, size.width, size.height);
}
// A bare attachment string carries none of the run's attributes. Losing the paragraph
// style at a paragraph's first character drops its line height, and losing the font lets
// a chip-only line shrink to the bitmap, so the placeholder keeps both, plus the run
// colour so a later re-apply (after an image loads) still tints with it.
static inline NSAttributedString *T3MarkdownTextAttachmentString(
NSTextAttachment *attachment, NSDictionary<NSAttributedStringKey, id> *runAttributes)
{
NSMutableAttributedString *string =
[[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
for (NSAttributedStringKey key in
@[
NSFontAttributeName, NSParagraphStyleAttributeName, NSForegroundColorAttributeName,
NSBaselineOffsetAttributeName
]) {
id value = runAttributes[key];
if (value != nil) {
[string addAttribute:key value:value range:NSMakeRange(0, string.length)];
}
}
return string;
}
static UIFont *T3ContextChipFont(NSDictionary *payload)
{
CGFloat size = MAX(10, MIN(40, [payload[@"fontSize"] doubleValue]));
size *= payload[@"fontSizeMultiplier"] != nil ? [payload[@"fontSizeMultiplier"] doubleValue] : 1;
return [UIFont fontWithName:@"DMSans-Medium" size:size]
?: [UIFont systemFontOfSize:size weight:UIFontWeightMedium];
}
static inline CGSize T3ContextChipSize(NSDictionary *payload, CGFloat maximumWidth)
{
UIFont *font = T3ContextChipFont(payload);
NSString *label = payload[@"label"];
CGFloat textWidth = [label sizeWithAttributes:@{ NSFontAttributeName: font }].width;
return CGSizeMake(MIN(maximumWidth, ceil(textWidth + font.pointSize * 2.5)),
ceil(font.pointSize * 1.41));
}
static inline UIImage *T3ContextChipImage(NSDictionary *payload, CGSize size, UIImage *fileIcon)
{
static NSCache<NSString *, UIImage *> *cache;
static dispatch_once_t once;
dispatch_once(&once, ^{ cache = [NSCache new]; cache.countLimit = 256; });
NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:NSJSONWritingSortedKeys error:nil];
NSString *key = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
key = [key stringByAppendingString:NSStringFromCGSize(size)];
if (fileIcon != nil) key = [key stringByAppendingString:@":file-icon"];
UIImage *cached = [cache objectForKey:key];
if (cached) return cached;
UIFont *font = T3ContextChipFont(payload);
CGFloat em = font.pointSize;
UIColor *accent = T3ContextChipColor(payload[@"accent"]);
UIColor *foreground = T3ContextChipBlend(accent, T3ContextChipColor(payload[@"foreground"]), 0.22);
UIColor *border = T3ContextChipBlend(accent, T3ContextChipColor(payload[@"border"]), 0.34);
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:
CGRectInset(CGRectMake(0, 0, size.width, size.height), 0.5, 0.5)
cornerRadius:em * 0.5];
[[accent colorWithAlphaComponent:0.11] setFill];
[path fill];
[border setStroke];
path.lineWidth = 1;
[path stroke];
CGFloat iconSize = em * 1.17;
UIImage *icon = fileIcon
?: T3ContextChipVectorIcon(payload[@"symbol"], iconSize, foreground)
?: [[UIImage systemImageNamed:payload[@"symbol"]
withConfiguration:[UIImageSymbolConfiguration configurationWithPointSize:em weight:UIImageSymbolWeightMedium]]
imageWithTintColor:foreground renderingMode:UIImageRenderingModeAlwaysOriginal];
[icon drawInRect:CGRectMake(em * 0.5, (size.height - iconSize) / 2, iconSize, iconSize)];
NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
paragraph.lineBreakMode = NSLineBreakByTruncatingMiddle;
CGFloat x = em * 2;
[payload[@"label"] drawInRect:CGRectMake(x, (size.height - font.lineHeight) / 2,
MAX(0, size.width - x - em * 0.5), font.lineHeight)
withAttributes:@{ NSFontAttributeName: font, NSForegroundColorAttributeName: foreground,
NSParagraphStyleAttributeName: paragraph }];
}];
[cache setObject:image forKey:key];
return image;
}
@@ -1,839 +0,0 @@
#import "T3MarkdownText.h"
#import "T3MarkdownTextShadowNode.h"
#import "T3MarkdownTextComponentDescriptor.h"
#import "T3MarkdownTextRun.h"
#import "T3ContextChip.h"
#import <React/RCTConversions.h>
#import <objc/runtime.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
#import <React/RCTFabricComponentsPlugins.h>
using namespace facebook::react;
@interface T3ContextChipAccessibilityElement : UIAccessibilityElement
@property(nonatomic, weak) T3MarkdownTextRun *run;
@end
@implementation T3ContextChipAccessibilityElement
- (BOOL)accessibilityActivate
{
if (self.run == nil) return NO;
[self.run onPress];
return YES;
}
@end
/** Preserve canonical references and their payload when copying a native text selection. */
@interface T3ContextCopyTextView : UITextView
@property(nonatomic, copy) NSDictionary *contextClipboardConfig;
@end
@implementation T3ContextCopyTextView
// Read-only text still supports selecting the entire document after selecting a word.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(selectAll:)) {
return self.selectable && self.text.length > 0 && self.selectedRange.length < self.text.length;
}
return [super canPerformAction:action withSender:sender];
}
- (void)copy:(id)sender
{
NSRange selected = self.selectedRange;
NSArray *ranges = self.contextClipboardConfig[@"ranges"];
if (selected.location == NSNotFound || selected.length == 0 || NSMaxRange(selected) > self.text.length || ranges.count == 0) {
[super copy:sender];
return;
}
NSMutableString *text = [[self.text substringWithRange:selected] mutableCopy];
BOOL hasContext = NO;
for (NSDictionary *range in [ranges reverseObjectEnumerator]) {
NSUInteger start = [range[@"start"] unsignedIntegerValue];
NSUInteger end = [range[@"end"] unsignedIntegerValue];
if (end <= start || end > self.text.length) continue;
NSRange overlap = NSIntersectionRange(selected, NSMakeRange(start, end - start));
if (overlap.length == 0 || ![range[@"text"] isKindOfClass:NSString.class]) continue;
[text replaceCharactersInRange:NSMakeRange(overlap.location - selected.location, overlap.length) withString:range[@"text"]];
hasContext = YES;
}
if (!hasContext) { [super copy:sender]; return; }
[text replaceOccurrencesOfString:@"\uFFFC\u00A0" withString:@"" options:0 range:NSMakeRange(0, text.length)];
NSString *fragment = self.contextClipboardConfig[@"fragment"];
NSMutableDictionary *payload = [[NSJSONSerialization JSONObjectWithData:[fragment dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil] mutableCopy];
NSArray *records = payload[@"records"];
NSMutableArray *copied = [NSMutableArray array];
NSMutableSet *screenshots = [NSMutableSet set];
for (NSDictionary *record in records) {
if ([text containsString:[NSString stringWithFormat:@"/%@)", record[@"contextId"]]]) {
[copied addObject:record];
if ([record[@"screenshotContextId"] isKindOfClass:NSString.class]) [screenshots addObject:record[@"screenshotContextId"]];
}
}
for (NSDictionary *record in records) {
if ([screenshots containsObject:record[@"contextId"]] && ![copied containsObject:record]) [copied addObject:record];
}
payload[@"records"] = copied;
NSData *encoded = payload ? [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil] : nil;
NSMutableDictionary *item = [@{@"public.utf8-plain-text": text} mutableCopy];
if (encoded && copied.count > 0) {
NSString *raw = [[NSString alloc] initWithData:encoded encoding:NSUTF8StringEncoding];
NSString *attribute = [raw stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.alphanumericCharacterSet];
NSString *escaped = [[[text stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"] stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"] stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
item[@"app.t3.context-fragment"] = encoded;
item[@"public.html"] = [[NSString stringWithFormat:@"<pre data-t3-context-fragment=\"%@\">%@</pre>", attribute, escaped] dataUsingEncoding:NSUTF8StringEncoding];
}
UIPasteboard.generalPasteboard.items = @[item];
}
@end
static void T3MarkdownTextApplyParagraphStyles(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
{
for (const auto &styleRange : styleRanges) {
if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
continue;
}
const NSRange markerRange = NSMakeRange(
styleRange.location,
MIN(styleRange.length, attributedString.length - styleRange.location));
const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
const NSParagraphStyle *existingStyle =
[attributedString attribute:NSParagraphStyleAttributeName
atIndex:paragraphRange.location
effectiveRange:nil];
NSMutableParagraphStyle *paragraphStyle =
existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
paragraphStyle.headIndent = styleRange.headIndent;
paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
paragraphStyle.tabStops = @[
[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
location:styleRange.headIndent
options:@{}]
];
paragraphStyle.defaultTabInterval = styleRange.headIndent;
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:paragraphRange];
}
}
static void T3MarkdownTextApplyAttachments(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges,
NSDictionary<NSString *, UIImage *> *images)
{
for (const auto &attachmentRange : attachmentRanges) {
if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
continue;
}
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *image = images[imageUri];
const BOOL isSymbol = [imageUri hasPrefix:@"sf:"];
if (isSymbol) {
image = [UIImage systemImageNamed:[imageUri substringFromIndex:3]];
}
NSDictionary *runAttributes =
[attributedString attributesAtIndex:attachmentRange.location effectiveRange:nil];
UIColor *foregroundColor = runAttributes[NSForegroundColorAttributeName];
if (image != nil && (isSymbol || attachmentRange.tintWithForeground)) {
image = [image imageWithTintColor:foregroundColor ?: UIColor.labelColor
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
NSDictionary *chip = T3ContextChipPayload(imageUri);
if (chip != nil) {
CGSize size = CGSizeMake(attachmentRange.chipWidth, attachmentRange.chipHeight);
attachment.bounds = T3ContextChipBounds(runAttributes[NSFontAttributeName], size);
NSString *iconUri = [chip[@"iconUri"] isKindOfClass:NSString.class] ? chip[@"iconUri"] : nil;
attachment.image = T3ContextChipImage(chip, size, iconUri ? images[iconUri] : nil);
}
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
[attributedString replaceCharactersInRange:range
withAttributedString:T3MarkdownTextAttachmentString(attachment, runAttributes)];
}
}
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@interface T3MarkdownOutsideTapCoordinator : NSObject <UIGestureRecognizerDelegate>
- (instancetype)initWithWindow:(UIWindow *)window;
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target;
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target;
@end
static const void *T3MarkdownOutsideTapCoordinatorKey =
&T3MarkdownOutsideTapCoordinatorKey;
@implementation T3MarkdownOutsideTapCoordinator {
__weak UIWindow *_window;
UITapGestureRecognizer *_recognizer;
NSHashTable<id<T3MarkdownOutsideTapTarget>> *_targets;
}
- (instancetype)initWithWindow:(UIWindow *)window
{
if (self = [super init]) {
_window = window;
_targets = [NSHashTable weakObjectsHashTable];
_recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
_recognizer.cancelsTouchesInView = NO;
_recognizer.delegate = self;
[window addGestureRecognizer:_recognizer];
}
return self;
}
- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target
{
[_targets addObject:target];
}
- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target
{
[_targets removeObject:target];
if (_targets.count > 0) {
return;
}
UIWindow *window = _window;
[window removeGestureRecognizer:_recognizer];
if (objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey) == self) {
objc_setAssociatedObject(
window,
T3MarkdownOutsideTapCoordinatorKey,
nil,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
- (void)handleTap:(UITapGestureRecognizer *)sender
{
UIWindow *window = _window;
if (window == nil) {
return;
}
UIView *hitView = [window hitTest:[sender locationInView:window] withEvent:nil];
if (hitView == nil) {
return;
}
for (id<T3MarkdownOutsideTapTarget> target in _targets.allObjects) {
[target clearSelectionForOutsideTapWithHitView:hitView];
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
@end
static T3MarkdownOutsideTapCoordinator *
T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
{
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey);
if (coordinator == nil) {
coordinator = [[T3MarkdownOutsideTapCoordinator alloc] initWithWindow:window];
objc_setAssociatedObject(
window,
T3MarkdownOutsideTapCoordinatorKey,
coordinator,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return coordinator;
}
@interface T3MarkdownText () <RCTT3MarkdownTextViewProtocol, UIGestureRecognizerDelegate, UITextViewDelegate>
@end
@interface T3MarkdownText () <T3MarkdownOutsideTapTarget>
@end
@implementation T3MarkdownText {
UIView * _view;
T3ContextCopyTextView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
NSMutableDictionary<NSString *, UIImage *> * _attachmentImages;
NSMutableSet<NSString *> * _pendingAttachmentUris;
UILongPressGestureRecognizer *_longPressGestureRecognizer;
UITapGestureRecognizer *_pressGestureRecognizer;
NSArray *_contextAccessibilityElements;
BOOL _textLayoutNeedsUpdate;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
_props = defaultProps;
_view = [[UIView alloc] init];
self.contentView = _view;
self.clipsToBounds = true;
_textView = [[T3ContextCopyTextView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
_textView.editable = false;
_textView.textContainerInset = UIEdgeInsetsZero;
_textView.textContainer.lineFragmentPadding = 0;
// The shadow node already sized this view to fit every line. A container
// that tracks the frame can come out a fraction of a point shorter after
// pixel rounding, and TextKit then drops the last line. Size it by hand
// with unbounded height and let the view's bounds clip.
_textView.textContainer.widthTracksTextView = NO;
_textView.textContainer.heightTracksTextView = NO;
_textView.delegate = self;
// Chat text supports selection and contextual actions, but not drag-and-drop.
_textView.textDragInteraction.enabled = NO;
_textView.linkTextAttributes = @{};
// Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
_textView.layoutManager.usesFontLeading = NO;
[self addSubview:_textView];
_longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(handleLongPressIfNecessary:)];
_longPressGestureRecognizer.delegate = self;
_pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handlePressIfNecessary:)];
_pressGestureRecognizer.delegate = self;
[_pressGestureRecognizer requireGestureRecognizerToFail:_longPressGestureRecognizer];
[_textView addGestureRecognizer:_pressGestureRecognizer];
[_textView addGestureRecognizer:_longPressGestureRecognizer];
}
return self;
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (_outsideTapWindow == self.window) {
return;
}
if (_outsideTapWindow != nil) {
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
}
_outsideTapWindow = self.window;
if (_outsideTapWindow != nil) {
[T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
}
}
- (void)dealloc
{
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
}
- (NSArray *)accessibilityElements
{
return _contextAccessibilityElements ?: [super accessibilityElements];
}
// See RCTParagraphComponentView
- (void)prepareForRecycle
{
[super prepareForRecycle];
T3MarkdownOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
_outsideTapWindow = nil;
_state.reset();
// Reset the frame to zero so that when it properly lays out on the next use
_textView.frame = CGRectZero;
_textView.attributedText = nil;
_contextAccessibilityElements = nil;
_textLayoutNeedsUpdate = YES;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Resize during UIKit's layout pass. Doing this in drawRect can leave the
// text view's drawing surface clipped to its previous width after a pane
// expands, even though TextKit has already rewrapped the lines.
if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
_textView.frame = _view.frame;
_textLayoutNeedsUpdate = YES;
[self setNeedsDisplay];
}
}
- (void)drawRect:(CGRect)rect
{
if (!_state) {
return;
}
const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
const auto attrString = _state->getData().attributedString;
NSMutableAttributedString *convertedAttrString =
[RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
T3MarkdownTextApplyParagraphStyles(
convertedAttrString,
_state->getData().paragraphStyleRanges);
T3MarkdownTextApplyAttachments(
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
// Matches the shadow node so drawn lines sit where measurement put them.
RCTApplyBaselineOffset(convertedAttrString);
NSUInteger runLocation = 0;
for (UIView *child in self.subviews) {
if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
continue;
}
T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
const NSRange runRange = NSMakeRange(runLocation, textChild.text.length);
runLocation = NSMaxRange(runRange);
if (![textChild hasContextMenu] || runRange.length == 0 ||
NSMaxRange(runRange) > convertedAttrString.length) {
continue;
}
NSURL *link = [NSURL URLWithString:
[NSString stringWithFormat:@"t3-markdown-run://%ld", (long)textChild.tag]];
if (link != nil) {
// A glyph must not be both a link and an attachment. UIKit caches them as
// different text-item classes and can send `attachment` to a cached link
// on a later tap. Attachment actions already use primaryActionForTextItem.
[convertedAttrString enumerateAttribute:NSAttachmentAttributeName
inRange:runRange
options:0
usingBlock:^(id attachment, NSRange range, BOOL *stop) {
if (attachment == nil) {
[convertedAttrString addAttribute:NSLinkAttributeName value:link range:range];
}
}];
}
}
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
// the frame triggers a layout flush that has the same effect. Bail out
// entirely when nothing actually changed so a JS-side state update made in
// response to onSelectionChange doesn't deselect what the user is selecting.
const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
const BOOL frameChanged = _textLayoutNeedsUpdate;
if (!textChanged && !frameChanged) {
return;
}
if (textChanged) {
// Reassigning attributedText clears any active selection. Save it and
// restore after, while suppressing the synthetic textViewDidChangeSelection
// events the clear-then-restore would otherwise produce — those would
// round-trip to JS and re-trigger this same path, causing a loop.
const NSRange savedRange = _textView.selectedRange;
_suppressSelectionChange = YES;
_textView.attributedText = convertedAttrString;
NSMutableString *accessibleText = [convertedAttrString.string mutableCopy];
for (auto it = _state->getData().attachmentRanges.rbegin();
it != _state->getData().attachmentRanges.rend(); ++it) {
NSDictionary *chip = T3ContextChipPayload([NSString stringWithUTF8String:it->imageUri.c_str()]);
if (chip != nil && it->location < accessibleText.length) {
[accessibleText replaceCharactersInRange:NSMakeRange(it->location, 1) withString:chip[@"label"]];
}
}
_textView.accessibilityLabel = accessibleText;
if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
_textView.selectedRange = savedRange;
}
_suppressSelectionChange = NO;
}
if (frameChanged) {
_textView.textContainer.size = CGSizeMake(CGRectGetWidth(_view.frame), CGFLOAT_MAX);
}
_textLayoutNeedsUpdate = NO;
// Text attachments have no native link element. Expose their existing runs
// at the measured glyph bounds, without inserting views into text layout.
NSMutableArray *accessibleElements = [NSMutableArray arrayWithObject:_textView];
for (UIView *child in self.subviews) {
if (![child isKindOfClass:T3MarkdownTextRun.class]) continue;
T3MarkdownTextRun *run = (T3MarkdownTextRun *)child;
run.contextChipInteractive = NO;
}
for (const auto &attachmentRange : _state->getData().attachmentRanges) {
NSDictionary *chip = T3ContextChipPayload(
[NSString stringWithUTF8String:attachmentRange.imageUri.c_str()]);
if (![chip[@"interactive"] boolValue]) continue;
NSRange range = NSMakeRange(attachmentRange.location, 1);
T3MarkdownTextRun *run = [self childForCharacterRange:range];
if (!run || NSMaxRange(range) > convertedAttrString.length) continue;
NSRange glyphRange = [_textView.layoutManager glyphRangeForCharacterRange:range actualCharacterRange:nil];
CGRect bounds = [_textView.layoutManager boundingRectForGlyphRange:glyphRange
inTextContainer:_textView.textContainer];
bounds = CGRectOffset(bounds, _textView.textContainerInset.left, _textView.textContainerInset.top);
run.contextChipInteractive = YES;
T3ContextChipAccessibilityElement *element =
[[T3ContextChipAccessibilityElement alloc] initWithAccessibilityContainer:self];
element.run = run;
element.accessibilityLabel = chip[@"label"];
element.accessibilityTraits = UIAccessibilityTraitButton;
element.accessibilityFrameInContainerSpace = [_textView convertRect:bounds toView:self];
[accessibleElements addObject:element];
}
_contextAccessibilityElements = accessibleElements;
__block std::vector<std::string> lines;
const int maxLines = props.numberOfLines;
[_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
CGRect usedRect,
NSTextContainer * _Nonnull textContainer,
NSRange glyphRange,
BOOL * _Nonnull stop) {
const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
const auto line = [self->_textView.text substringWithRange:charRange];
lines.push_back(line.UTF8String);
// enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
// 18, so cap explicitly.
if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
*stop = YES;
}
}];
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
};
}
- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
{
for (const auto &attachmentRange : attachmentRanges) {
NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
if ([imageUri hasPrefix:@"sf:"]) {
continue;
}
NSDictionary *chip = T3ContextChipPayload(imageUri);
if (chip != nil) {
imageUri = [chip[@"iconUri"] isKindOfClass:NSString.class] ? chip[@"iconUri"] : nil;
if (imageUri.length == 0) continue;
}
if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
continue;
}
NSURL *url = [NSURL URLWithString:imageUri];
if (url == nil) {
continue;
}
if (url.isFileURL) {
UIImage *image = [UIImage imageWithContentsOfFile:url.path];
if (image != nil) {
_attachmentImages[imageUri] = image;
dispatch_async(dispatch_get_main_queue(), ^{
[self refreshDisplayedAttachments];
});
}
continue;
}
[_pendingAttachmentUris addObject:imageUri];
[[[NSURLSession sharedSession] dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[self->_pendingAttachmentUris removeObject:imageUri];
if (image != nil) {
self->_attachmentImages[imageUri] = image;
[self refreshDisplayedAttachments];
}
});
}] resume];
}
}
- (void)refreshDisplayedAttachments
{
if (!_state || _textView.attributedText == nil) {
return;
}
NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
T3MarkdownTextApplyAttachments(
attributedText,
_state->getData().attachmentRanges,
_attachmentImages);
const NSRange savedRange = _textView.selectedRange;
_suppressSelectionChange = YES;
_textView.attributedText = attributedText;
if (savedRange.location != NSNotFound &&
NSMaxRange(savedRange) <= _textView.attributedText.length) {
_textView.selectedRange = savedRange;
}
_suppressSelectionChange = NO;
[_textView setNeedsDisplay];
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
if (oldViewProps.contextClipboardConfig != newViewProps.contextClipboardConfig) {
NSString *config = RCTNSStringFromString(newViewProps.contextClipboardConfig);
_textView.contextClipboardConfig = config.length ? [NSJSONSerialization JSONObjectWithData:[config dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] : nil;
}
if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
_textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
}
if (oldViewProps.selectable != newViewProps.selectable) {
_textView.selectable = newViewProps.selectable;
}
if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
if (@available(iOS 11.0, *)) {
_textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
}
}
if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
} else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
_textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
}
}
// I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
// is in will have this background color applied. To apply it just to a particular part of a string, you'd need
// to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
// This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
_textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
}
[super updateProps:props oldProps:oldProps];
}
// See RCTParagraphComponentView
- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
{
_state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
[self setNeedsDisplay];
}
// MARK: - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer != _longPressGestureRecognizer &&
gestureRecognizer != _pressGestureRecognizer) {
return YES;
}
const auto location = [self getLocationOfPress:gestureRecognizer];
const auto child = [self getTouchChild:location];
return ![child hasContextMenu];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
return YES;
}
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
{
if ([hitView isDescendantOfView:self]) {
return;
}
// Defer past the current event loop turn so any in-flight edit-menu action
// (Copy / Define / Look Up / …) reads the live selection before we clear it.
UITextView *textView = _textView;
dispatch_async(dispatch_get_main_queue(), ^{
UITextRange *range = textView.selectedTextRange;
if (range != nil && !range.isEmpty) {
textView.selectedTextRange = nil;
}
});
}
// MARK: - Touch handling
- (nullable T3MarkdownTextRun *)childForCharacterRange:(NSRange)characterRange
{
NSUInteger location = 0;
for (UIView *child in self.subviews) {
if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
continue;
}
T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
const NSRange range = NSMakeRange(location, textChild.text.length);
if (NSIntersectionRange(range, characterRange).length > 0) {
return textChild;
}
location = NSMaxRange(range);
}
return nil;
}
- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
{
return [sender locationInView:_textView];
}
- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
{
const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
inTextContainer:_textView.textContainer
fractionOfDistanceBetweenInsertionPoints:nil
];
int currIndex = -1;
for (UIView* child in self.subviews) {
if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
continue;
}
T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
// This is UTF16 code units!!
currIndex += textChild.text.length;
if (charIndex <= currIndex) {
return textChild;
}
}
return nil;
}
- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
{
const auto location = [self getLocationOfPress:sender];
const auto child = [self getTouchChild:location];
if (child) {
[child onPress];
}
}
- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
{
if (sender.state != UIGestureRecognizerStateBegan) {
return;
}
const auto location = [self getLocationOfPress:sender];
const auto child = [self getTouchChild:location];
if (child) {
[child onLongPress];
}
}
// MARK: - UITextViewDelegate
- (nullable UIAction *)textView:(UITextView *)textView
primaryActionForTextItem:(UITextItem *)textItem
defaultAction:(UIAction *)defaultAction API_AVAILABLE(ios(17.0))
{
T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
if (![child hasContextMenu] && !child.contextChipInteractive) {
return defaultAction;
}
__weak T3MarkdownTextRun *weakChild = child;
return [UIAction actionWithHandler:^(__kindof UIAction *action) {
[weakChild onPress];
}];
}
- (nullable UITextItemMenuConfiguration *)textView:(UITextView *)textView
menuConfigurationForTextItem:(UITextItem *)textItem
defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0))
{
T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
UIMenu *menu = [child contextMenu];
if (child.contextChipInteractive && menu == nil) return nil;
return [UITextItemMenuConfiguration configurationWithMenu:menu ?: defaultMenu];
}
- (void)textViewDidChangeSelection:(UITextView *)textView
{
if (_suppressSelectionChange) {
return;
}
if (_eventEmitter == nullptr) {
return;
}
const NSRange selectedRange = textView.selectedRange;
if (selectedRange.location == NSNotFound) {
return;
}
// Fires on programmatic selection changes too (e.g. the outside-tap clear
// in handleOutsideTap:), so JS will see a synthetic empty-range event then.
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
static_cast<int>(self.tag),
static_cast<int>(selectedRange.location),
static_cast<int>(selectedRange.location + selectedRange.length),
});
}
Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
{
return T3MarkdownText.class;
}
@end
@@ -1,13 +0,0 @@
#pragma once
#include "T3MarkdownTextShadowNode.h"
#include <react/renderer/core/ConcreteComponentDescriptor.h>
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
namespace facebook::react {
using T3MarkdownTextComponentDescriptor = ConcreteComponentDescriptor<T3MarkdownTextShadowNode>;
void T3MarkdownTextSpec_registerComponentDescriptorsFromCodegen(
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
}
@@ -1,35 +0,0 @@
#import <React/RCTViewManager.h>
#import <React/RCTUIManager.h>
#import "Utils.h"
@interface T3MarkdownTextManager : RCTViewManager
@end
@implementation T3MarkdownTextManager
RCT_EXPORT_MODULE(T3MarkdownText)
- (UIView *)view
{
return [[UIView alloc] init];
}
RCT_CUSTOM_VIEW_PROPERTY(color, NSString, UIView)
{
}
@end
@interface T3MarkdownTextRunManager : RCTViewManager
@end
@implementation T3MarkdownTextRunManager
RCT_EXPORT_MODULE(T3MarkdownTextRun)
- (UIView *)view
{
return nil;
}
@end
@@ -1,28 +0,0 @@
// This guard prevent this file to be compiled in the old architecture.
#ifdef RCT_NEW_ARCH_ENABLED
#import <React/RCTViewComponentView.h>
#import <React/RCTComponent.h>
#import <UIKit/UIKit.h>
#ifndef T3MarkdownTextRunNativeComponent_h
#define T3MarkdownTextRunNativeComponent_h
NS_ASSUME_NONNULL_BEGIN
@interface T3MarkdownTextRun : RCTViewComponentView
@property (nonatomic, copy, nullable) NSString *text;
@property (nonatomic, assign) BOOL contextChipInteractive;
- (nullable UIMenu *)contextMenu;
- (BOOL)hasContextMenu;
- (void)onContextMenuAction:(NSString *)actionIdentifier;
- (void)onPress;
- (void)onLongPress;
@end
NS_ASSUME_NONNULL_END
#endif /* UitextviewViewNativeComponent_h */
#endif /* RCT_NEW_ARCH_ENABLED */
@@ -1,140 +0,0 @@
#import "T3MarkdownTextRun.h"
#import "T3MarkdownText.h"
#import "T3MarkdownTextRunComponentDescriptor.h"
#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
#import <React/RCTFabricComponentsPlugins.h>
#import "Utils.h"
using namespace facebook::react;
@interface T3MarkdownTextRun () <RCTT3MarkdownTextRunViewProtocol>
@end
@implementation T3MarkdownTextRun {
NSString * _text;
NSString * _contextMenuConfig;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<T3MarkdownTextRunComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const T3MarkdownTextRunProps>();
_props = defaultProps;
}
return self;
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextRunProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextRunProps const>(props);
if (newViewProps.text != oldViewProps.text) {
NSString *text = [NSString stringWithUTF8String:newViewProps.text.c_str()];
_text = text;
}
if (newViewProps.contextMenuConfig != oldViewProps.contextMenuConfig) {
_contextMenuConfig = [NSString stringWithUTF8String:newViewProps.contextMenuConfig.c_str()];
}
[super updateProps:props oldProps:oldProps];
}
- (BOOL)hasContextMenu
{
return _contextMenuConfig.length > 0;
}
- (nullable UIMenu *)contextMenu
{
if (_contextMenuConfig.length == 0) {
return nil;
}
NSData *data = [_contextMenuConfig dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *config = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (![config isKindOfClass:[NSDictionary class]]) {
return nil;
}
NSArray *actionConfigs = config[@"actions"];
if (![actionConfigs isKindOfClass:[NSArray class]] || actionConfigs.count == 0) {
return nil;
}
NSMutableArray<UIMenuElement *> *actions = [NSMutableArray arrayWithCapacity:actionConfigs.count];
__weak T3MarkdownTextRun *weakSelf = self;
for (NSDictionary *actionConfig in actionConfigs) {
if (![actionConfig isKindOfClass:[NSDictionary class]]) {
continue;
}
NSString *actionIdentifier = actionConfig[@"id"];
NSString *title = actionConfig[@"title"];
if (![actionIdentifier isKindOfClass:[NSString class]] ||
![title isKindOfClass:[NSString class]]) {
continue;
}
UIAction *action = [UIAction actionWithTitle:title
image:nil
identifier:actionIdentifier
handler:^(__kindof UIAction *selectedAction) {
[weakSelf onContextMenuAction:selectedAction.identifier];
}];
if ([actionConfig[@"disabled"] boolValue]) {
action.attributes = UIMenuElementAttributesDisabled;
}
[actions addObject:action];
}
if (actions.count == 0) {
return nil;
}
NSString *title = [config[@"title"] isKindOfClass:[NSString class]] ? config[@"title"] : @"";
return [UIMenu menuWithTitle:title children:actions];
}
- (void)onContextMenuAction:(NSString *)actionIdentifier
{
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextRunEventEmitter>(_eventEmitter)
->onContextMenuAction(facebook::react::T3MarkdownTextRunEventEmitter::OnContextMenuAction{
static_cast<int>(self.tag),
actionIdentifier.UTF8String,
});
}
}
- (void)onPress {
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextRunEventEmitter>(_eventEmitter)
->onPress(facebook::react::T3MarkdownTextRunEventEmitter::OnPress{});
}
}
- (void)onLongPress {
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextRunEventEmitter>(_eventEmitter)
->onLongPress(facebook::react::T3MarkdownTextRunEventEmitter::OnLongPress{});
}
}
+ (BOOL)shouldBeRecycled {
return NO;
}
Class<RCTComponentViewProtocol> T3MarkdownTextRunCls(void)
{
return T3MarkdownTextRun.class;
}
@end
@@ -1,13 +0,0 @@
#pragma once
#include "T3MarkdownTextRunShadowNode.h"
#include <react/renderer/core/ConcreteComponentDescriptor.h>
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
namespace facebook::react {
using T3MarkdownTextRunComponentDescriptor = ConcreteComponentDescriptor<T3MarkdownTextRunShadowNode>;
void T3MarkdownTextRunSpec_registerComponentDescriptorsFromCodegen(
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
}
@@ -1,6 +0,0 @@
#include "T3MarkdownTextRunShadowNode.h"
namespace facebook::react {
extern const char T3MarkdownTextRunComponentName[] = "T3MarkdownTextRun";
} // namespace facebook::react
@@ -1,16 +0,0 @@
#pragma once
#include <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#include <react/renderer/components/T3MarkdownTextSpec/Props.h>
#include <react/renderer/components/T3MarkdownTextSpec/States.h>
#include <react/renderer/components/view/ConcreteViewShadowNode.h>
namespace facebook::react {
extern const char T3MarkdownTextRunComponentName[];
using T3MarkdownTextRunShadowNode = ConcreteViewShadowNode<
T3MarkdownTextRunComponentName,
T3MarkdownTextRunProps,
T3MarkdownTextRunEventEmitter,
T3MarkdownTextRunState>;
}
@@ -1,82 +0,0 @@
#pragma once
#include <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
#include <react/renderer/components/T3MarkdownTextSpec/Props.h>
#include <react/renderer/components/view/ConcreteViewShadowNode.h>
#include <react/renderer/textlayoutmanager/TextLayoutManager.h>
#include <react/renderer/core/LayoutContext.h>
#include <react/renderer/core/ShadowNode.h>
#include <string>
#include <vector>
namespace facebook::react {
extern const char T3MarkdownTextComponentName[];
struct T3MarkdownTextParagraphStyleRange {
size_t location;
size_t length;
Float firstLineHeadIndent;
Float headIndent;
Float paragraphSpacing;
};
struct T3MarkdownTextAttachmentRange {
size_t location;
size_t length;
std::string imageUri;
/// Recolor the loaded image with the run's foreground color, like `sf:` symbols.
bool tintWithForeground;
Float chipWidth = 0;
Float chipHeight = 0;
};
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
return 14;
}
inline Float T3MarkdownTextAttachmentBaselineOffset(
const T3MarkdownTextAttachmentRange &) {
return -2;
}
class T3MarkdownTextStateReal final {
public:
AttributedString attributedString;
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
};
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
T3MarkdownTextComponentName,
T3MarkdownTextProps,
T3MarkdownTextEventEmitter,
T3MarkdownTextStateReal> {
public:
using ConcreteViewShadowNode::ConcreteViewShadowNode;
T3MarkdownTextShadowNode(
const ShadowNode& sourceShadowNode,
const ShadowNodeFragment& fragment
);
static ShadowNodeTraits BaseTraits() {
auto traits = ConcreteViewShadowNode::BaseTraits();
traits.set(ShadowNodeTraits::Trait::LeafYogaNode);
traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode);
return traits;
}
void layout(LayoutContext layoutContext) override;
Size measureContent(
const LayoutContext& layoutContext,
const LayoutConstraints& layoutConstraints) const override;
private:
mutable AttributedString _attributedString;
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
};
} // namespace facebook::React
@@ -1,303 +0,0 @@
#include "T3MarkdownTextShadowNode.h"
#include "T3MarkdownTextRunShadowNode.h"
#import "T3ContextChip.h"
#include <react/renderer/components/view/ViewShadowNode.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
#include <algorithm>
#include <cmath>
namespace facebook::react {
static constexpr Float ParagraphStyleEncodingOffset = 1000;
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
static constexpr auto LinkAttachmentNativeIdPrefix = "t3-link:";
static void applyParagraphStyles(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
{
for (const auto &styleRange : styleRanges) {
if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
continue;
}
const NSRange markerRange = NSMakeRange(
styleRange.location,
MIN(styleRange.length, attributedString.length - styleRange.location));
const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
const NSParagraphStyle *existingStyle =
[attributedString attribute:NSParagraphStyleAttributeName
atIndex:paragraphRange.location
effectiveRange:nil];
NSMutableParagraphStyle *paragraphStyle =
existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
paragraphStyle.headIndent = styleRange.headIndent;
paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
paragraphStyle.tabStops = @[
[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
location:styleRange.headIndent
options:@{}]
];
paragraphStyle.defaultTabInterval = styleRange.headIndent;
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:paragraphRange];
}
}
static void applyAttachments(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges)
{
for (const auto &attachmentRange : attachmentRanges) {
if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
continue;
}
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage alloc] init];
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
NSDictionary *runAttributes =
[attributedString attributesAtIndex:attachmentRange.location effectiveRange:nil];
if (attachmentRange.chipWidth > 0) {
attachment.bounds = T3ContextChipBounds(
runAttributes[NSFontAttributeName],
CGSizeMake(attachmentRange.chipWidth, attachmentRange.chipHeight));
}
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
[attributedString replaceCharactersInRange:range
withAttributedString:T3MarkdownTextAttachmentString(attachment, runAttributes)];
}
}
T3MarkdownTextShadowNode::T3MarkdownTextShadowNode(
const ShadowNode& sourceShadowNode,
const ShadowNodeFragment& fragment
) : ConcreteViewShadowNode(sourceShadowNode, fragment) {
};
Size T3MarkdownTextShadowNode::measureContent(
const LayoutContext& layoutContext,
const LayoutConstraints& layoutConstraints) const {
const auto &baseProps = getConcreteProps();
auto baseTextAttributes = TextAttributes::defaultTextAttributes();
baseTextAttributes.backgroundColor = baseProps.backgroundColor;
baseTextAttributes.allowFontScaling = baseProps.allowFontScaling;
Float fontSizeMultiplier = 1.0;
if (baseTextAttributes.allowFontScaling) {
fontSizeMultiplier = layoutContext.fontSizeMultiplier;
}
auto baseAttributedString = AttributedString{};
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
size_t utf16Offset = 0;
const auto &children = getChildren();
for (size_t i = 0; i < children.size(); i++) {
const auto child = children[i].get();
if (auto textViewChild = dynamic_cast<const T3MarkdownTextRunShadowNode *>(child)) {
auto &props = textViewChild->getConcreteProps();
auto fragment = AttributedString::Fragment{};
auto textAttributes = TextAttributes::defaultTextAttributes();
textAttributes.allowFontScaling = baseProps.allowFontScaling;
textAttributes.backgroundColor = props.backgroundColor;
textAttributes.fontSize = props.fontSize * fontSizeMultiplier;
textAttributes.lineHeight = props.lineHeight * fontSizeMultiplier;
textAttributes.foregroundColor = props.color;
const bool hasParagraphStyle = props.shadowRadius >= ParagraphStyleEncodingOffset;
if (!hasParagraphStyle) {
textAttributes.textShadowColor = props.shadowColor;
textAttributes.textShadowOffset = props.shadowOffset;
textAttributes.textShadowRadius = props.shadowRadius;
}
textAttributes.letterSpacing = props.letterSpacing;
textAttributes.textDecorationColor = props.textDecorationColor;
textAttributes.fontFamily = props.fontFamily;
if (props.fontStyle == T3MarkdownTextRunFontStyle::Italic) {
textAttributes.fontStyle = FontStyle::Italic;
} else {
textAttributes.fontStyle = FontStyle::Normal;
}
if (props.fontWeight == T3MarkdownTextRunFontWeight::Bold) {
textAttributes.fontWeight = FontWeight::Bold;
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::UltraLight) {
textAttributes.fontWeight = FontWeight::UltraLight;
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Light) {
textAttributes.fontWeight = FontWeight::Light;
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Medium) {
textAttributes.fontWeight = FontWeight::Medium;
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Semibold) {
textAttributes.fontWeight = FontWeight::Semibold;
} else if (props.fontWeight == T3MarkdownTextRunFontWeight::Heavy) {
textAttributes.fontWeight = FontWeight::Heavy;
} else {
textAttributes.fontWeight = FontWeight::Regular;
}
if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::LineThrough) {
textAttributes.textDecorationLineType = TextDecorationLineType::Strikethrough;
} else if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::Underline) {
textAttributes.textDecorationLineType = TextDecorationLineType::Underline;
} else {
textAttributes.textDecorationLineType = TextDecorationLineType::None;
}
if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Solid) {
textAttributes.textDecorationStyle = TextDecorationStyle::Solid;
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dotted) {
textAttributes.textDecorationStyle = TextDecorationStyle::Dotted;
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dashed) {
textAttributes.textDecorationStyle = TextDecorationStyle::Dashed;
} else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Double) {
textAttributes.textDecorationStyle = TextDecorationStyle::Double;
}
if (props.textAlign == T3MarkdownTextRunTextAlign::Left) {
textAttributes.alignment = TextAlignment::Left;
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Right) {
textAttributes.alignment = TextAlignment::Right;
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Center) {
textAttributes.alignment = TextAlignment::Center;
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Justify) {
textAttributes.alignment = TextAlignment::Justified;
} else if (props.textAlign == T3MarkdownTextRunTextAlign::Auto) {
textAttributes.alignment = TextAlignment::Natural;
}
textAttributes.backgroundColor = props.backgroundColor;
fragment.string = props.text;
fragment.textAttributes = textAttributes;
NSString *fragmentText = [NSString stringWithUTF8String:props.text.c_str()];
const size_t fragmentLength = fragmentText.length;
if (hasParagraphStyle) {
paragraphStyleRanges.push_back(T3MarkdownTextParagraphStyleRange{
utf16Offset,
fragmentLength,
props.shadowOffset.width,
props.shadowOffset.height,
props.shadowRadius - ParagraphStyleEncodingOffset,
});
}
if (props.nativeId.rfind("t3-chip:", 0) == 0 && fragmentLength > 0) {
const std::string uri = props.nativeId.substr(3);
NSMutableDictionary *payload =
[T3ContextChipPayload([NSString stringWithUTF8String:uri.c_str()]) mutableCopy];
// Chips must scale with the paragraph or smaller Dynamic Type sizes clip them.
// Store the scaled payload so measurement and the rendered bitmap use the same font.
payload[@"fontSizeMultiplier"] = @(fontSizeMultiplier);
NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil];
NSString *scaledUri = [@"chip:" stringByAppendingString:
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
const CGFloat maxWidth = std::isfinite(layoutConstraints.maximumSize.width)
? layoutConstraints.maximumSize.width : 320;
const CGSize size = T3ContextChipSize(payload, maxWidth);
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset, 1, std::string(scaledUri.UTF8String), false,
static_cast<Float>(size.width), static_cast<Float>(size.height),
});
} else if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset,
1,
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
false,
});
} else if (
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset,
1,
props.nativeId.substr(
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
false,
});
} else if (
props.nativeId.rfind(LinkAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset,
1,
props.nativeId.substr(std::char_traits<char>::length(LinkAttachmentNativeIdPrefix)),
true,
});
}
utf16Offset += fragmentLength;
baseAttributedString.appendFragment(std::move(fragment));
}
}
_attributedString = baseAttributedString;
_paragraphStyleRanges = paragraphStyleRanges;
_attachmentRanges = attachmentRanges;
NSMutableAttributedString *convertedAttributedString =
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
applyParagraphStyles(convertedAttributedString, paragraphStyleRanges);
applyAttachments(convertedAttributedString, attachmentRanges);
// TextKit stacks a paragraph's extra line height above the glyphs. React Native's own
// layout manager centres them with a baseline offset; do the same, after attachments
// so chips shift with the words.
RCTApplyBaselineOffset(convertedAttributedString);
const CGFloat maximumWidth = std::isfinite(layoutConstraints.maximumSize.width)
? layoutConstraints.maximumSize.width
: CGFLOAT_MAX;
NSTextStorage *textStorage =
[[NSTextStorage alloc] initWithAttributedString:convertedAttributedString];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
layoutManager.usesFontLeading = NO;
NSTextContainer *textContainer =
[[NSTextContainer alloc] initWithSize:CGSizeMake(maximumWidth, CGFLOAT_MAX)];
textContainer.lineFragmentPadding = 0;
textContainer.maximumNumberOfLines = baseProps.numberOfLines;
if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
textContainer.lineBreakMode = NSLineBreakByTruncatingHead;
} else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
textContainer.lineBreakMode = NSLineBreakByTruncatingMiddle;
} else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
} else {
textContainer.lineBreakMode = NSLineBreakByClipping;
}
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[layoutManager ensureLayoutForTextContainer:textContainer];
const CGRect usedRect = [layoutManager usedRectForTextContainer:textContainer];
return {
std::clamp(
static_cast<Float>(std::ceil(usedRect.size.width)),
layoutConstraints.minimumSize.width,
layoutConstraints.maximumSize.width),
std::clamp(
static_cast<Float>(std::ceil(usedRect.size.height)),
layoutConstraints.minimumSize.height,
layoutConstraints.maximumSize.height),
};
}
void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
ensureUnsealed();
setStateData(T3MarkdownTextStateReal{
_attributedString,
_paragraphStyleRanges,
_attachmentRanges,
});
}
}
@@ -1,57 +0,0 @@
{
"name": "@t3tools/mobile-markdown-text",
"version": "0.0.0",
"private": true,
"source": "./index.ts",
"files": [
"android",
"assets",
"expo-module.config.json",
"ios",
"src",
"index.ts",
"LICENSE",
"UPSTREAM.md",
"T3MarkdownText.podspec",
"react-native.config.js"
],
"main": "./index.ts",
"types": "./index.ts",
"react-native": "./index.ts",
"exports": {
".": "./index.ts",
"./file-icons": "./src/markdownFileIcons.ts",
"./link-icons": "./src/markdownLinkIcons.ts",
"./links": "./src/markdownLinks.ts",
"./markdown": "./src/nativeMarkdownText.ts",
"./primitive": "./src/MarkdownTextPrimitive.tsx",
"./renderer": "./src/SelectableMarkdownText.tsx",
"./types": "./src/SelectableMarkdownText.types.ts"
},
"peerDependencies": {
"@t3tools/client-runtime": "*",
"@t3tools/shared": "*",
"expo": "*",
"expo-asset": "*",
"expo-clipboard": "*",
"expo-haptics": "*",
"expo-symbols": "*",
"react": "*",
"react-native": "*",
"react-native-nitro-markdown": "*"
},
"codegenConfig": {
"name": "T3MarkdownTextSpec",
"type": "all",
"jsSrcsDir": "src",
"ios": {
"componentProvider": {
"T3MarkdownText": "T3MarkdownText",
"T3MarkdownTextRun": "T3MarkdownTextRun"
}
},
"outputDir": {
"ios": "ios/generated"
}
}
}
@@ -1,73 +0,0 @@
import { SymbolView } from "expo-symbols";
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { memo, useEffect, useRef, useState } from "react";
import { Pressable, type ColorValue } from "react-native";
const COPY_FEEDBACK_DURATION_MS = 1200;
function copyTextWithHaptic(value: string): void {
void Clipboard.setStringAsync(value);
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
export const CopyTextButton = memo(function CopyTextButton(props: {
readonly accessibilityLabel: string;
readonly text: string;
readonly tintColor: ColorValue;
readonly copiedTintColor?: ColorValue;
readonly backgroundColor?: ColorValue;
readonly borderColor?: ColorValue;
readonly iconSize?: number;
readonly buttonSize?: number;
}) {
const [copied, setCopied] = useState(false);
const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (resetTimeoutRef.current) {
clearTimeout(resetTimeoutRef.current);
}
},
[],
);
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={copied ? "Copied" : props.accessibilityLabel}
disabled={props.text.length === 0}
hitSlop={8}
onPress={() => {
copyTextWithHaptic(props.text);
setCopied(true);
if (resetTimeoutRef.current) {
clearTimeout(resetTimeoutRef.current);
}
resetTimeoutRef.current = setTimeout(() => {
setCopied(false);
resetTimeoutRef.current = null;
}, COPY_FEEDBACK_DURATION_MS);
}}
style={({ pressed }) => ({
width: props.buttonSize ?? 30,
height: props.buttonSize ?? 30,
alignItems: "center",
justifyContent: "center",
borderRadius: 9,
borderWidth: props.borderColor ? 1 : 0,
borderColor: props.borderColor,
backgroundColor: props.backgroundColor,
opacity: pressed ? 0.52 : 1,
})}
>
<SymbolView
name={copied ? "checkmark" : "doc.on.doc"}
size={props.iconSize ?? 13}
tintColor={copied ? (props.copiedTintColor ?? props.tintColor) : props.tintColor}
type="monochrome"
/>
</Pressable>
);
});
@@ -1,179 +0,0 @@
import React, { type Ref } from "react";
import {
findNodeHandle,
Platform,
processColor,
StyleSheet,
Text as RNText,
type ColorValue,
type TextInstance,
type TextProps,
type ViewStyle,
} from "react-native";
import { setMarkdownSelectionHandleColor } from "./T3MarkdownTextSelectionModule";
import T3MarkdownTextRunNativeComponent from "./T3MarkdownTextRunNativeComponent";
import T3MarkdownTextNativeComponent from "./T3MarkdownTextNativeComponent";
import { flattenStyles } from "./util";
const TextAncestorContext = React.createContext<[boolean, ViewStyle]>([
false,
StyleSheet.create({}),
]);
const textDefaults = {
allowFontScaling: true,
selectable: true,
} satisfies TextProps;
const useTextAncestorContext = () => React.useContext(TextAncestorContext);
/**
* Event fired by `onSelectionChange`. `start`/`end` are 0-based UTF-16 indices
* into the rendered string. `start === end` means the selection was cleared.
*/
export type SelectionChangeEvent = {
nativeEvent: { target: number; start: number; end: number };
};
export type ContextMenuActionEvent = {
nativeEvent: { target: number; actionIdentifier: string };
};
/**
* `onTextLayout` is not offered: the native view reports plain line strings
* while the React Native Text fallback reports measured `TextLayoutLine`s.
*/
export type MarkdownTextPrimitiveProps = Omit<TextProps, "onTextLayout"> & {
nativeTextRef?: Ref<TextInstance>;
selectionHandleColor?: ColorValue;
uiTextView?: boolean;
contextMenuConfig?: string;
contextClipboardConfig?: string;
onContextMenuAction?: (event: ContextMenuActionEvent) => void;
/**
* Fired when the native text selection changes. Only fires on iOS when
* `uiTextView` is true. Note: fires on every selection-edge adjustment
* (e.g. dragging a selection handle), so consumers driving expensive work
* off this event should debounce.
*/
onSelectionChange?: (event: SelectionChangeEvent) => void;
};
function MarkdownTextPrimitiveChild({
style,
children,
nativeTextRef: _nativeTextRef,
...rest
}: MarkdownTextPrimitiveProps) {
const [isAncestor, rootStyle] = useTextAncestorContext();
// Flatten the styles, and apply the root styles when needed
const flattenedStyle = React.useMemo(() => flattenStyles(rootStyle, style), [rootStyle, style]);
const contextValue = React.useMemo<[boolean, ViewStyle]>(
() => [true, flattenedStyle],
[flattenedStyle],
);
let childPosition = 0;
const nativeChildren = React.Children.toArray(children).map((child) => {
const position = childPosition;
childPosition += 1;
if (React.isValidElement(child)) {
return child;
}
if (typeof child !== "string" && typeof child !== "number") {
return null;
}
const text = child.toString();
return (
// @ts-expect-error The generated run props do not include inherited Text props.
<T3MarkdownTextRunNativeComponent
key={`text-${position}-${text.length}-${text}`}
style={flattenedStyle}
text={text}
{...rest}
/>
);
});
if (!isAncestor) {
// Press handlers are delivered by the text runs; the container never sees them.
const { onPress: _onPress, onLongPress: _onLongPress, ...containerProps } = rest;
return (
<TextAncestorContext.Provider value={contextValue}>
<T3MarkdownTextNativeComponent
{...textDefaults}
{...containerProps}
style={[flattenedStyle]}
>
{nativeChildren}
</T3MarkdownTextNativeComponent>
</TextAncestorContext.Provider>
);
}
return <>{nativeChildren}</>;
}
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 ref={nativeTextRef} {...props} />;
}
return <MarkdownTextPrimitiveChild {...props} />;
}
function AndroidMarkdownText({
nativeTextRef,
selectionHandleColor,
onLayout,
contextClipboardConfig: _contextClipboardConfig,
...props
}: MarkdownTextPrimitiveProps) {
const textRef = React.useRef<TextInstance | null>(null);
React.useImperativeHandle<TextInstance | null, TextInstance | null>(
nativeTextRef,
() => textRef.current,
[],
);
const color = processColor(selectionHandleColor);
const applyHandleColor = React.useCallback(() => {
if (!textRef.current || typeof color !== "number") return;
const reactTag = findNodeHandle(textRef.current);
if (reactTag != null) setMarkdownSelectionHandleColor(reactTag, color);
}, [color]);
// RN's selectionColor only sets the highlight. Retint mounted handles when
// the theme changes, and after layout when the native view first exists.
React.useEffect(applyHandleColor, [applyHandleColor]);
return (
<RNText
ref={textRef}
{...props}
onLayout={(event) => {
applyHandleColor();
onLayout?.(event);
}}
/>
);
}
export function MarkdownTextPrimitive({
selectionHandleColor,
...props
}: MarkdownTextPrimitiveProps) {
if (Platform.OS === "android" && selectionHandleColor !== undefined) {
return <AndroidMarkdownText {...props} selectionHandleColor={selectionHandleColor} />;
}
if (Platform.OS !== "ios") {
const { nativeTextRef, contextClipboardConfig: _contextClipboardConfig, ...textProps } = props;
return <RNText ref={nativeTextRef} {...textProps} />;
}
return <MarkdownTextPrimitiveInner {...props} />;
}
@@ -1,687 +0,0 @@
import { SymbolView } from "expo-symbols";
import { githubAlert } from "./githubAlert";
import { createContext, memo, useContext, useMemo } from "react";
import { Image, Platform, ScrollView, Text, useColorScheme, View } from "react-native";
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import { CopyTextButton } from "./CopyTextButton";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownNodePosition,
} from "./nativeMarkdownText";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText";
import type {
MarkdownCodeHighlighter,
MarkdownHighlightedToken,
MarkdownImageRenderer,
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
} from "./SelectableMarkdownText.types";
import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
/** Set by SelectableMarkdownText so images anywhere in the block tree can use it. */
export const MarkdownImageRendererContext = createContext<MarkdownImageRenderer | null>(null);
const MONO_FONT_FAMILY = Platform.select({
ios: "ui-monospace",
android: "monospace",
default: "monospace",
});
function nodeKey(node: MarkdownNode, index: number): string {
return `${node.type}:${nativeMarkdownNodePosition(node, index)}`;
}
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
}
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
return codeBlockFontSize(textStyle) + 6;
}
function nodeText(node: MarkdownNode): string {
if (node.content !== undefined) {
return node.content;
}
return (node.children ?? []).map(nodeText).join("");
}
function documentFor(node: MarkdownNode): MarkdownNode {
return node.type === "document" ? node : { type: "document", children: [node] };
}
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
const HighlightedCodeLine = memo(function HighlightedCodeLine(props: {
readonly tokens: ReadonlyArray<MarkdownHighlightedToken>;
readonly color: string;
readonly newline: boolean;
}) {
let offset = 0;
const children = [];
for (const token of props.tokens) {
if (!token.content) continue;
children.push(
<MarkdownTextPrimitive
key={offset}
style={{
color: token.color ?? props.color,
fontFamily: MONO_FONT_FAMILY,
fontStyle: token.fontStyle !== null && (token.fontStyle & 1) === 1 ? "italic" : "normal",
fontWeight: token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
}}
>
{token.content}
</MarkdownTextPrimitive>,
);
offset += token.content.length;
}
return (
<MarkdownTextPrimitive>
{children}
{props.newline ? "\n" : ""}
</MarkdownTextPrimitive>
);
});
function HighlightedCodeText(props: {
readonly content: string;
readonly highlighted: HighlightedCode | null;
readonly textStyle: NativeMarkdownTextStyle;
}) {
// The text root provides inherited styles through context. A new style object
// would rerender every token even when its completed line is unchanged.
const fontSize = codeBlockFontSize(props.textStyle);
const lineHeight = codeBlockLineHeight(props.textStyle);
const style = useMemo(
() => ({
color: props.textStyle.codeColor,
fontFamily: MONO_FONT_FAMILY,
fontSize,
lineHeight,
}),
[props.textStyle.codeColor, fontSize, lineHeight],
);
let offset = 0;
const lines = [];
if (props.highlighted) {
for (const tokens of props.highlighted) {
lines.push(
<HighlightedCodeLine
key={offset}
tokens={tokens}
color={props.textStyle.codeColor}
newline={lines.length + 1 < props.highlighted.length}
/>,
);
offset += tokens.reduce((length, token) => length + token.content.length, 0) + 1;
}
}
return (
<MarkdownTextPrimitive
uiTextView
selectable
selectionColor={props.textStyle.selectionColor}
selectionHandleColor={props.textStyle.selectionHandleColor}
style={style}
>
{props.highlighted ? lines : props.content}
</MarkdownTextPrimitive>
);
}
function NativeCodeBlock(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly compact?: boolean;
}) {
const content = nodeText(props.node).replace(/\n$/, "");
const colorScheme = useColorScheme();
const theme = colorScheme === "dark" ? "dark" : "light";
const highlighted = useHighlightedCode(content, props.node.language, theme, props.highlightCode);
const languageLabel = props.node.language?.toUpperCase() ?? "CODE";
return (
<View
style={{
backgroundColor: props.textStyle.codeBlockBackgroundColor,
borderColor: props.textStyle.dividerColor,
borderCurve: "continuous",
borderRadius: 10,
borderWidth: 1,
marginVertical: props.compact ? 7 : 0,
overflow: "hidden",
}}
>
<View
style={{
minHeight: 42,
borderBottomColor: props.textStyle.dividerColor,
borderBottomWidth: 1,
paddingLeft: 14,
paddingRight: 6,
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
}}
>
<MarkdownTextPrimitive
selectable
selectionColor={props.textStyle.selectionColor}
selectionHandleColor={props.textStyle.selectionHandleColor}
style={{
flex: 1,
color: props.textStyle.mutedColor,
fontFamily: MONO_FONT_FAMILY,
fontSize: codeBlockFontSize(props.textStyle),
}}
>
{languageLabel}
</MarkdownTextPrimitive>
<CopyTextButton
accessibilityLabel={`Copy ${languageLabel.toLowerCase()} code`}
text={content}
tintColor={props.textStyle.mutedColor}
copiedTintColor={props.textStyle.linkColor}
backgroundColor={props.textStyle.codeBackgroundColor}
borderColor={props.textStyle.dividerColor}
buttonSize={34}
iconSize={14}
/>
</View>
<ScrollView
horizontal
bounces={false}
nestedScrollEnabled={Platform.OS === "android"}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
>
<HighlightedCodeText
content={content}
highlighted={highlighted}
textStyle={props.textStyle}
/>
</ScrollView>
</View>
);
}
function collectTableRows(node: MarkdownNode): MarkdownNode[] {
const rows: MarkdownNode[] = [];
const visit = (child: MarkdownNode) => {
if (child.type === "table_row") {
rows.push(child);
return;
}
for (const nested of child.children ?? []) {
visit(nested);
}
};
visit(node);
return rows;
}
function NativeTable(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const rows = collectTableRows(props.node);
return (
<ScrollView
horizontal
bounces={false}
nestedScrollEnabled={Platform.OS === "android"}
showsHorizontalScrollIndicator={false}
>
<View
style={{
borderColor: props.textStyle.dividerColor,
borderCurve: "continuous",
borderRadius: 8,
borderWidth: 1,
overflow: "hidden",
}}
>
{rows.map((row, rowIndex) => (
<View
key={nodeKey(row, rowIndex)}
style={{
flexDirection: "row",
backgroundColor: rowIndex === 0 ? props.textStyle.codeBackgroundColor : "transparent",
borderTopColor: props.textStyle.dividerColor,
borderTopWidth: rowIndex === 0 ? 0 : 1,
}}
>
{(row.children ?? []).map((cell, cellIndex) => (
<View
key={nodeKey(cell, cellIndex)}
style={{
width: 160,
borderLeftColor: props.textStyle.dividerColor,
borderLeftWidth: cellIndex === 0 ? 0 : 1,
paddingHorizontal: 10,
paddingVertical: 8,
}}
>
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
))}
</View>
))}
</View>
</ScrollView>
);
}
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const renderImage = useContext(MarkdownImageRendererContext);
const href = props.node.href;
if (!href) {
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
if (renderImage) {
const rendered = renderImage({
href,
alt: props.node.alt ?? null,
title: props.node.title ?? null,
});
if (rendered != null) {
return <>{rendered}</>;
}
}
return (
<View style={{ gap: 6 }}>
<Image
source={{ uri: href }}
resizeMode="contain"
accessibilityLabel={props.node.alt ?? props.node.title}
style={{
width: "100%",
aspectRatio: 16 / 9,
backgroundColor: props.textStyle.codeBackgroundColor,
borderRadius: 10,
}}
/>
{props.node.alt ? (
<MarkdownTextPrimitive
selectable
selectionColor={props.textStyle.selectionColor}
selectionHandleColor={props.textStyle.selectionHandleColor}
style={{
color: props.textStyle.mutedColor,
fontFamily: props.textStyle.fontFamily,
fontSize: 12,
lineHeight: 16,
}}
>
{props.node.alt}
</MarkdownTextPrimitive>
) : null}
</View>
);
}
function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
const groups: MarkdownNode[] = [];
let inline: MarkdownNode[] = [];
const flush = () => {
if (inline.length === 0) {
return;
}
groups.push({ type: "paragraph", children: inline });
inline = [];
};
for (const node of nodes) {
if (node.type === "image") {
flush();
groups.push(node);
} else {
inline.push(node);
}
}
flush();
return groups;
}
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<View style={{ gap: 8 }}>
{inlineGroups(props.node.children ?? []).map((child, index) =>
child.type === "image" ? (
<NativeMarkdownImage
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
),
)}
</View>
);
}
function NativeList(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth: number;
}) {
const ordered = props.node.ordered ?? false;
const start = props.node.start ?? 1;
const nested = props.depth > 0;
return (
<View
style={{
gap: nested ? 3 : 5,
}}
>
{(props.node.children ?? []).map((item, index) => {
const taskMarker = item.type === "task_list_item";
const marker = taskMarker
? item.checked
? "☑︎"
: "☐︎"
: ordered
? `${start + index}.`
: props.depth % 3 === 1
? "◦"
: props.depth % 3 === 2
? "▪︎"
: "•";
const markerWidth = ordered ? 28 : taskMarker ? 20 : 18;
const markerOffset = taskMarker ? 3 : ordered ? 0 : 2;
return (
<View
key={nodeKey(item, index)}
style={{ alignItems: "flex-start", flexDirection: "row" }}
>
<View
style={{
width: markerWidth,
height: props.textStyle.lineHeight,
marginRight: 6,
alignItems: ordered ? "flex-end" : "center",
justifyContent: "flex-start",
}}
>
<Text
style={{
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: taskMarker ? 14 : props.textStyle.fontSize,
lineHeight: props.textStyle.lineHeight,
fontVariant: ordered ? ["tabular-nums"] : undefined,
transform: [{ translateY: markerOffset }],
}}
>
{marker}
</Text>
</View>
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
{nativeMarkdownListItemBlocks(item).map((child, childIndex) => (
<NativeMarkdownBlock
key={nodeKey(child, childIndex)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={props.depth + 1}
compact
/>
))}
</View>
</View>
);
})}
</View>
);
}
export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth?: number;
readonly compact?: boolean;
}) {
const depth = props.depth ?? 0;
const dark = useColorScheme() === "dark";
switch (props.node.type) {
case "document":
return (
<View style={{ gap: 8 }}>
{(props.node.children ?? []).map((child, index) => (
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
))}
</View>
);
case "code_block":
return (
<NativeCodeBlock
node={props.node}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
compact={props.compact}
/>
);
case "table":
return (
<NativeTable
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "image":
return (
<NativeMarkdownImage
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "horizontal_rule":
return (
<View
style={{
height: 1,
backgroundColor: props.textStyle.dividerColor,
}}
/>
);
case "blockquote": {
const alert = githubAlert(props.node);
const alertColor = dark ? alert?.color : alert?.lightColor;
return (
<View
style={{
borderLeftColor: alertColor ?? props.textStyle.quoteMarkerColor,
borderLeftWidth: 2,
marginVertical: props.compact ? 4 : 0,
paddingLeft: 11,
paddingVertical: 2,
gap: 6,
}}
>
{alert ? (
<View style={{ flexDirection: "row", alignItems: "center", gap: 7 }}>
{Platform.OS === "ios" ? (
<SymbolView name={alert.symbol} size={17} tintColor={alertColor} />
) : null}
<Text
style={{
color: alertColor,
fontFamily: props.textStyle.boldFontFamily,
fontSize: props.textStyle.fontSize,
}}
>
{alert.title}
</Text>
</View>
) : null}
{(alert?.children ?? props.node.children ?? []).map((child, index) => (
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
))}
</View>
);
}
case "list":
return (
<NativeList
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
);
case "paragraph":
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "html_block":
case "math_block":
return (
<View
style={{
marginVertical: props.compact ? 2 : 0,
paddingHorizontal: props.node.type === "math_block" ? 10 : 0,
paddingVertical: props.node.type === "math_block" ? 8 : 0,
backgroundColor:
props.node.type === "math_block"
? props.textStyle.codeBackgroundColor
: "transparent",
}}
>
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
);
case "table_head":
case "table_body":
case "table_row":
case "table_cell":
case "list_item":
case "task_list_item":
return (
<View style={{ gap: 4 }}>
{(props.node.children ?? []).map((child, index) => (
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
))}
</View>
);
default:
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
}
@@ -1,446 +0,0 @@
import { createContext, useCallback, useContext, useMemo } from "react";
import { decodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import {
findNodeHandle,
Image,
Linking,
Platform,
StyleSheet,
type TextInstance,
type TextStyle,
useColorScheme,
View,
} from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource, markdownIconAssetUri } from "./markdownFileIcons";
import { markdownLinkIconSource } from "./markdownLinkIcons";
import { resolveMarkdownFileIcon, resolveMarkdownLinkIcon } from "./markdownLinks";
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
import { nativeMarkdownContextCopyRanges } from "./nativeMarkdownText";
import type {
MarkdownFileContextMenu,
NativeMarkdownTextStyle,
} from "./SelectableMarkdownText.types";
import {
installMarkdownCopySanitizer,
renderAndroidContextChip,
} from "./T3MarkdownTextSelectionModule";
import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
import { contextChipPresentation } from "./nativeMarkdownText";
export const MarkdownContextClipboardContext = createContext("");
export interface MarkdownFileContextMenuHandlers {
readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
readonly onFileContextMenuAction: (href: string, actionId: string) => void;
}
/** Set by SelectableMarkdownText so file chips anywhere in the block tree get the same menu. */
export const MarkdownFileContextMenuContext = createContext<MarkdownFileContextMenuHandlers | null>(
null,
);
const EXTERNAL_LINK_PREFIX = "◉ ";
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
// React Native turns a run whose whole text is U+FFFC into a bare inline-view attachment
// with no font or paragraph style, so a chip opening a paragraph would drop its line
// height. Any other single character keeps the run's attributes; the native side swaps it
// for the chip attachment either way.
const IOS_CHIP_PLACEHOLDER = "\u200B";
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 [
run.text,
run.bold,
run.italic,
run.strikethrough,
run.code,
run.href,
run.externalHost,
run.fileIcon,
run.skillName,
run.skillLabel,
run.sourceText,
run.role,
run.headingLevel,
run.depth,
run.spacing,
run.firstLineHeadIndent,
run.headIndent,
run.paragraphSpacing,
].join(":");
}
const DEFAULT_BODY_FONT_SIZE = 15;
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
const index = Math.max(0, Math.min(5, headingLevel - 1));
const configured = textStyle.headingFontSizes?.[index];
if (typeof configured === "number" && Number.isFinite(configured)) {
return configured;
}
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
return Math.max(12, Math.round((DEFAULT_HEADING_FONT_SIZES[index] ?? 15) * scale));
}
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
const textDecorationLine = run.strikethrough
? "line-through"
: run.href && !isFile
? "underline"
: "none";
return {
color: isFile
? textStyle.fileTextColor
: isSkill
? textStyle.skillTextColor
: run.href
? textStyle.linkColor
: isHeading
? textStyle.strongColor
: run.role === "quote-marker"
? textStyle.quoteMarkerColor
: run.role === "divider"
? textStyle.dividerColor
: run.role === "code-language"
? textStyle.mutedColor
: run.role === "list-marker"
? textStyle.mutedColor
: isCodeBlock
? textStyle.codeColor
: run.code
? textStyle.inlineCodeColor
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily:
isFile || isSkill
? textStyle.boldFontFamily
: run.code || isCodeBlock
? MONO_FONT_FAMILY
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
fontSize:
run.role === "spacer"
? (run.spacing ?? 10)
: run.role === "list-break"
? textStyle.fontSize
: isHeading
? headingFontSize
: run.role === "code-language"
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
: run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
lineHeight:
run.role === "spacer"
? (run.spacing ?? 10)
: run.role === "list-break"
? textStyle.lineHeight + (run.spacing ?? 0)
: isHeading
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
: isCodeBlock
? Math.max(16, textStyle.lineHeight - 2)
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
textDecorationLine,
backgroundColor: isCodeBlock
? textStyle.codeBlockBackgroundColor
: parseComposerContextHref(run.href ?? "")
? textStyle.codeBackgroundColor
: undefined,
...(hasParagraphStyle
? {
shadowColor: "transparent",
shadowOffset: {
width: run.firstLineHeadIndent ?? 0,
height: run.headIndent,
},
shadowRadius: PARAGRAPH_STYLE_ENCODING_OFFSET + (run.paragraphSpacing ?? 0),
}
: {}),
};
}
export function NativeMarkdownSelectableText(props: {
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const colorScheme = useColorScheme();
const menu = useContext(MarkdownFileContextMenuContext);
const contextClipboardFragment = useContext(MarkdownContextClipboardContext);
const contextRecords = useMemo(
() => decodeComposerContextFragment(contextClipboardFragment)?.records ?? [],
[contextClipboardFragment],
);
const containsInlineIcon = props.runs.some(
(run) =>
run.fileIcon != null ||
run.skillName != null ||
parseComposerContextHref(run.href ?? "") !== null ||
(run.externalHost != null && resolveMarkdownLinkIcon(run.externalHost) !== null),
);
const keyedRuns = useMemo(() => {
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
return props.runs.map((run) => {
const signature = runKeySignature(run);
const occurrence = occurrences.get(signature) ?? 0;
occurrences.set(signature, occurrence + 1);
let text = run.text;
let linkIcon = null;
const contextReference = parseComposerContextHref(run.href ?? "");
const contextRecord = contextReference
? contextRecords.find((record) => record.contextId === contextReference.contextId)
: undefined;
const chip =
contextReference || run.skillName || run.fileIcon
? {
...contextChipPresentation(
contextReference?.kind ?? (run.skillName ? "skill" : "mention"),
contextRecord,
),
label: run.skillLabel ?? run.text,
interactive: Boolean(run.href),
iconUri:
!contextReference && run.fileIcon
? markdownIconAssetUri(markdownFileIconSource(run.fileIcon))
: contextRecord?.kind === "mention" && "path" in contextRecord
? markdownIconAssetUri(
markdownFileIconSource(resolveMarkdownFileIcon(contextRecord.path)),
)
: undefined,
fontSize: props.textStyle.fontSize * 0.8,
foreground: props.textStyle.color,
border: props.textStyle.contextChipBorderColor ?? props.textStyle.dividerColor,
}
: null;
// Android sizes the chip's inline box from the paragraph font so the line box stays
// the height of a plain text line; see renderContextChip.
const androidChip =
Platform.OS === "android" && chip
? renderAndroidContextChip(
JSON.stringify({
...chip,
text: {
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
},
}),
)
: null;
if (androidChip) {
text = "";
} else if (chip && Platform.OS === "ios") {
text = IOS_CHIP_PLACEHOLDER;
} else if (run.fileIcon && Platform.OS === "ios") {
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
} else if (run.skillName && 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);
linkIcon = resolveMarkdownLinkIcon(run.externalHost);
if (linkIcon === null) {
text = `${EXTERNAL_LINK_PREFIX}${text}`;
} else if (Platform.OS === "ios") {
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
}
}
return { key: `${signature}:${occurrence}`, run, text, linkIcon, chip, androidChip };
});
}, [props.runs, props.textStyle, contextRecords]);
const ranges = nativeMarkdownContextCopyRanges(
keyedRuns.map(({ run, text, linkIcon, androidChip }) => ({
run,
text,
inlineImageLength:
Platform.OS === "android" && (androidChip || run.fileIcon || linkIcon) ? 1 : 0,
})),
);
const contextClipboardConfig = ranges.length
? JSON.stringify({ fragment: contextClipboardFragment, ranges })
: "";
const attachAndroidText = useCallback(
(textView: TextInstance | null) => {
if (Platform.OS !== "android" || !containsInlineIcon || !textView) return;
const reactTag = findNodeHandle(textView);
if (typeof reactTag === "number") {
installMarkdownCopySanitizer(reactTag, contextClipboardConfig);
}
},
[containsInlineIcon, contextClipboardConfig],
);
// T3MarkdownText only rebuilds its attributed string during native layout. A
// color-only child update can otherwise leave the previous appearance cached.
const appearanceKey = [
colorScheme ?? "unspecified",
props.textStyle.fontSize,
props.textStyle.lineHeight,
props.textStyle.headingFontSizes?.join(","),
props.textStyle.color,
props.textStyle.strongColor,
props.textStyle.mutedColor,
props.textStyle.linkColor,
props.textStyle.inlineCodeColor,
props.textStyle.codeColor,
props.textStyle.codeBackgroundColor,
props.textStyle.codeBlockBackgroundColor,
props.textStyle.fileTextColor,
props.textStyle.skillTextColor,
props.textStyle.quoteMarkerColor,
props.textStyle.dividerColor,
props.textStyle.contextChipBorderColor,
].join(":");
return (
<MarkdownTextPrimitive
key={appearanceKey}
nativeTextRef={attachAndroidText}
contextClipboardConfig={contextClipboardConfig}
accessibilityLabel={
Platform.OS === "android" && containsInlineIcon
? props.runs.map((run) => run.skillLabel ?? run.text).join("")
: undefined
}
uiTextView
selectable
selectionColor={props.textStyle.selectionColor}
selectionHandleColor={props.textStyle.selectionHandleColor}
style={{
flexShrink: 1,
minWidth: 0,
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
lineHeight: props.textStyle.lineHeight,
}}
>
{keyedRuns.map(({ key, run, text, linkIcon, chip, androidChip }) => {
const href = run.href;
const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
const onPress = href
? () => {
if (props.onLinkPress) props.onLinkPress(href);
else void Linking.openURL(href);
}
: undefined;
const fileIconUri = run.fileIcon
? markdownIconAssetUri(markdownFileIconSource(run.fileIcon))
: undefined;
const linkIconUri = linkIcon
? markdownIconAssetUri(markdownLinkIconSource(linkIcon))
: undefined;
return (
<MarkdownTextPrimitive
key={key}
accessibilityLabel={androidChip ? chip?.label : undefined}
nativeID={
Platform.OS === "ios"
? chip
? `t3-chip:${JSON.stringify(chip)}`
: fileIconUri
? `t3-file:${fileIconUri}`
: run.skillName
? "t3-skill:sf:cube"
: linkIconUri
? `t3-link:${linkIconUri}`
: undefined
: undefined
}
contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
style={[
runStyle(run, props.textStyle),
chip ? { backgroundColor: "transparent" } : undefined,
]}
onPress={onPress}
onContextMenuAction={
contextMenu && href && menu
? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
: undefined
}
>
{androidChip ? (
// The inline box sits on the baseline and is only as tall as the font's
// ascent, so it never changes the line's height. The bitmap hangs off that
// box (views in text are not clipped) to centre the chip on the text.
<View
accessible
accessibilityLabel={chip?.label}
accessibilityRole={onPress ? "button" : "image"}
accessibilityActions={onPress ? [{ name: "activate" }] : undefined}
onAccessibilityAction={
onPress
? (event) => {
if (event.nativeEvent.actionName === "activate") onPress();
}
: undefined
}
style={{ width: androidChip.width, height: androidChip.boxHeight }}
>
<Image
// The bitmap is measured in whole pixels but laid out in dp, so the box can
// round a hair narrower than the image. `cover` would crop that difference
// off the right-hand border; `contain` fits the whole chip instead.
resizeMode="contain"
source={{ uri: androidChip.uri }}
style={{
position: "absolute",
left: 0,
top: androidChip.offsetY,
width: androidChip.width,
height: androidChip.height,
}}
/>
</View>
) : Platform.OS === "android" && run.fileIcon ? (
<Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
) : Platform.OS === "android" && linkIcon ? (
<Image
source={markdownLinkIconSource(linkIcon)}
style={styles.inlineIcon}
tintColor={props.textStyle.linkColor}
/>
) : null}
{text}
</MarkdownTextPrimitive>
);
})}
</MarkdownTextPrimitive>
);
}
@@ -1,125 +0,0 @@
import { useMemo } from "react";
import { View } from "react-native";
import { parseMarkdownWithOptions } from "react-native-nitro-markdown/headless";
import {
nativeMarkdownWithHtml,
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownWithAuthoredWindowsPaths,
nativeMarkdownWithPreservedSoftBreaks,
} from "./nativeMarkdownText";
import { MarkdownImageRendererContext, NativeMarkdownBlock } from "./NativeMarkdownBlock";
import {
MarkdownContextClipboardContext,
MarkdownFileContextMenuContext,
NativeMarkdownSelectableText,
type MarkdownFileContextMenuHandlers,
} from "./NativeMarkdownSelectableText";
import type {
SelectableMarkdownSkill,
SelectableMarkdownTextProps,
} from "./SelectableMarkdownText.types";
const EMPTY_SKILLS: ReadonlyArray<SelectableMarkdownSkill> = [];
export type {
MarkdownCodeHighlighter,
MarkdownHighlightedToken,
MarkdownImageRenderer,
MarkdownImageRequest,
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
SelectableMarkdownTextProps,
} from "./SelectableMarkdownText.types";
export function hasNativeSelectableMarkdownText(): boolean {
return true;
}
export function SelectableMarkdownText({
markdown,
contextClipboardFragment,
skills = EMPTY_SKILLS,
textStyle,
highlightCode,
preserveSoftBreaks = false,
onLinkPress,
fileContextMenu,
onFileContextMenuAction,
renderImage,
marginTop = 0,
marginBottom = 0,
}: SelectableMarkdownTextProps) {
const chunks = useMemo(() => {
const parsedDocument = nativeMarkdownWithAuthoredWindowsPaths(
nativeMarkdownWithHtml(
parseMarkdownWithOptions(markdown, { gfm: true, html: true, math: false }),
(content) => parseMarkdownWithOptions(content, { gfm: true, html: false, math: false }),
),
markdown,
);
const document = preserveSoftBreaks
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
: parsedDocument;
return nativeMarkdownDocumentChunks(document).map((chunk) =>
chunk.kind === "selectable"
? {
...chunk,
runs: nativeMarkdownDocumentRuns(chunk.node, skills),
}
: chunk,
);
}, [markdown, preserveSoftBreaks, skills]);
const fileContextMenuHandlers = useMemo<MarkdownFileContextMenuHandlers | null>(
() =>
fileContextMenu && onFileContextMenuAction
? { fileContextMenu, onFileContextMenuAction }
: null,
[fileContextMenu, onFileContextMenuAction],
);
return (
<MarkdownContextClipboardContext.Provider value={contextClipboardFragment ?? ""}>
<MarkdownImageRendererContext.Provider value={renderImage ?? null}>
<MarkdownFileContextMenuContext.Provider value={fileContextMenuHandlers}>
{/* A percentage width here creates a cyclic intrinsic measurement inside
shrink-to-fit containers such as user-message bubbles. Yoga then gives
the native text node an unbounded second pass and the parent only clips
the resulting single-line width instead of reflowing it. */}
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
{chunks.map((chunk, index) => {
const content =
chunk.kind === "rich" ? (
<NativeMarkdownBlock
node={chunk.node}
skills={skills}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
/>
) : (
<NativeMarkdownSelectableText
runs={chunk.runs}
textStyle={textStyle}
onLinkPress={onLinkPress}
/>
);
return (
<View
key={chunk.key}
style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
>
{content}
</View>
);
})}
</View>
</MarkdownFileContextMenuContext.Provider>
</MarkdownImageRendererContext.Provider>
</MarkdownContextClipboardContext.Provider>
);
}
@@ -1,30 +0,0 @@
import { requireOptionalNativeModule } from "expo";
interface T3MarkdownTextSelectionNativeModule {
readonly setSelectionHandleColor?: (reactTag: number, color: number) => void;
readonly installCopySanitizer: (reactTag: number, contextClipboardConfig: string) => void;
readonly renderContextChip?: (payloadJson: string) => {
readonly uri: string;
readonly width: number;
readonly height: number;
/** Inline box height: the paragraph font's ascent, so the line box never grows. */
readonly boxHeight: number;
/** Bitmap top relative to the box top; negative when the chip overhangs the box. */
readonly offsetY: number;
} | null;
}
const nativeModule =
requireOptionalNativeModule<T3MarkdownTextSelectionNativeModule>("T3MarkdownTextSelection");
export function installMarkdownCopySanitizer(reactTag: number, contextClipboardConfig = ""): void {
nativeModule?.installCopySanitizer(reactTag, contextClipboardConfig);
}
export function setMarkdownSelectionHandleColor(reactTag: number, color: number): void {
nativeModule?.setSelectionHandleColor?.(reactTag, color);
}
export function renderAndroidContextChip(payloadJson: string) {
return nativeModule?.renderContextChip?.(payloadJson) ?? null;
}
@@ -1,42 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import { githubAlert } from "./githubAlert";
const quote = (...children: MarkdownNode[]): MarkdownNode => ({
type: "blockquote",
children: [{ type: "paragraph", children }],
});
describe("GitHub alerts in native Markdown", () => {
it.each(["NOTE", "TIP", "IMPORTANT", "WARNING", "CAUTION"])(
"recognizes %s and retains formatted content",
(marker) => {
const bold: MarkdownNode = { type: "bold", children: [{ type: "text", content: "Details" }] };
const node = quote({ type: "text", content: `[!${marker}]` }, { type: "soft_break" }, bold);
const original = structuredClone(node);
const alert = githubAlert(node);
expect(alert?.title.toUpperCase()).toBe(marker);
expect(alert?.children[0]?.children).toEqual([bold]);
expect(node).toEqual(original);
},
);
it("handles text nodes containing the line break and following text", () => {
expect(
githubAlert(quote({ type: "text", content: "[!WARNING]\nKeep this text." }))?.children[0]
?.children?.[0]?.content,
).toBe("Keep this text.");
});
it("leaves inline markers, code, and ordinary quotes alone", () => {
expect(githubAlert(quote({ type: "text", content: "[!WARNING] inline" }))).toBeNull();
expect(
githubAlert(
quote(
{ type: "text", content: "[!WARNING]" },
{ type: "bold", children: [{ type: "text", content: "inline" }] },
),
),
).toBeNull();
expect(githubAlert({ type: "code_block", content: "> [!WARNING]" })).toBeNull();
expect(githubAlert(quote({ type: "text", content: "Just a quote" }))).toBeNull();
});
});
@@ -1,52 +0,0 @@
import type { MarkdownNode } from "react-native-nitro-markdown/headless";
const ALERTS = {
NOTE: { title: "Note", color: "#4493f8", lightColor: "#0969da", symbol: "info.circle" },
TIP: { title: "Tip", color: "#3fb950", lightColor: "#1a7f37", symbol: "lightbulb" },
IMPORTANT: {
title: "Important",
color: "#ab7df8",
lightColor: "#8250df",
symbol: "exclamationmark.bubble",
},
WARNING: {
title: "Warning",
color: "#d29922",
lightColor: "#9a6700",
symbol: "exclamationmark.triangle",
},
CAUTION: {
title: "Caution",
color: "#f85149",
lightColor: "#cf222e",
symbol: "exclamationmark.octagon",
},
} as const;
/** GitHub alerts are blockquotes whose first line contains only the alert marker. */
export function githubAlert(node: MarkdownNode) {
if (node.type !== "blockquote") return null;
const paragraph = node.children?.[0];
const text = paragraph?.children?.[0];
if (paragraph?.type !== "paragraph" || text?.type !== "text") return null;
const match = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](\r?\n|$)/i.exec(text.content ?? "");
if (!match) return null;
const rest = (text.content ?? "").slice(match[0].length);
const siblings = paragraph.children?.slice(1) ?? [];
if (
!rest &&
!match[2] &&
siblings.length &&
!["soft_break", "line_break"].includes(siblings[0]!.type)
)
return null;
if (!rest && ["soft_break", "line_break"].includes(siblings[0]?.type ?? "")) siblings.shift();
const children = [...(rest ? [{ ...text, content: rest }] : []), ...siblings];
return {
...ALERTS[match[1]!.toUpperCase() as keyof typeof ALERTS],
children: [
...(children.length ? [{ ...paragraph, children }] : []),
...(node.children?.slice(1) ?? []),
],
};
}
@@ -1,60 +0,0 @@
import type { ImageSourcePropType } from "react-native";
export const MARKDOWN_FILE_ICON_SOURCES = {
agents: require("../assets/file-icons/pierre_agents.png"),
astro: require("../assets/file-icons/pierre_astro.png"),
babel: require("../assets/file-icons/pierre_babel.png"),
bash: require("../assets/file-icons/pierre_bash.png"),
biome: require("../assets/file-icons/pierre_biome.png"),
bootstrap: require("../assets/file-icons/pierre_bootstrap.png"),
browserslist: require("../assets/file-icons/pierre_browserslist.png"),
bun: require("../assets/file-icons/pierre_bun.png"),
c: require("../assets/file-icons/pierre_c.png"),
claude: require("../assets/file-icons/pierre_claude.png"),
cpp: require("../assets/file-icons/pierre_cpp.png"),
css: require("../assets/file-icons/pierre_css.png"),
database: require("../assets/file-icons/pierre_database.png"),
default: require("../assets/file-icons/pierre_default.png"),
docker: require("../assets/file-icons/pierre_docker.png"),
eslint: require("../assets/file-icons/pierre_eslint.png"),
font: require("../assets/file-icons/pierre_font.png"),
git: require("../assets/file-icons/pierre_git.png"),
go: require("../assets/file-icons/pierre_go.png"),
graphql: require("../assets/file-icons/pierre_graphql.png"),
html: require("../assets/file-icons/pierre_html.png"),
image: require("../assets/file-icons/pierre_image.png"),
javascript: require("../assets/file-icons/pierre_javascript.png"),
json: require("../assets/file-icons/pierre_json.png"),
markdown: require("../assets/file-icons/pierre_markdown.png"),
mcp: require("../assets/file-icons/pierre_mcp.png"),
nextjs: require("../assets/file-icons/pierre_nextjs.png"),
npm: require("../assets/file-icons/pierre_npm.png"),
oxc: require("../assets/file-icons/pierre_oxc.png"),
pnpm: require("../assets/file-icons/pierre_pnpm.png"),
postcss: require("../assets/file-icons/pierre_postcss.png"),
prettier: require("../assets/file-icons/pierre_prettier.png"),
python: require("../assets/file-icons/pierre_python.png"),
react: require("../assets/file-icons/pierre_react.png"),
ruby: require("../assets/file-icons/pierre_ruby.png"),
rust: require("../assets/file-icons/pierre_rust.png"),
sass: require("../assets/file-icons/pierre_sass.png"),
stylelint: require("../assets/file-icons/pierre_stylelint.png"),
svelte: require("../assets/file-icons/pierre_svelte.png"),
svg: require("../assets/file-icons/pierre_svg.png"),
svgo: require("../assets/file-icons/pierre_svgo.png"),
swift: require("../assets/file-icons/pierre_swift.png"),
table: require("../assets/file-icons/pierre_table.png"),
tailwind: require("../assets/file-icons/pierre_tailwind.png"),
terraform: require("../assets/file-icons/pierre_terraform.png"),
text: require("../assets/file-icons/pierre_text.png"),
typescript: require("../assets/file-icons/pierre_typescript.png"),
video: require("../assets/file-icons/pierre_video.png"),
vite: require("../assets/file-icons/pierre_vite.png"),
vscode: require("../assets/file-icons/pierre_vscode.png"),
vue: require("../assets/file-icons/pierre_vue.png"),
wasm: require("../assets/file-icons/pierre_wasm.png"),
webpack: require("../assets/file-icons/pierre_webpack.png"),
yml: require("../assets/file-icons/pierre_yml.png"),
zig: require("../assets/file-icons/pierre_zig.png"),
zip: require("../assets/file-icons/pierre_zip.png"),
} as const satisfies Readonly<Record<string, ImageSourcePropType>>;
File diff suppressed because it is too large. Load diff
@@ -1,28 +0,0 @@
import { expect, it } from "vite-plus/test";
import { pendingCodeHighlight } from "./pendingCodeHighlight";
it("keeps completed colors and exact current text without retaining an edited tail", () => {
const colored = [
[{ content: "const n = 1;", color: "red", fontStyle: 0 }],
[{ content: "partial", color: "blue", fontStyle: 0 }],
];
const result = pendingCodeHighlight(
"const n = 1;\npartial",
"const n = 1;\nchanged\nnext",
colored,
)!;
expect(result[0]).toBe(colored[0]);
expect(result.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
"const n = 1;\nchanged\nnext",
);
expect(
result
.slice(1)
.flat()
.every((token) => token.color === null),
).toBe(true);
expect(
pendingCodeHighlight("const n = 1;\npartial", "const n = 2;\npartial", colored),
).toBeNull();
expect(pendingCodeHighlight("partial", "other", colored)).toBeNull();
});
@@ -1,19 +0,0 @@
import type { MarkdownHighlightedToken } from "./SelectableMarkdownText.types";
/** Keep finished lines colored while the current line awaits highlighting. */
export function pendingCodeHighlight(
previousCode: string,
code: string,
tokens: ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>,
): ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>> | null {
const end = previousCode.lastIndexOf("\n") + 1;
if (!end || !code.startsWith(previousCode.slice(0, end))) return null;
const completedLines = previousCode.slice(0, end).split("\n").length - 1;
return [
...tokens.slice(0, completedLines),
...code
.slice(end)
.split("\n")
.map((content) => [{ content, color: null, fontStyle: null }]),
];
}
@@ -1,189 +0,0 @@
import { act, useLayoutEffect } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { MarkdownCodeHighlighter } from "./SelectableMarkdownText.types";
import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
type Deferred = {
readonly code: string;
readonly resolve: (tokens: HighlightedCode) => void;
};
/** One colored line per newline-separated line, so a line's color proves where it came from. */
function tokensFor(code: string, color: string): HighlightedCode {
return code.split("\n").map((content) => [{ content, color, fontStyle: 0 }]);
}
function lineText(tokens: HighlightedCode | null): string | null {
return tokens?.map((line) => line.map((token) => token.content).join("")).join("\n") ?? null;
}
function lineColors(tokens: HighlightedCode | null): ReadonlyArray<string | null> {
return tokens?.map((line) => line[0]?.color ?? null) ?? [];
}
const deferred: Deferred[] = [];
const readResults = new Map<string, HighlightedCode>();
let renders = 0;
let result: HighlightedCode | null = null;
let root: Root;
const highlightCode: MarkdownCodeHighlighter = Object.assign(
vi.fn(
(input: { code: string }) =>
new Promise<HighlightedCode>((resolve) => {
deferred.push({ code: input.code, resolve });
}),
),
{
read: vi.fn((input: { code: string }) => readResults.get(input.code)),
},
);
function Probe(props: {
readonly code: string;
readonly language?: string;
readonly theme?: "light" | "dark";
}) {
const tokens = useHighlightedCode(
props.code,
props.language ?? "ts",
props.theme ?? "dark",
highlightCode,
);
useLayoutEffect(() => {
renders += 1;
result = tokens;
});
return null;
}
async function render(props: Parameters<typeof Probe>[0]) {
await act(() => root.render(<Probe {...props} />));
}
async function resolveAsync(index: number, color: string) {
const pending = deferred[index];
if (!pending) throw new Error(`no pending highlight at ${index}`);
await act(async () => {
pending.resolve(tokensFor(pending.code, color));
});
}
beforeEach(async () => {
// The probe has no DOM output, but ReactDOM needs an event target.
const document = {
nodeType: 9,
addEventListener() {},
removeEventListener() {},
};
const container = {
nodeType: 1,
tagName: "DIV",
namespaceURI: "http://www.w3.org/1999/xhtml",
ownerDocument: document,
addEventListener() {},
removeEventListener() {},
};
vi.stubGlobal("document", document);
vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
deferred.length = 0;
readResults.clear();
renders = 0;
result = null;
vi.mocked(highlightCode).mockClear();
vi.mocked(highlightCode.read!).mockClear();
root = createRoot(container as unknown as HTMLElement);
});
afterEach(async () => {
await act(() => root.unmount());
vi.unstubAllGlobals();
});
// Every test uses a distinct language so the module-level token cache from an
// earlier test can never satisfy a later one.
describe("useHighlightedCode", () => {
it("keeps colors from the latest synchronous read when a later read misses", async () => {
const language = "sync-baseline";
await render({ code: "a", language });
expect(result).toBeNull();
await resolveAsync(0, "async");
expect(lineColors(result)).toEqual(["async"]);
readResults.set("a\nb", tokensFor("a\nb", "sync-1"));
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync-2"));
const rendersBeforeAppends = renders;
await render({ code: "a\nb", language });
await render({ code: "a\nb\nc", language });
expect(lineColors(result)).toEqual(["sync-2", "sync-2", "sync-2"]);
// A synchronous hit is one render per append: no state update, no highlighter call.
expect(renders - rendersBeforeAppends).toBe(2);
expect(highlightCode).toHaveBeenCalledTimes(1);
await render({ code: "a\nb\nc\nd", language });
expect(highlightCode).toHaveBeenCalledTimes(2);
expect(lineText(result)).toBe("a\nb\nc\nd");
// Lines before the previous code's final newline are the completed ones.
expect(lineColors(result)).toEqual(["sync-2", "sync-2", null, null]);
await resolveAsync(1, "async-2");
expect(lineColors(result)).toEqual(["async-2", "async-2", "async-2", "async-2"]);
});
it("does not show obsolete text after a non-append edit", async () => {
const language = "non-append";
await render({ code: "a\nb", language });
await resolveAsync(0, "async");
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
await render({ code: "a\nb\nc", language });
expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
await render({ code: "x\nb\nc", language });
expect(result).toBeNull();
await resolveAsync(1, "async-2");
expect(lineText(result)).toBe("x\nb\nc");
});
it("never reuses colors across a language or theme change", async () => {
const language = "theme-change";
await render({ code: "a\nb", language });
await resolveAsync(0, "async");
readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
await render({ code: "a\nb\nc", language });
expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
await render({ code: "a\nb\nc\nd", language, theme: "light" });
expect(result).toBeNull();
await render({ code: "a\nb\nc\nd", language: `${language}-other` });
expect(result).toBeNull();
});
it("ignores an asynchronous completion that is older than the current code", async () => {
const language = "stale-async";
await render({ code: "a\nb", language });
await resolveAsync(0, "async");
await render({ code: "a\nb\nc", language });
expect(deferred).toHaveLength(2);
expect(lineColors(result)).toEqual(["async", null, null]);
readResults.set("a\nb\nc\nd", tokensFor("a\nb\nc\nd", "sync"));
await render({ code: "a\nb\nc\nd", language });
expect(lineColors(result)).toEqual(["sync", "sync", "sync", "sync"]);
await render({ code: "a\nb\nc\nd\ne", language });
expect(deferred).toHaveLength(3);
expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
// The older request finishes after newer synchronous results exist.
await resolveAsync(1, "stale");
expect(lineText(result)).toBe("a\nb\nc\nd\ne");
expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
await resolveAsync(2, "async-3");
expect(lineColors(result)).toEqual(["async-3", "async-3", "async-3", "async-3", "async-3"]);
});
});
@@ -1,149 +0,0 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { pendingCodeHighlight } from "./pendingCodeHighlight";
import type {
MarkdownCodeHighlighter,
MarkdownHighlightedToken,
} from "./SelectableMarkdownText.types";
export type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
interface HighlightedCodeResult {
readonly key: string;
readonly code: string;
readonly language: string | undefined;
readonly theme: "light" | "dark";
readonly tokens: HighlightedCode | null;
}
const highlightedCodeCache = new Map<string, HighlightedCode>();
const highlightedCodePromiseCache = new Map<string, Promise<HighlightedCode>>();
const HIGHLIGHTED_CODE_CACHE_LIMIT = 64;
function codeHighlightCacheKey(
code: string,
language: string | undefined,
theme: "light" | "dark",
): string {
return `${theme}:${language ?? "text"}:${code}`;
}
function cacheHighlightedCode(key: string, tokens: HighlightedCode): void {
highlightedCodeCache.delete(key);
highlightedCodeCache.set(key, tokens);
while (highlightedCodeCache.size > HIGHLIGHTED_CODE_CACHE_LIMIT) {
const oldestKey = highlightedCodeCache.keys().next().value;
if (oldestKey === undefined) {
break;
}
highlightedCodeCache.delete(oldestKey);
}
}
function loadHighlightedCode(
code: string,
language: string | undefined,
theme: "light" | "dark",
highlightCode: MarkdownCodeHighlighter,
session: object,
): Promise<HighlightedCode> {
const key = codeHighlightCacheKey(code, language, theme);
const cached = highlightedCodeCache.get(key);
if (cached) {
return Promise.resolve(cached);
}
const pending = highlightedCodePromiseCache.get(key);
if (pending) {
return pending;
}
const promise = highlightCode({ code, language, theme, session })
.then((tokens) => {
cacheHighlightedCode(key, tokens);
highlightedCodePromiseCache.delete(key);
return tokens;
})
.catch((error) => {
highlightedCodePromiseCache.delete(key);
throw error;
});
highlightedCodePromiseCache.set(key, promise);
return promise;
}
/**
* Tokens for a code block, or null while nothing usable exists yet. A cached or
* synchronous result renders in the same pass. Otherwise the most recent
* completed result seeds `pendingCodeHighlight` so finished lines keep their
* colors while the asynchronous highlighter catches up.
*/
export function useHighlightedCode(
code: string,
language: string | undefined,
theme: "light" | "dark",
highlightCode: MarkdownCodeHighlighter,
): HighlightedCode | null {
const [session] = useState(() => ({}));
const key = codeHighlightCacheKey(code, language, theme);
const ready = useMemo(
() => highlightedCodeCache.get(key) ?? highlightCode.read?.({ code, language, theme, session }),
[code, language, theme, key, highlightCode, session],
);
const [highlighted, setHighlighted] = useState<HighlightedCodeResult>(() => ({
code,
language,
theme,
key,
tokens: highlightedCodeCache.get(key) ?? null,
}));
// Synchronous reads never touch state, so each append costs one render. The
// ref remembers the newest of them, and is cleared whenever an asynchronous
// result commits so `highlighted` is the baseline again from then on.
const latestRead = useRef<HighlightedCodeResult | null>(null);
useEffect(() => {
if (ready) {
latestRead.current = { code, language, theme, key, tokens: ready };
return;
}
let active = true;
const commit = (tokens: HighlightedCode | null) => {
latestRead.current = null;
setHighlighted({ code, language, theme, key, tokens });
};
const cached = highlightedCodeCache.get(key);
if (cached) {
cacheHighlightedCode(key, cached);
commit(cached);
return () => {
active = false;
};
}
void loadHighlightedCode(code, language, theme, highlightCode, session)
.then((tokens) => {
if (active) {
commit(tokens);
}
})
.catch(() => {
if (active) {
commit(null);
}
});
return () => {
active = false;
};
}, [code, highlightCode, key, language, theme, ready, session]);
if (ready) return ready;
// oxlint-disable-next-line react/refs -- Written only after commit; a discarded render never advances it.
const baseline = latestRead.current ?? highlighted;
if (baseline.key === key) return baseline.tokens;
if (baseline.tokens && baseline.language === language && baseline.theme === theme) {
return pendingCodeHighlight(baseline.code, code, baseline.tokens);
}
return null;
}
@@ -4,10 +4,10 @@ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
Pod::Spec.new do |s|
s.name = "T3MarkdownText"
s.name = "T3SourceText"
s.version = package["version"]
s.summary = "Native selectable markdown renderer for T3 Code mobile."
s.description = "Fabric-backed attributed text and markdown rendering primitives owned by T3 Code."
s.summary = "Native selectable source text for T3 Code mobile."
s.description = "Fabric-backed styled source text with whole-document selection."
s.homepage = "https://t3tools.com"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "T3 Tools" => "[email protected]" }
@@ -7,6 +7,5 @@ version `2.2.0`, commit `addc08fea303608f070fe1eeba4bc075f181c4af`.
The upstream project is Copyright (c) 2024-25 Bluesky PBC and licensed under
the MIT License included in this directory.
T3 Code has substantially modified and renamed the implementation, integrated
its markdown renderer, and owns the resulting module going forward. This is not
T3 Code has substantially modified and renamed the implementation, limited it to selectable source-file text, and owns the resulting module going forward. This is not
an upstream package dependency or a compatibility fork.
@@ -0,0 +1 @@
export { SourceText } from "./src/SourceText";
@@ -1,11 +1,11 @@
#import <React/RCTViewComponentView.h>
#import <UIKit/UIKit.h>
#ifndef T3MarkdownTextNativeComponent_h
#define T3MarkdownTextNativeComponent_h
#ifndef T3SourceTextNativeComponent_h
#define T3SourceTextNativeComponent_h
NS_ASSUME_NONNULL_BEGIN
@interface T3MarkdownText : RCTViewComponentView
@interface T3SourceText : RCTViewComponentView
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,302 @@
#import "T3SourceText.h"
#import <React/RCTFabricComponentsPlugins.h>
#import "T3SourceTextComponentDescriptor.h"
#import "T3SourceTextShadowNode.h"
#import <React/RCTConversions.h>
#import <objc/runtime.h>
#import <react/renderer/components/T3SourceTextSpec/EventEmitters.h>
#import <react/renderer/components/T3SourceTextSpec/Props.h>
#import <react/renderer/components/T3SourceTextSpec/RCTComponentViewHelpers.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
using namespace facebook::react;
@interface T3SourceTextView : UITextView
@end
@implementation T3SourceTextView
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
// Read-only UITextViews must still allow selecting the whole file.
if (action == @selector(selectAll:)) {
return self.selectable && self.text.length > 0 &&
self.selectedRange.length < self.text.length;
}
return [super canPerformAction:action withSender:sender];
}
@end
@protocol T3SourceTextOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@interface T3SourceTextOutsideTapCoordinator
: NSObject <UIGestureRecognizerDelegate>
- (instancetype)initWithWindow:(UIWindow *)window;
- (void)addTarget:(id<T3SourceTextOutsideTapTarget>)target;
- (void)removeTarget:(id<T3SourceTextOutsideTapTarget>)target;
@end
static const void *T3SourceTextOutsideTapCoordinatorKey =
&T3SourceTextOutsideTapCoordinatorKey;
@implementation T3SourceTextOutsideTapCoordinator {
__weak UIWindow *_window;
UITapGestureRecognizer *_recognizer;
NSHashTable<id<T3SourceTextOutsideTapTarget>> *_targets;
}
- (instancetype)initWithWindow:(UIWindow *)window {
if (self = [super init]) {
_window = window;
_targets = [NSHashTable weakObjectsHashTable];
_recognizer =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTap:)];
_recognizer.cancelsTouchesInView = NO;
_recognizer.delegate = self;
[window addGestureRecognizer:_recognizer];
}
return self;
}
- (void)addTarget:(id<T3SourceTextOutsideTapTarget>)target {
[_targets addObject:target];
}
- (void)removeTarget:(id<T3SourceTextOutsideTapTarget>)target {
[_targets removeObject:target];
if (_targets.count > 0) {
return;
}
UIWindow *window = _window;
[window removeGestureRecognizer:_recognizer];
if (objc_getAssociatedObject(window, T3SourceTextOutsideTapCoordinatorKey) ==
self) {
objc_setAssociatedObject(window, T3SourceTextOutsideTapCoordinatorKey, nil,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
- (void)handleTap:(UITapGestureRecognizer *)sender {
UIWindow *window = _window;
if (window == nil) {
return;
}
UIView *hitView = [window hitTest:[sender locationInView:window]
withEvent:nil];
if (hitView == nil) {
return;
}
for (id<T3SourceTextOutsideTapTarget> target in _targets.allObjects) {
[target clearSelectionForOutsideTapWithHitView:hitView];
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
@end
static T3SourceTextOutsideTapCoordinator *
T3SourceTextOutsideTapCoordinatorForWindow(UIWindow *window) {
T3SourceTextOutsideTapCoordinator *coordinator =
objc_getAssociatedObject(window, T3SourceTextOutsideTapCoordinatorKey);
if (coordinator == nil) {
coordinator =
[[T3SourceTextOutsideTapCoordinator alloc] initWithWindow:window];
objc_setAssociatedObject(window, T3SourceTextOutsideTapCoordinatorKey,
coordinator, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return coordinator;
}
@interface T3SourceText () <RCTT3SourceTextViewProtocol, UITextViewDelegate,
T3SourceTextOutsideTapTarget>
@end
@implementation T3SourceText {
UIView *_view;
T3SourceTextView *_textView;
BOOL _textLayoutNeedsUpdate;
T3SourceTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow *_outsideTapWindow;
BOOL _suppressSelectionChange;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider {
return concreteComponentDescriptorProvider<T3SourceTextComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
static const auto defaultProps =
std::make_shared<const T3SourceTextProps>();
_props = defaultProps;
_view = [[UIView alloc] init];
self.contentView = _view;
self.clipsToBounds = YES;
_textView = [[T3SourceTextView alloc] init];
_textView.scrollEnabled = NO;
_textView.editable = NO;
_textView.textContainerInset = UIEdgeInsetsZero;
_textView.textContainer.lineFragmentPadding = 0;
_textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
_textView.textContainer.widthTracksTextView = NO;
_textView.textContainer.heightTracksTextView = NO;
_textView.delegate = self;
_textView.textDragInteraction.enabled = NO;
_textView.layoutManager.usesFontLeading = NO;
[self addSubview:_textView];
}
return self;
}
- (void)didMoveToWindow {
[super didMoveToWindow];
if (_outsideTapWindow == self.window)
return;
T3SourceTextOutsideTapCoordinator *coordinator = objc_getAssociatedObject(
_outsideTapWindow, T3SourceTextOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
_outsideTapWindow = self.window;
if (_outsideTapWindow != nil) {
[T3SourceTextOutsideTapCoordinatorForWindow(_outsideTapWindow)
addTarget:self];
}
}
- (void)dealloc {
T3SourceTextOutsideTapCoordinator *coordinator = objc_getAssociatedObject(
_outsideTapWindow, T3SourceTextOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
}
- (void)prepareForRecycle {
[super prepareForRecycle];
T3SourceTextOutsideTapCoordinator *coordinator = objc_getAssociatedObject(
_outsideTapWindow, T3SourceTextOutsideTapCoordinatorKey);
[coordinator removeTarget:self];
_outsideTapWindow = nil;
_state.reset();
_textView.frame = CGRectZero;
_textView.attributedText = nil;
_textLayoutNeedsUpdate = YES;
}
- (void)layoutSubviews {
[super layoutSubviews];
if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
_textView.frame = _view.frame;
_textLayoutNeedsUpdate = YES;
[self setNeedsDisplay];
}
}
- (void)drawRect:(CGRect)rect {
if (!_state)
return;
NSMutableAttributedString *text = [RCTNSAttributedStringFromAttributedString(
_state->getData().attributedString) mutableCopy];
RCTApplyBaselineOffset(text);
const BOOL textChanged =
![_textView.attributedText isEqualToAttributedString:text];
const BOOL frameChanged = _textLayoutNeedsUpdate;
if (!textChanged && !frameChanged)
return;
if (textChanged) {
const NSRange savedRange = _textView.selectedRange;
_suppressSelectionChange = YES;
_textView.attributedText = text;
if (savedRange.location != NSNotFound && savedRange.length > 0 &&
NSMaxRange(savedRange) <= text.length) {
_textView.selectedRange = savedRange;
}
_suppressSelectionChange = NO;
}
if (frameChanged)
_textView.textContainer.size = CGSizeMake(CGRectGetWidth(_view.frame), CGFLOAT_MAX);
_textLayoutNeedsUpdate = NO;
}
- (void)updateProps:(Props::Shared const &)props
oldProps:(Props::Shared const &)oldProps {
const auto &oldViewProps =
*std::static_pointer_cast<T3SourceTextProps const>(_props);
const auto &newViewProps =
*std::static_pointer_cast<T3SourceTextProps const>(props);
if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
_textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
}
if (oldViewProps.selectable != newViewProps.selectable)
_textView.selectable = newViewProps.selectable;
if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
_textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
}
if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
switch (newViewProps.ellipsizeMode) {
case T3SourceTextEllipsizeMode::Head:
_textView.textContainer.lineBreakMode = NSLineBreakByTruncatingHead;
break;
case T3SourceTextEllipsizeMode::Middle:
_textView.textContainer.lineBreakMode = NSLineBreakByTruncatingMiddle;
break;
case T3SourceTextEllipsizeMode::Tail:
_textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
break;
case T3SourceTextEllipsizeMode::Clip:
_textView.textContainer.lineBreakMode = NSLineBreakByClipping;
break;
}
}
if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
_textView.backgroundColor =
RCTUIColorFromSharedColor(newViewProps.backgroundColor);
}
[super updateProps:props oldProps:oldProps];
}
- (void)updateState:(const facebook::react::State::Shared &)state
oldState:(const facebook::react::State::Shared &)oldState {
_state =
std::static_pointer_cast<const T3SourceTextShadowNode::ConcreteState>(
state);
[self setNeedsDisplay];
}
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView {
if ([hitView isDescendantOfView:self])
return;
UITextView *textView = _textView;
// Allow a pending native Copy action to consume its selection first.
dispatch_async(dispatch_get_main_queue(), ^{
UITextRange *range = textView.selectedTextRange;
if (range != nil && !range.isEmpty)
textView.selectedTextRange = nil;
});
}
- (void)textViewDidChangeSelection:(UITextView *)textView {
if (_suppressSelectionChange || _eventEmitter == nullptr)
return;
const NSRange range = textView.selectedRange;
if (range.location == NSNotFound)
return;
std::dynamic_pointer_cast<const facebook::react::T3SourceTextEventEmitter>(
_eventEmitter)
->onSelectionChange(
facebook::react::T3SourceTextEventEmitter::OnSelectionChange{
static_cast<int>(self.tag), static_cast<int>(range.location),
static_cast<int>(NSMaxRange(range))});
}
Class<RCTComponentViewProtocol> T3SourceTextCls(void) {
return T3SourceText.class;
}
@end
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more