Skip to content
TypeScript

fix(mobile): composer chips match chat chips (#22518)

oliverecfe4f7955bd
diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ChipIcons.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ChipIcons.kt
new file mode 100644
index 00000000000..5b466062932
--- /dev/null
+++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ChipIcons.kt
@@ -0,0 +1,60 @@
+package expo.modules.t3composereditor
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.os.Handler
+import android.os.Looper
+import java.net.URL
+import java.util.concurrent.Executors
+
+internal object T3ChipIcons {
+ private val images = HashMap<String, Bitmap>()
+ private val pending = HashMap<String, MutableSet<(String) -> Unit>>()
+ private val downloads = Executors.newSingleThreadExecutor()
+ private val main = Handler(Looper.getMainLooper())
+
+ fun cached(uri: String): Bitmap? = images[uri]
+
+ fun load(context: Context, uri: String, onLoaded: (String) -> Unit): Bitmap? =
+ images[uri] ?: when {
+ uri.isEmpty() -> null
+ uri.startsWith("http://") || uri.startsWith("https://") -> {
+ download(uri, onLoaded)
+ null
+ }
+ else -> decodeLocal(context, uri)?.also { images[uri] = it }
+ }
+
+ private fun download(uri: String, onLoaded: (String) -> Unit) {
+ val waiting = pending[uri]
+ if (waiting != null) {
+ waiting.add(onLoaded)
+ return
+ }
+ pending[uri] = mutableSetOf(onLoaded)
+ downloads.execute {
+ val bitmap = runCatching {
+ URL(uri).openStream().use(BitmapFactory::decodeStream)
+ }.getOrNull()
+ main.post {
+ val callbacks = pending.remove(uri).orEmpty()
+ if (bitmap != null) {
+ images[uri] = bitmap
+ callbacks.forEach { it(uri) }
+ }
+ }
+ }
+ }
+
+ private fun decodeLocal(context: Context, uri: String): Bitmap? = runCatching {
+ when {
+ uri.startsWith("/") -> BitmapFactory.decodeFile(uri)
+ uri.startsWith("file:") -> Uri.parse(uri).path?.let(BitmapFactory::decodeFile)
+ else -> context.resources.getIdentifier(uri, "drawable", context.packageName)
+ .takeIf { it != 0 }
+ ?.let { BitmapFactory.decodeResource(context.resources, it) }
+ }
+ }.getOrNull()
+}
diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt
index 32d48da78b3..0b44599016b 100644
--- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt
+++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt
@@ -61,7 +61,20 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
private var contentInsetVertical = 0
private var tokensJson = "[]"
private var tokens: List<ComposerToken> = emptyList()
- private var chipTheme = ComposerChipTheme.default()
+ private val redrawChipsWithIcon: (String) -> Unit = { uri ->
+ editor.text?.let { editable ->
+ editable.getSpans(0, editable.length, ComposerChipSpan::class.java)
+ .filter { it.iconUri == uri }
+ .forEach {
+ editable.setSpan(
+ it,
+ editable.getSpanStart(it),
+ editable.getSpanEnd(it),
+ editable.getSpanFlags(it)
+ )
+ }
+ }
+ }
private var autoCorrect = true
private var spellCheck = true
private var nativeEventCount = 0
@@ -241,17 +254,6 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
} else {
applySelectionTheme(parseColor(theme.optString("selection"), editor.currentTextColor))
}
- chipTheme = ComposerChipTheme(
- chipBackground = parseColor(theme.optString("chipBackground"), chipTheme.chipBackground),
- chipBorder = parseColor(theme.optString("chipBorder"), chipTheme.chipBorder),
- chipText = parseColor(theme.optString("chipText"), chipTheme.chipText),
- skillBackground = parseColor(
- theme.optString("skillBackground"),
- chipTheme.skillBackground,
- ),
- skillBorder = parseColor(theme.optString("skillBorder"), chipTheme.skillBorder),
- skillText = parseColor(theme.optString("skillText"), chipTheme.skillText),
- )
applyTokenSpans()
} catch (_: Exception) {
}
@@ -452,20 +454,18 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
if (token.start < 0 || token.end <= token.start || token.end > editable.length) return@forEach
val expectedSource = editable.substring(token.start, token.end)
if (expectedSource != token.source) return@forEach
+ T3ChipIcons.load(context, token.iconUri, redrawChipsWithIcon)
editable.setSpan(
ComposerChipSpan(
T3ContextChip(
content = T3ContextChip.Content(
label = token.label,
- symbol = token.symbol,
- detail = token.detail
- ),
- fontSize = editor.textSize * 0.8f,
- colors = T3ContextChip.Colors(
- accent = T3ContextChip.color(token.accent, chipTheme.chipText),
- foreground = chipTheme.chipText,
- border = chipTheme.chipBorder
+ detail = token.detail,
+ iconUri = token.iconUri,
+ tintsIcon = token.tintsIcon
),
+ fontSize = editor.textSize,
+ color = T3ContextChip.color(token.accent, editor.currentTextColor),
maximumWidth = (
editor.width.takeIf {
it > 0
@@ -508,34 +508,17 @@ private data class ComposerToken(
val label: String,
val detail: String,
val accent: String,
- val symbol: String,
+ val iconUri: String,
+ val tintsIcon: Boolean,
val start: Int,
val end: Int
)
-private data class ComposerChipTheme(
- val chipBackground: Int,
- val chipBorder: Int,
- val chipText: Int,
- val skillBackground: Int,
- val skillBorder: Int,
- val skillText: Int
-) {
- companion object {
- fun default() = ComposerChipTheme(
- chipBackground = Color.rgb(238, 240, 243),
- chipBorder = Color.rgb(210, 214, 220),
- chipText = Color.rgb(35, 39, 45),
- skillBackground = Color.rgb(233, 239, 255),
- skillBorder = Color.rgb(185, 200, 245),
- skillText = Color.rgb(45, 72, 155),
- )
- }
-}
-
private class ComposerChipSpan(
private val chip: T3ContextChip
) : ReplacementSpan() {
+ val iconUri get() = chip.iconUri
+
override fun getSize(
paint: Paint,
text: CharSequence,
@@ -581,7 +564,8 @@ private fun parseTokens(value: String): List<ComposerToken> = try {
label = token.optString("label"),
detail = token.optString("detail"),
accent = token.optString("accent"),
- symbol = token.optString("symbol", "doc"),
+ iconUri = if (token.isNull("iconUri")) "" else token.optString("iconUri"),
+ tintsIcon = token.optBoolean("tintsIcon"),
start = token.optInt("start"),
end = token.optInt("end"),
)
diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt
index d4f8312b72b..d2b7b9cb9e4 100644
--- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt
+++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ContextChip.kt
@@ -3,7 +3,8 @@ package expo.modules.t3composereditor
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
-import android.graphics.Path
+import android.graphics.PorterDuff
+import android.graphics.PorterDuffColorFilter
import android.graphics.RectF
import android.graphics.Typeface
import android.text.TextPaint
@@ -11,24 +12,25 @@ import android.text.TextUtils
import kotlin.math.ceil
import kotlin.math.min
-/** Shared by editable spans and inline chat images so their metrics and colors agree. */
class T3ContextChip(
content: Content,
fontSize: Float,
- colors: Colors,
+ private val color: Int,
maximumWidth: Float,
- private val density: Float
+ density: Float
) {
/** What the chip says: its name, the size beside it, and the glyph that leads it. */
- data class Content(val label: String, val symbol: String, val detail: String = "")
-
- data class Colors(val accent: Int, val foreground: Int, val border: Int)
-
- private val symbol = content.symbol
+ data class Content(
+ val label: String,
+ val detail: String = "",
+ val iconUri: String = "",
+ val tintsIcon: Boolean = false
+ )
private val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = fontSize
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
}
private val em = fontSize
@@ -37,72 +39,47 @@ class T3ContextChip(
private val detailPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = fontSize * 0.84f
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
}
private val detailText = if (content.detail.isEmpty()) "" else " ${content.detail}"
private val detailWidth = if (detailText.isEmpty()) 0f else detailPaint.measureText(detailText)
- // The border is stroked, and a stroke straddles the path it follows, so the box has to
- // reserve a stroke on every side it insets. Reserving it once left the right edge a
- // stroke short, and antialiasing shaved that curve flat against the span bounds.
- private val strokeWidth = density
- private val inset = strokeWidth * 2f
+ val iconUri = content.iconUri
+ private val iconPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
+ if (content.tintsIcon) {
+ colorFilter =
+ PorterDuffColorFilter([email protected], PorterDuff.Mode.SRC_IN)
+ }
+ }
+ private val padding = density * 5
+ private val iconSlot = if (iconUri.isEmpty()) 0f else em * 1.25f
val width = ceil(
min(
maximumWidth.coerceAtLeast(em * 3),
- paint.measureText(content.label) + detailWidth + em * 2.5f + inset
+ paint.measureText(content.label) + detailWidth + iconSlot + padding * 2
)
)
- val height = ceil(em * 1.41f + inset)
+ val height = ceil(paint.fontMetrics.descent - paint.fontMetrics.ascent)
private val text = TextUtils.ellipsize(
content.label,
paint,
- (width - em * 2.5f - inset - detailWidth).coerceAtLeast(0f),
+ (width - iconSlot - padding * 2 - detailWidth).coerceAtLeast(0f),
TextUtils.TruncateAt.MIDDLE
).toString()
- private val fill = Color.argb(
- 28,
- Color.red(colors.accent),
- Color.green(colors.accent),
- Color.blue(colors.accent)
- )
- private val textColor = blend(colors.accent, colors.foreground, 0.22f)
- private val borderColor = blend(colors.accent, colors.border, 0.34f)
-
- // Half a stroke keeps the border inside the box; the rest of the reserved margin is
- // slack, so an antialiased edge fades out before it reaches the span bounds.
- private val shape =
- RectF(inset / 2f, inset / 2f, width - inset / 2f, height - inset / 2f)
- private val icon = iconPath(symbol)
fun draw(canvas: Canvas, x: Float, y: Float) {
canvas.save()
canvas.translate(x, y)
- paint.style = Paint.Style.FILL
- paint.color = fill
- canvas.drawRoundRect(shape, em / 2, em / 2, paint)
- paint.style = Paint.Style.STROKE
- paint.strokeWidth = strokeWidth
- paint.color = borderColor
- canvas.drawRoundRect(shape, em / 2, em / 2, paint)
- paint.color = textColor
- canvas.save()
- val iconSize = em * 1.17f
- canvas.translate(em / 2 + inset / 2f, (height - iconSize) / 2)
- canvas.scale(iconSize / 24, iconSize / 24)
- paint.strokeWidth = 1.7f
- paint.strokeJoin = Paint.Join.ROUND
- paint.strokeCap = Paint.Cap.ROUND
- canvas.drawPath(icon, paint)
- canvas.restore()
- paint.style = Paint.Style.FILL
- val metrics = paint.fontMetrics
- val baseline = (height - metrics.descent - metrics.ascent) / 2
- canvas.drawText(text, em * 2 + inset / 2f, baseline, paint)
+ T3ChipIcons.cached(iconUri)?.let {
+ val top = (height - em) / 2
+ canvas.drawBitmap(it, null, RectF(padding, top, padding + em, top + em), iconPaint)
+ }
+ val baseline = -paint.fontMetrics.ascent
+ canvas.drawText(text, padding + iconSlot, baseline, paint)
if (detailText.isNotEmpty()) {
- detailPaint.color = paint.color
canvas.drawText(
detailText,
- em * 2 + inset / 2f + paint.measureText(text),
+ padding + iconSlot + paint.measureText(text),
baseline,
detailPaint
)
@@ -123,62 +100,5 @@ class T3ContextChip(
}
Color.parseColor(androidColor)
}.getOrDefault(fallback)
-
- private fun blend(accent: Int, base: Int, weight: Float): Int = Color.rgb(
- (Color.red(accent) * weight + Color.red(base) * (1 - weight)).toInt(),
- (Color.green(accent) * weight + Color.green(base) * (1 - weight)).toInt(),
- (Color.blue(accent) * weight + Color.blue(base) * (1 - weight)).toInt(),
- )
-
- private fun iconPath(symbol: String) = Path().apply {
- fun line(vararg points: Float) {
- moveTo(points[0], points[1])
- for (index in 2 until points.size step 2) lineTo(points[index], points[index + 1])
- }
- when (symbol) {
- "cube" -> {
- line(12f, 2f, 21f, 7f, 21f, 17f, 12f, 22f, 3f, 17f, 3f, 7f, 12f, 2f)
- line(3f, 7f, 12f, 12f, 21f, 7f)
- line(12f, 12f, 12f, 22f)
- }
- // lucide `git-pull-request`, the glyph web draws: two nodes, an elbow, and a stem.
- "git-pull-request" -> {
- addCircle(18f, 18f, 3f, Path.Direction.CW)
- addCircle(6f, 6f, 3f, Path.Direction.CW)
- moveTo(13f, 6f)
- lineTo(16f, 6f)
- cubicTo(17.1f, 6f, 18f, 6.9f, 18f, 8f)
- lineTo(18f, 15f)
- line(6f, 9f, 6f, 21f)
- }
- "cursorarrow.click" -> {
- line(4f, 3f, 19f, 12f, 12f, 14f, 9f, 21f, 4f, 3f)
- line(13f, 15f, 18f, 21f)
- }
- "text.bubble" -> {
- line(3f, 4f, 21f, 4f, 21f, 17f, 10f, 17f, 5f, 21f, 5f, 17f, 3f, 17f, 3f, 4f)
- line(7f, 8f, 17f, 8f)
- line(7f, 12f, 14f, 12f)
- }
- "terminal", "play.rectangle", "photo" -> {
- addRoundRect(2f, 4f, 22f, 20f, 2f, 2f, Path.Direction.CW)
- when (symbol) {
- "terminal" -> {
- line(6f, 8f, 10f, 12f, 6f, 16f)
- line(13f, 16f, 18f, 16f)
- }
- "play.rectangle" -> line(9f, 8f, 16f, 12f, 9f, 16f, 9f, 8f)
- else -> {
- addCircle(8f, 9f, 1.5f, Path.Direction.CW)
- line(3f, 18f, 11f, 12f, 15f, 15f, 18f, 12f, 21f, 16f)
- }
- }
- }
- else -> {
- line(5f, 2f, 14f, 2f, 20f, 8f, 20f, 22f, 5f, 22f, 5f, 2f)
- line(14f, 2f, 14f, 8f, 20f, 8f)
- }
- }
- }
}
}
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index b816bafde14..9a5dae1db3f 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
@@ -7,7 +7,7 @@ private struct ComposerTokenPayload: Decodable {
let label: String
let iconUri: String?
let accent: String?
- let symbol: String?
+ let tintsIcon: Bool?
let detail: String?
let start: Int
let end: Int
@@ -29,20 +29,6 @@ private struct ComposerControlledDocumentPayload: Decodable {
private struct ComposerThemePayload: Decodable {
let text: String
let placeholder: String
- let chipBackground: String
- let chipBorder: String
- let chipText: String
- let skillBackground: String
- let skillBorder: String
- let skillText: String
- let fileTint: String
-}
-
-private struct ComposerChipStyle {
- let tint: UIColor
- let backgroundColor: UIColor
- let borderColor: UIColor
- let textColor: UIColor
}
private enum ComposerEnterBehavior: String {
@@ -446,14 +432,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
private var requestedSelection: ComposerSelectionPayload?
private var theme = ComposerThemePayload(
text: "#262626",
- placeholder: "#8e8e93",
- chipBackground: "#f2f2f7",
- chipBorder: "#dedee3",
- chipText: "#262626",
- skillBackground: "#f9e8fb",
- skillBorder: "#e5a6eb",
- skillText: "#a21caf",
- fileTint: "#737373"
+ placeholder: "#8e8e93"
)
private var fontFamily = "DMSans-Regular"
private var fontSize: CGFloat = 14
@@ -906,40 +885,26 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
- let isSkill = token.type == "skill"
- let accent = token.accent.flatMap { UIColor(composerHex: $0) }
- let foreground = UIColor(composerHex: theme.chipText) ?? .label
- let border = UIColor(composerHex: theme.chipBorder) ?? .separator
- let tint = accent.map { blend($0, over: foreground, weight: 0.22) }
- ?? UIColor(composerHex: isSkill ? theme.skillText : theme.fileTint) ?? .secondaryLabel
- let iconName = token.symbol ?? (isSkill ? "cube" : "doc")
- let iconImage = token.iconUri.flatMap(iconImage(for:))
- let style = ComposerChipStyle(
- tint: tint,
- backgroundColor: accent?.withAlphaComponent(0.11) ?? UIColor(
- composerHex: isSkill ? theme.skillBackground : theme.chipBackground
- ) ?? .secondarySystemFill,
- borderColor: accent.map { blend($0, over: border, weight: 0.34) } ?? UIColor(
- composerHex: isSkill ? theme.skillBorder : theme.chipBorder
- ) ?? .separator,
- textColor: tint
- )
+ let color = token.accent.flatMap { UIColor(composerHex: $0) }
+ ?? UIColor(composerHex: theme.text) ?? .label
+ let chipFont = UIFont(name: "DMSans-Medium", size: fontSize)
+ ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
+ let icon = token.iconUri.flatMap(iconImage(for:)).map {
+ token.tintsIcon == true ? Self.tinted($0, color: color) : $0
+ }
let image = renderChip(
label: token.label,
detail: token.detail,
- iconName: iconName,
- iconImage: iconImage,
- style: style
+ icon: icon,
+ color: color,
+ font: chipFont
)
- let font = UIFont(name: fontFamily, size: fontSize)
- ?? UIFont.systemFont(ofSize: fontSize)
- let baselineOffset = floor((font.capHeight - image.size.height) / 2)
let attachment = ComposerTextAttachment(
source: token.source,
label: token.label,
image: image,
size: image.size,
- baselineOffset: baselineOffset
+ baselineOffset: chipFont.ascender - image.size.height
)
let attributedAttachment = NSMutableAttributedString(attachment: attachment)
attributedAttachment.addAttributes(
@@ -949,78 +914,35 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
return attributedAttachment
}
- /// Chip glyphs with no SF Symbol that reads correctly. A pull request would otherwise land on
- /// `arrow.triangle.branch`, a road-sign fork that says "branch", not "pull request", so it is
- /// drawn from the same lucide geometry web and Android use.
- private static func vectorIcon(named name: String, size: CGFloat, color: UIColor) -> UIImage? {
- guard name == "git-pull-request" else { return nil }
- return UIGraphicsImageRenderer(size: CGSize(width: size, height: size)).image { _ in
- let s = size / 24 // lucide authors on a 24pt grid.
- let path = UIBezierPath()
- for centre in [CGPoint(x: 18 * s, y: 18 * s), CGPoint(x: 6 * s, y: 6 * s)] {
- path.append(UIBezierPath(arcCenter: centre, radius: 3 * s, startAngle: 0,
- endAngle: .pi * 2, clockwise: true))
- }
- path.move(to: CGPoint(x: 13 * s, y: 6 * s))
- path.addLine(to: CGPoint(x: 16 * s, y: 6 * s))
- path.addCurve(to: CGPoint(x: 18 * s, y: 8 * s),
- controlPoint1: CGPoint(x: 17.1 * s, y: 6 * s),
- controlPoint2: CGPoint(x: 18 * s, y: 6.9 * s))
- path.addLine(to: CGPoint(x: 18 * s, y: 15 * s))
- path.move(to: CGPoint(x: 6 * s, y: 9 * s))
- path.addLine(to: CGPoint(x: 6 * s, y: 21 * s))
- path.lineWidth = 2 * s
- path.lineCapStyle = .round
- path.lineJoinStyle = .round
- color.setStroke()
- path.stroke()
- }
- }
-
private func renderChip(
label: String,
detail: String?,
- iconName: String,
- iconImage: UIImage?,
- style: ComposerChipStyle
+ icon: UIImage?,
+ color: UIColor,
+ font: UIFont
) -> UIImage {
- // Kept in step with `T3ContextChipVectorIcon` in the markdown module: a chip drawn here and
- // the same chip drawn in a sent message have to be the same picture.
- let chipFontSize = fontSize * 0.86
- let font = UIFont(name: "DMSans-Medium", size: chipFontSize)
- ?? UIFont.systemFont(ofSize: chipFontSize, weight: .medium)
- let fallbackIcon = Self.vectorIcon(named: iconName, size: 14, color: style.textColor)
- ?? UIImage(
- systemName: iconName,
- withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .medium)
- )
- let icon = iconImage ?? fallbackIcon
- // The size reads as metadata, not part of the name, so it renders a step down from the
- // label the way the web chip does.
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .left
- let detailFont = UIFont(name: "DMSans-Medium", size: chipFontSize * 0.84)
- ?? UIFont.systemFont(ofSize: chipFontSize * 0.84, weight: .medium)
+ paragraph.lineBreakMode = .byTruncatingMiddle
let attributedLabel = NSMutableAttributedString(
string: label,
- attributes: [.font: font, .foregroundColor: style.textColor, .paragraphStyle: paragraph]
+ attributes: [.font: font, .foregroundColor: color, .paragraphStyle: paragraph]
)
+ // The size reads as metadata, not part of the name, so it renders a step down from the
+ // label the way the web chip does.
if let detail, !detail.isEmpty {
+ let detailFont = font.withSize(font.pointSize * 0.84)
attributedLabel.append(
NSAttributedString(
string: " \(detail)",
- attributes: [
- .font: detailFont,
- .foregroundColor: style.textColor,
- .paragraphStyle: paragraph,
- ]
+ attributes: [.font: detailFont, .foregroundColor: color, .paragraphStyle: paragraph]
)
)
}
- let iconWidth: CGFloat = icon == nil ? 0 : chipFontSize * 1.17
- let iconGap: CGFloat = icon == nil ? 0 : chipFontSize * 0.33
- let padding = chipFontSize * 0.5
- let height = ceil(chipFontSize * 1.41)
+ let iconSide = font.pointSize
+ let iconSlot: CGFloat = icon == nil ? 0 : iconSide * 1.25
+ let padding: CGFloat = 5
+ let height = ceil(font.ascender - font.descender)
// A long path would otherwise draw a chip wider than the composer and clip. Cap the label
// to the text the editor can actually show and truncate inside it, as Android's
// `maximumWidth` does, so the chip always fits the line it sits on.
@@ -1030,58 +952,35 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
if availableWidth <= 0 {
chipsNeedMeasuredWidth = true
}
- let maximumLabelWidth = max(chipFontSize * 3, availableWidth - padding * 2 - iconWidth - iconGap)
- paragraph.lineBreakMode = .byTruncatingMiddle
- attributedLabel.addAttribute(
- .paragraphStyle,
- value: paragraph,
- range: NSRange(location: 0, length: attributedLabel.length)
- )
- let measured = attributedLabel.size()
- let textSize = CGSize(width: min(measured.width, maximumLabelWidth), height: measured.height)
- let width = ceil(padding * 2 + iconWidth + iconGap + textSize.width)
+ let maximumLabelWidth = max(font.pointSize * 3, availableWidth - padding * 2 - iconSlot)
+ let labelWidth = min(attributedLabel.size().width, maximumLabelWidth)
+ let width = ceil(padding * 2 + iconSlot + labelWidth)
let format = UIGraphicsImageRendererFormat.preferred()
format.opaque = false
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
- return renderer.image { context in
- let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
- let path = UIBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), cornerRadius: chipFontSize * 0.5)
- style.backgroundColor.setFill()
- path.fill()
- style.borderColor.setStroke()
- path.lineWidth = 1
- path.stroke()
-
- var x = padding
+ return renderer.image { _ in
if let icon {
- let renderedIcon = iconImage == nil
- ? icon.withTintColor(style.tint, renderingMode: .alwaysOriginal)
- : icon
- renderedIcon.draw(
- in: CGRect(x: x, y: (height - iconWidth) / 2, width: iconWidth, height: iconWidth)
+ icon.draw(
+ in: CGRect(x: padding, y: (height - iconSide) / 2, width: iconSide, height: iconSide)
)
- x += iconWidth + iconGap
}
// Exactly the measured width: a spare pixel here would let a capped label draw past
// the cap instead of truncating inside it.
attributedLabel.draw(
- in: CGRect(x: x, y: (height - textSize.height) / 2, width: textSize.width, height: textSize.height)
+ in: CGRect(x: padding + iconSlot, y: 0, width: labelWidth, height: height)
)
- context.cgContext.setAllowsAntialiasing(true)
}
}
- private func blend(_ accent: UIColor, over base: UIColor, weight: CGFloat) -> UIColor {
- var ar: CGFloat = 0, ag: CGFloat = 0, ab: CGFloat = 0, aa: CGFloat = 0
- var br: CGFloat = 0, bg: CGFloat = 0, bb: CGFloat = 0, ba: CGFloat = 0
- accent.getRed(&ar, green: &ag, blue: &ab, alpha: &aa)
- base.getRed(&br, green: &bg, blue: &bb, alpha: &ba)
- return UIColor(
- red: ar * weight + br * (1 - weight),
- green: ag * weight + bg * (1 - weight),
- blue: ab * weight + bb * (1 - weight),
- alpha: aa * weight + ba * (1 - weight)
- )
+ private static func tinted(_ image: UIImage, color: UIColor) -> UIImage {
+ let format = UIGraphicsImageRendererFormat.preferred()
+ format.scale = image.scale
+ format.opaque = false
+ return UIGraphicsImageRenderer(size: image.size, format: format).image { _ in
+ color.setFill()
+ UIRectFill(CGRect(origin: .zero, size: image.size))
+ image.draw(at: .zero, blendMode: .destinationIn, alpha: 1)
+ }
}
private func iconImage(for uri: String) -> UIImage? {
diff --git a/apps/mobile/src/lib/composerChipPresentation.ts b/apps/mobile/src/lib/composerChipPresentation.ts
index 518b5843eca..257234fd02b 100644
--- a/apps/mobile/src/lib/composerChipPresentation.ts
+++ b/apps/mobile/src/lib/composerChipPresentation.ts
@@ -3,12 +3,12 @@ import { imageMimeType } from "@t3tools/shared/image";
import { videoMimeType } from "@t3tools/shared/video";
import type { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";
+import { resolveMarkdownFileIcon, type MarkdownFileIcon } from "./markdownLinks";
export type ContextChipIcon = keyof typeof CONTEXT_CHIP_ICON_SOURCES;
interface ContextChipPresentation {
readonly accent?: string;
- readonly symbol: string;
readonly icon: ContextChipIcon | null;
}
@@ -17,33 +17,29 @@ interface ContextChipPresentation {
* surface. See `ContextChip.tsx`.
*/
const CONTEXT_CHIP_PRESENTATIONS = {
- image: { accent: "#d55665", symbol: "photo", icon: "image" },
- video: { accent: "#d06217", symbol: "play.rectangle", icon: "film" },
- file: { accent: "#0090cd", symbol: "doc", icon: null },
- mention: { accent: "#0096af", symbol: "doc", icon: null },
- terminal: { accent: "#009f6e", symbol: "terminal", icon: "terminal" },
- element: { accent: "#b87501", symbol: "cursorarrow.click", icon: "mouse-pointer-click" },
+ image: { accent: "#d55665", icon: "image" },
+ video: { accent: "#d06217", icon: "film" },
+ file: { accent: "#0090cd", icon: null },
+ mention: { accent: "#0096af", icon: null },
+ terminal: { accent: "#009f6e", icon: "terminal" },
+ element: { accent: "#b87501", icon: "mouse-pointer-click" },
"preview-annotation": {
accent: "#b87501",
- symbol: "cursorarrow.click",
icon: "mouse-pointer-click",
},
- "review-comment": { accent: "#8a70dd", symbol: "text.bubble", icon: "message-circle" },
+ "review-comment": { accent: "#8a70dd", icon: "message-circle" },
"pull-request": {
accent: "#7079e4",
- symbol: "git-pull-request",
icon: "git-pull-request-arrow",
},
- skill: { accent: "#b261be", symbol: "cube", icon: "skill" },
+ skill: { accent: "#b261be", icon: "skill" },
thread: {
accent: "#009c96",
- symbol: "bubble.left.and.bubble.right",
icon: "messages-square",
},
} as const satisfies Record<string, ContextChipPresentation>;
export const UNAVAILABLE_CONTEXT_CHIP_PRESENTATION: ContextChipPresentation = {
- symbol: "doc",
icon: "circle-dashed",
};
@@ -56,10 +52,10 @@ export function composerChipSizeSuffix(record?: {
}
const PULL_REQUEST_CHIP_PRESENTATIONS = {
- open: { accent: "#009f6e", symbol: "git-pull-request", icon: "git-pull-request-arrow" },
- draft: { accent: "#7f8793", symbol: "git-pull-request", icon: "git-pull-request-draft" },
- merged: { accent: "#8a70dd", symbol: "git-pull-request", icon: "git-merge" },
- closed: { accent: "#d55665", symbol: "git-pull-request", icon: "git-pull-request-closed" },
+ open: { accent: "#009f6e", icon: "git-pull-request-arrow" },
+ draft: { accent: "#7f8793", icon: "git-pull-request-draft" },
+ merged: { accent: "#8a70dd", icon: "git-merge" },
+ closed: { accent: "#d55665", icon: "git-pull-request-closed" },
} as const satisfies Record<string, ContextChipPresentation>;
export function contextChipPresentation(
@@ -102,3 +98,22 @@ export function contextChipPresentation(
? CONTEXT_CHIP_PRESENTATIONS[presentationKind as keyof typeof CONTEXT_CHIP_PRESENTATIONS]
: UNAVAILABLE_CONTEXT_CHIP_PRESENTATION;
}
+
+export type ContextChipIconRef =
+ | { readonly kind: "chip"; readonly name: ContextChipIcon }
+ | { readonly kind: "file"; readonly name: MarkdownFileIcon };
+
+export function contextChipIcon(
+ presentation: Pick<ContextChipPresentation, "icon">,
+ fileName: string,
+): ContextChipIconRef {
+ return presentation.icon
+ ? { kind: "chip", name: presentation.icon }
+ : { kind: "file", name: resolveMarkdownFileIcon(fileName) };
+}
+
+export function contextRecordFileName(record?: object): string {
+ if (record && "path" in record && typeof record.path === "string") return record.path;
+ if (record && "name" in record && typeof record.name === "string") return record.name;
+ return "";
+}
diff --git a/apps/mobile/src/lib/contextChipIconSource.ts b/apps/mobile/src/lib/contextChipIconSource.ts
new file mode 100644
index 00000000000..6aa92d8e47d
--- /dev/null
+++ b/apps/mobile/src/lib/contextChipIconSource.ts
@@ -0,0 +1,13 @@
+import type { ContextChipIconRef } from "./composerChipPresentation";
+import { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";
+import { markdownFileIconSource, markdownIconAssetUri } from "./markdownFileIcons";
+
+export function contextChipIconSource(icon: ContextChipIconRef) {
+ return icon.kind === "chip"
+ ? CONTEXT_CHIP_ICON_SOURCES[icon.name]
+ : markdownFileIconSource(icon.name);
+}
+
+export function contextChipIconUri(icon: ContextChipIconRef): string | null {
+ return markdownIconAssetUri(contextChipIconSource(icon)) ?? null;
+}
diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.ts
index aa4ea56a05b..db16d018159 100644
--- a/apps/mobile/src/lib/enrichedLinkPresentation.ts
+++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts
@@ -1,22 +1,19 @@
import type { ComposerContextRecord } from "@t3tools/contracts";
import {
composerChipSizeSuffix,
+ contextChipIcon,
contextChipPresentation,
- type ContextChipIcon,
+ contextRecordFileName,
+ type ContextChipIconRef,
UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
} from "./composerChipPresentation";
-import { resolveMarkdownFileIcon, type MarkdownFileIcon } from "./markdownLinks";
import type { SelectableMarkdownSkill } from "../native/SelectableMarkdownText.types";
import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
-export type EnrichedChipIcon =
- | { readonly kind: "chip"; readonly name: ContextChipIcon }
- | { readonly kind: "file"; readonly name: MarkdownFileIcon };
-
export function enrichedContextLinkPresentation(
href: string,
records?: ReadonlyArray<ComposerContextRecord>,
-): { accent?: string; icon: EnrichedChipIcon; label?: string } | undefined {
+): { accent?: string; icon: ContextChipIconRef; label?: string } | undefined {
const reference = parseComposerContextHref(href);
if (!reference) return undefined;
const record = records?.find((candidate) => candidate.contextId === reference.contextId);
@@ -25,13 +22,9 @@ export function enrichedContextLinkPresentation(
? UNAVAILABLE_CONTEXT_CHIP_PRESENTATION
: contextChipPresentation(reference.kind, record);
const size = composerChipSizeSuffix(record);
- const fileName =
- record && "path" in record ? record.path : record && "name" in record ? record.name : "";
return {
...(presentation.accent ? { accent: presentation.accent } : {}),
- icon: presentation.icon
- ? { kind: "chip", name: presentation.icon }
- : { kind: "file", name: resolveMarkdownFileIcon(fileName) },
+ icon: contextChipIcon(presentation, contextRecordFileName(record)),
...(record && size ? { label: `${record.label} · ${size}` } : {}),
};
}
diff --git a/apps/mobile/src/lib/nativeComposerTheme.test.ts b/apps/mobile/src/lib/nativeComposerTheme.test.ts
index 34aae8622b5..19bcd2ff008 100644
--- a/apps/mobile/src/lib/nativeComposerTheme.test.ts
+++ b/apps/mobile/src/lib/nativeComposerTheme.test.ts
@@ -9,13 +9,8 @@ describe("native composer colors", () => {
...getMobileThemeVariables("t3-code", "light"),
"--color-screen": "#ffffffff",
"--color-composer-surface": "#ffffffff",
- "--color-subtle": "#0000000d",
"--color-placeholder": "#0000009e",
- "--color-inline-skill-background": "#ffffffff",
- "--color-inline-skill-border": "#00000080",
});
- expect(theme.chipBackground).toBe("#f2f2f2");
expect(theme.placeholder).toBe("#616161");
- expect(theme.skillBorder).toBe("#7f7f7f");
});
});
diff --git a/apps/mobile/src/lib/nativeComposerTheme.ts b/apps/mobile/src/lib/nativeComposerTheme.ts
index 80e252f0d23..c740a990075 100644
--- a/apps/mobile/src/lib/nativeComposerTheme.ts
+++ b/apps/mobile/src/lib/nativeComposerTheme.ts
@@ -3,17 +3,8 @@ import { flattenThemeColor, type MobileThemeVariables } from "./mobileTheme";
/** Native chip parsers need opaque hex instead of CSS rgba or platform-specific alpha order. */
export function createNativeComposerTheme(theme: MobileThemeVariables) {
const surface = flattenThemeColor(theme["--color-composer-surface"], theme["--color-screen"]);
- const chipBackground = flattenThemeColor(theme["--color-subtle"], surface);
- const skillBackground = flattenThemeColor(theme["--color-inline-skill-background"], surface);
return {
text: flattenThemeColor(theme["--color-foreground"], surface),
placeholder: flattenThemeColor(theme["--color-placeholder"], surface),
- chipBackground,
- chipBorder: flattenThemeColor(theme["--color-border"], chipBackground),
- chipText: flattenThemeColor(theme["--color-foreground"], chipBackground),
- skillBackground,
- skillBorder: flattenThemeColor(theme["--color-inline-skill-border"], skillBackground),
- skillText: flattenThemeColor(theme["--color-inline-skill-foreground"], skillBackground),
- fileTint: flattenThemeColor(theme["--color-icon-muted"], chipBackground),
};
}
diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
index dfbfff19217..519de199319 100644
--- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
@@ -15,9 +15,13 @@ import {
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
import { StyleSheet } from "react-native";
-import { markdownFileIconSource, markdownIconAssetUri } from "../lib/markdownFileIcons";
-import { composerChipSizeSuffix, contextChipPresentation } from "../lib/composerChipPresentation";
-import { resolveMarkdownFileIcon } from "../lib/markdownLinks";
+import {
+ composerChipSizeSuffix,
+ contextChipIcon,
+ contextChipPresentation,
+ contextRecordFileName,
+} from "../lib/composerChipPresentation";
+import { contextChipIconUri } from "../lib/contextChipIconSource";
import { useUniwindTheme } from "../lib/useUniwindTheme";
import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
import { FONT_FAMILIES } from "../lib/fontFamilies";
@@ -111,10 +115,6 @@ function basename(path: string): string {
return separator >= 0 ? path.slice(separator + 1) : path;
}
-function fileIconUri(path: string): string | null {
- return markdownIconAssetUri(markdownFileIconSource(resolveMarkdownFileIcon(path))) ?? null;
-}
-
export function ComposerEditor({
ref,
skills = EMPTY_SKILLS,
@@ -168,12 +168,20 @@ export function ComposerEditor({
token.type === "context"
? props.context?.records.find((record) => record.contextId === token.contextId)
: undefined;
+ const presentation = contextChipPresentation(
+ token.type === "context" ? token.kind : token.type,
+ record,
+ );
+ const icon = contextChipIcon(
+ presentation,
+ token.type === "mention" ? token.value : contextRecordFileName(record),
+ );
return {
type: token.type,
source: token.source,
start: token.start,
end: token.end,
- ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
+ accent: presentation.accent,
label:
token.type === "skill"
? (skillLabels.get(token.value) ?? token.value)
@@ -181,12 +189,8 @@ export function ComposerEditor({
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
: basename(token.value),
detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
- iconUri:
- token.type === "mention"
- ? fileIconUri(token.value)
- : record?.kind === "mention" && "path" in record
- ? fileIconUri(record.path)
- : null,
+ iconUri: contextChipIconUri(icon),
+ tintsIcon: icon.kind === "chip",
};
}),
);
diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx
index 732df5f8f2e..89fd665ab1d 100644
--- a/apps/mobile/src/native/T3ComposerEditor.native.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx
@@ -16,9 +16,13 @@ import {
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { Image, Platform, StyleSheet } from "react-native";
-import { markdownFileIconSource, markdownIconAssetUri } from "../lib/markdownFileIcons";
-import { composerChipSizeSuffix, contextChipPresentation } from "../lib/composerChipPresentation";
-import { resolveMarkdownFileIcon } from "../lib/markdownLinks";
+import {
+ composerChipSizeSuffix,
+ contextChipIcon,
+ contextChipPresentation,
+ contextRecordFileName,
+} from "../lib/composerChipPresentation";
+import { contextChipIconUri } from "../lib/contextChipIconSource";
import { MOBILE_TYPOGRAPHY } from "../lib/typography";
import { useNativePaste } from "../lib/useNativePaste";
import { FONT_FAMILIES } from "../lib/fontFamilies";
@@ -110,10 +114,6 @@ function basename(path: string): string {
return separator >= 0 ? path.slice(separator + 1) : path;
}
-function fileIconUri(path: string): string | null {
- return markdownIconAssetUri(markdownFileIconSource(resolveMarkdownFileIcon(path))) ?? null;
-}
-
export function ComposerEditor({
ref,
skills = EMPTY_SKILLS,
@@ -166,12 +166,20 @@ export function ComposerEditor({
token.type === "context"
? props.context?.records.find((record) => record.contextId === token.contextId)
: undefined;
+ const presentation = contextChipPresentation(
+ token.type === "context" ? token.kind : token.type,
+ record,
+ );
+ const icon = contextChipIcon(
+ presentation,
+ token.type === "mention" ? token.value : contextRecordFileName(record),
+ );
return {
type: token.type,
source: token.source,
start: token.start,
end: token.end,
- ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
+ accent: presentation.accent,
label:
token.type === "skill"
? (skillLabels.get(token.value) ?? token.value)
@@ -179,12 +187,8 @@ export function ComposerEditor({
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
: basename(token.value),
detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
- iconUri:
- token.type === "mention"
- ? fileIconUri(token.value)
- : record?.kind === "mention" && "path" in record
- ? fileIconUri(record.path)
- : null,
+ iconUri: contextChipIconUri(icon),
+ tintsIcon: icon.kind === "chip",
};
}),
);
diff --git a/apps/mobile/src/native/useEnrichedLinkVariants.ts b/apps/mobile/src/native/useEnrichedLinkVariants.ts
index 31f97493739..3e4a0f92b7c 100644
--- a/apps/mobile/src/native/useEnrichedLinkVariants.ts
+++ b/apps/mobile/src/native/useEnrichedLinkVariants.ts
@@ -9,6 +9,7 @@ import type { ComposerContextRecord } from "@t3tools/contracts";
import { contextChipPresentation } from "../lib/composerChipPresentation";
import { CONTEXT_CHIP_ICON_SOURCES } from "../lib/contextChipIcons.generated";
import { FONT_FAMILIES } from "../lib/fontFamilies";
+import { contextChipIconSource } from "../lib/contextChipIconSource";
import { markdownFileIconSource } from "../lib/markdownFileIcons";
import { markdownLinkIconSource } from "../lib/markdownLinkIcons";
import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
@@ -21,15 +22,8 @@ import {
enrichedLinkVariantPattern,
enrichedSkillDisplayName,
enrichedSkillReference,
- type EnrichedChipIcon,
} from "../lib/enrichedLinkPresentation";
-function chipIconSource(icon: EnrichedChipIcon) {
- return icon.kind === "chip"
- ? CONTEXT_CHIP_ICON_SOURCES[icon.name]
- : markdownFileIconSource(icon.name);
-}
-
export function enrichedContextLinkCustomization(
href: string,
records?: ReadonlyArray<ComposerContextRecord>,
@@ -38,7 +32,7 @@ export function enrichedContextLinkCustomization(
if (!context) return undefined;
return {
label: context.label,
- icon: chipIconSource(context.icon),
+ icon: contextChipIconSource(context.icon),
chip: { accent: context.accent, tintsIcon: context.icon.kind === "chip" },
};
}