Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e65de2ee3 | ||
|
|
df9fea5a6f |
No files matched your search
@@ -23,54 +23,46 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
const DEVELOPMENT_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-dev.png",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
|
||||
androidAdaptiveBackgroundColor: "#00639B",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#00639B",
|
||||
} as const;
|
||||
|
||||
const RELEASE_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-prod.png",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-mark.png",
|
||||
androidAdaptiveBackgroundColor: "#000000",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#FFFFFF",
|
||||
} as const;
|
||||
|
||||
const VARIANT_CONFIG = {
|
||||
const VARIANT_CONFIG: Record<
|
||||
AppVariant,
|
||||
{
|
||||
readonly appName: string;
|
||||
readonly scheme: string;
|
||||
readonly iosIcon: string;
|
||||
readonly splashIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
}
|
||||
> = {
|
||||
development: {
|
||||
appName: "T3 Code Dev",
|
||||
scheme: "t3code-dev",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: DEVELOPMENT_ASSETS,
|
||||
},
|
||||
preview: {
|
||||
appName: "T3 Code Preview",
|
||||
scheme: "t3code-preview",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
scheme: "t3code",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
} as const;
|
||||
};
|
||||
|
||||
function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
switch (value) {
|
||||
@@ -129,7 +121,7 @@ const config: ExpoConfig = {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: variant.assets.appIcon,
|
||||
icon: "./assets/icon.png",
|
||||
userInterfaceStyle: "automatic",
|
||||
updates: {
|
||||
enabled: true,
|
||||
@@ -138,7 +130,7 @@ const config: ExpoConfig = {
|
||||
fallbackToCacheTimeout: 0,
|
||||
},
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
@@ -159,12 +151,13 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
android: {
|
||||
icon: variant.assets.appIcon,
|
||||
icon: "./assets/icon.png",
|
||||
package: variant.androidPackage,
|
||||
adaptiveIcon: {
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
monochromeImage: variant.assets.androidMonochromeIcon,
|
||||
backgroundColor: "#E6F4FE",
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundImage: "./assets/android-icon-background.png",
|
||||
monochromeImage: "./assets/android-icon-monochrome.png",
|
||||
},
|
||||
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
|
||||
// JS back handling survives it via react-native's Android 16 shim plus
|
||||
@@ -172,7 +165,7 @@ const config: ExpoConfig = {
|
||||
predictiveBackGestureEnabled: true,
|
||||
},
|
||||
web: {
|
||||
favicon: variant.assets.appIcon,
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-asset",
|
||||
@@ -202,14 +195,6 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
icon: variant.assets.androidNotificationIcon,
|
||||
color: variant.assets.androidNotificationColor,
|
||||
mode: APP_VARIANT === "development" ? "development" : "production",
|
||||
},
|
||||
],
|
||||
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
|
||||
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
|
||||
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
|
||||
@@ -221,8 +206,8 @@ const config: ExpoConfig = {
|
||||
// the shortcut items set in src/features/shortcuts.
|
||||
androidIcons: {
|
||||
shortcut_icon: {
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundColor: "#E6F4FE",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -232,18 +217,17 @@ const config: ExpoConfig = {
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
image: variant.assets.splashIcon,
|
||||
image: variant.splashIcon,
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#ffffff",
|
||||
imageWidth: 220,
|
||||
dark: {
|
||||
image: variant.assets.splashIcon,
|
||||
image: variant.splashIcon,
|
||||
backgroundColor: "#0a0a0a",
|
||||
},
|
||||
},
|
||||
|
||||
|
Before Width: | Height: | Size: 323 KiB After Width: | Height: | Size: 323 KiB |
|
After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 733 B |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 2.0 MiB |
@@ -1,315 +0,0 @@
|
||||
package expo.modules.t3reviewdiff
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
internal class ReviewDiffCanvasDrawing(context: Context) {
|
||||
private val density = context.resources.displayMetrics.density
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
|
||||
val backgroundPaint = Paint()
|
||||
val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
|
||||
private val italicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
|
||||
}
|
||||
private val boldItalicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
|
||||
}
|
||||
|
||||
init {
|
||||
textPaint.typeface = ReviewDiffTypefaces.regular
|
||||
uiPaint.typeface = Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val left = style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
|
||||
}
|
||||
|
||||
fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val chevron = fileHeaderChevronRect(top, bottom, style)
|
||||
return RectF(
|
||||
chevron.right + 8f * density,
|
||||
chevron.top,
|
||||
chevron.right + 28f * density,
|
||||
chevron.bottom,
|
||||
)
|
||||
}
|
||||
|
||||
fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val right = width - style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(
|
||||
right - 20f * density,
|
||||
centerY - 10f * density,
|
||||
right,
|
||||
centerY + 10f * density,
|
||||
)
|
||||
}
|
||||
|
||||
fun drawDisclosureChevron(
|
||||
canvas: Canvas,
|
||||
rect: RectF,
|
||||
color: Int,
|
||||
collapsed: Boolean
|
||||
) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path()
|
||||
if (collapsed) {
|
||||
path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
|
||||
path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
|
||||
path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
|
||||
} else {
|
||||
path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
|
||||
path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
|
||||
val color = when (changeType) {
|
||||
"new" -> theme.addText
|
||||
"deleted" -> theme.deleteText
|
||||
else -> theme.hunkText
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
|
||||
if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
|
||||
drawRenameChevronIcon(canvas, rect, color)
|
||||
} else {
|
||||
backgroundPaint.color = color
|
||||
canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
|
||||
if (checked) {
|
||||
backgroundPaint.color = theme.hunkText
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = if (checked) theme.hunkText else theme.mutedText
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
if (checked) {
|
||||
borderPaint.color = theme.background
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path().apply {
|
||||
moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
|
||||
lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
|
||||
lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.7f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
canvas.drawOval(rect, borderPaint)
|
||||
canvas.drawLine(
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.3f,
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.58f,
|
||||
borderPaint,
|
||||
)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
|
||||
}
|
||||
|
||||
fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
|
||||
paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
||||
configureTextPaint(paint, color, size)
|
||||
}
|
||||
|
||||
fun configureMonospacePaint(color: Int, size: Float, weight: String) {
|
||||
textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
|
||||
configureTextPaint(textPaint, color, size)
|
||||
}
|
||||
|
||||
fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
|
||||
val tokenBold = fontStyle and 2 != 0
|
||||
val italic = fontStyle and 1 != 0
|
||||
textPaint.typeface = when {
|
||||
tokenBold && italic -> boldItalicCodeTypeface
|
||||
tokenBold -> ReviewDiffTypefaces.bold
|
||||
italic -> italicCodeTypeface
|
||||
else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
|
||||
}
|
||||
configureTextPaint(textPaint, color, style.codeFontSizePx)
|
||||
textPaint.isUnderlineText = fontStyle and 4 != 0
|
||||
}
|
||||
|
||||
fun lineNumberColor(change: String): Int = when (change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.mutedText
|
||||
}
|
||||
|
||||
fun drawDeleteStripes(
|
||||
canvas: Canvas,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
width: Float,
|
||||
color: Int
|
||||
) {
|
||||
backgroundPaint.color = color
|
||||
var y = top.toFloat()
|
||||
while (y < bottom) {
|
||||
canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
|
||||
y += 2f * density
|
||||
}
|
||||
}
|
||||
|
||||
fun drawWordDiffRanges(
|
||||
canvas: Canvas,
|
||||
row: DiffRow,
|
||||
codeX: Float,
|
||||
top: Int,
|
||||
bottom: Int
|
||||
) {
|
||||
if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
|
||||
val color = if (row.change == "add") theme.addBar else theme.deleteBar
|
||||
backgroundPaint.color = withAlpha(color, 71)
|
||||
val characterWidth = textPaint.measureText("M")
|
||||
val fontHeight = textPaint.fontMetrics.run { descent - ascent }
|
||||
val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
|
||||
val highlightTop = (top + bottom - highlightHeight) / 2f
|
||||
row.wordDiffRanges.forEach { range ->
|
||||
val left = codeX + range.start * characterWidth
|
||||
val right = max(left + 2f * density, codeX + range.end * characterWidth)
|
||||
canvas.drawRoundRect(
|
||||
RectF(left, highlightTop, right, highlightTop + highlightHeight),
|
||||
3f * density,
|
||||
3f * density,
|
||||
backgroundPaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun drawFileHeaderPathScrollFades(
|
||||
canvas: Canvas,
|
||||
pathRect: RectF,
|
||||
horizontalOffset: Int,
|
||||
maxOffset: Int
|
||||
) {
|
||||
if (maxOffset <= 0 || pathRect.width() <= 0f) return
|
||||
val fadeWidth = min(28f * density, pathRect.width() / 3f)
|
||||
if (horizontalOffset > 0) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
|
||||
fadesToRight = false,
|
||||
)
|
||||
}
|
||||
if (horizontalOffset < maxOffset) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
|
||||
fadesToRight = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val chevronWidth = 3.6f * density
|
||||
val chevronHeight = 8f * density
|
||||
val gap = 2.4f * density
|
||||
val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
|
||||
val path = Path()
|
||||
for (x in listOf(startX, startX + chevronWidth + gap)) {
|
||||
path.moveTo(x, rect.centerY() - chevronHeight / 2f)
|
||||
path.lineTo(x + chevronWidth, rect.centerY())
|
||||
path.lineTo(x, rect.centerY() + chevronHeight / 2f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
|
||||
private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
|
||||
paint.textSize = size
|
||||
paint.color = color
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.textAlign = Paint.Align.LEFT
|
||||
paint.isUnderlineText = false
|
||||
paint.isFakeBoldText = false
|
||||
paint.clearShadowLayer()
|
||||
}
|
||||
|
||||
private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
|
||||
val opaque = theme.headerBackground
|
||||
val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
|
||||
backgroundPaint.shader = LinearGradient(
|
||||
rect.left,
|
||||
rect.centerY(),
|
||||
rect.right,
|
||||
rect.centerY(),
|
||||
if (fadesToRight) transparent else opaque,
|
||||
if (fadesToRight) opaque else transparent,
|
||||
Shader.TileMode.CLAMP,
|
||||
)
|
||||
canvas.drawRect(rect, backgroundPaint)
|
||||
backgroundPaint.shader = null
|
||||
}
|
||||
|
||||
private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
|
||||
}
|
||||
|
||||
private object ReviewDiffTypefaces {
|
||||
val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
|
||||
private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
|
||||
val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
|
||||
|
||||
fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold" -> medium
|
||||
"bold", "heavy", "black" -> bold
|
||||
else -> regular
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Typeface
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.VelocityTracker
|
||||
@@ -19,7 +19,6 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
@@ -50,13 +49,12 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
private val verticalScroller = OverScroller(context)
|
||||
private val horizontalScroller = OverScroller(context)
|
||||
private var dragAxis: DragAxis? = null
|
||||
private var horizontalDragTarget: HorizontalPanTarget? = null
|
||||
private var lastTouchX = 0f
|
||||
private var lastTouchY = 0f
|
||||
private var velocityTracker: VelocityTracker? = null
|
||||
|
||||
init {
|
||||
canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }
|
||||
canvasView.onRowTap = { row, gesture -> handleRowTap(row, gesture) }
|
||||
canvasView.onVisibleRowsChanged = { first, last ->
|
||||
onDebug(
|
||||
mapOf(
|
||||
@@ -88,13 +86,12 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
lastVisibleFileId = null
|
||||
pendingInitialScroll = true
|
||||
canvasView.setVerticalOffset(0)
|
||||
canvasView.resetHorizontalOffsets()
|
||||
canvasView.setHorizontalOffset(0)
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
fun setCollapsedFileIdsJson(value: String) {
|
||||
collapsedFileIds = parseStringSet(value)
|
||||
canvasView.collapsedFileIds = collapsedFileIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -110,7 +107,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
|
||||
fun setCollapsedCommentIdsJson(value: String) {
|
||||
collapsedCommentIds = parseStringSet(value)
|
||||
canvasView.collapsedCommentIds = collapsedCommentIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -206,7 +202,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
verticalScroller.forceFinished(true)
|
||||
horizontalScroller.forceFinished(true)
|
||||
dragAxis = null
|
||||
horizontalDragTarget = canvasView.horizontalPanTarget(event.y)
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
parent?.requestDisallowInterceptTouchEvent(true)
|
||||
@@ -217,13 +212,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
val deltaX = event.x - lastTouchX
|
||||
val deltaY = event.y - lastTouchY
|
||||
if (max(abs(deltaX), abs(deltaY)) > touchSlop) {
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) {
|
||||
DragAxis.VERTICAL
|
||||
} else {
|
||||
horizontalDragTarget
|
||||
?.takeIf { canvasView.maxHorizontalOffset(it) > 0 }
|
||||
?.let { DragAxis.HORIZONTAL }
|
||||
}
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) DragAxis.VERTICAL else DragAxis.HORIZONTAL
|
||||
}
|
||||
}
|
||||
return dragAxis != null
|
||||
@@ -249,7 +238,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
) {
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
horizontalDragTarget = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
}
|
||||
return handled
|
||||
@@ -265,7 +253,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
if (axis == DragAxis.VERTICAL) {
|
||||
canvasView.scrollByVertical(deltaY)
|
||||
} else {
|
||||
horizontalDragTarget?.let { canvasView.scrollByHorizontal(deltaX, it) }
|
||||
canvasView.scrollByHorizontal(deltaX)
|
||||
}
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
@@ -288,7 +276,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
)
|
||||
postInvalidateOnAnimation()
|
||||
}
|
||||
} else if (horizontalDragTarget?.kind == HorizontalPanKind.CODE) {
|
||||
} else {
|
||||
val velocity = -(velocityTracker?.xVelocity ?: 0f).toInt()
|
||||
if (abs(velocity) >= minimumFlingVelocity) {
|
||||
horizontalScroller.fling(
|
||||
@@ -306,7 +294,6 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
dragAxis = null
|
||||
horizontalDragTarget = null
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
@@ -338,7 +325,11 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
|
||||
filtered.add(row)
|
||||
} else if (!currentFileCollapsed) {
|
||||
filtered.add(row)
|
||||
if (row.kind != "comment" || !collapsedCommentIds.contains(row.id)) {
|
||||
filtered.add(row)
|
||||
} else {
|
||||
filtered.add(row.copy(commentText = "Comment collapsed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
visibleRows = filtered
|
||||
@@ -348,11 +339,10 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) {
|
||||
private fun handleRowTap(row: DiffRow, gesture: String) {
|
||||
when (row.kind) {
|
||||
"file" -> {
|
||||
if (gesture != "tap") return
|
||||
if (target == RowTapTarget.VIEWED_CHECKBOX) {
|
||||
if (gesture == "longPress") {
|
||||
onToggleViewedFile(mapOf("fileId" to row.resolvedFileId))
|
||||
} else {
|
||||
onToggleFile(mapOf("fileId" to row.resolvedFileId))
|
||||
@@ -418,22 +408,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
|
||||
private enum class RowTapTarget {
|
||||
ROW,
|
||||
VIEWED_CHECKBOX
|
||||
}
|
||||
|
||||
private enum class HorizontalPanKind {
|
||||
CODE,
|
||||
FILE_HEADER_PATH
|
||||
}
|
||||
|
||||
private data class HorizontalPanTarget(
|
||||
val fileId: String,
|
||||
val kind: HorizontalPanKind
|
||||
)
|
||||
|
||||
internal data class DiffRow(
|
||||
private data class DiffRow(
|
||||
val kind: String,
|
||||
val id: String,
|
||||
val fileId: String,
|
||||
@@ -447,7 +422,6 @@ internal data class DiffRow(
|
||||
val change: String,
|
||||
val oldLineNumber: Int?,
|
||||
val newLineNumber: Int?,
|
||||
val wordDiffRanges: List<DiffWordDiffRange>,
|
||||
val commentText: String,
|
||||
val commentRangeLabel: String,
|
||||
val commentSectionTitle: String
|
||||
@@ -455,18 +429,13 @@ internal data class DiffRow(
|
||||
val resolvedFileId: String get() = fileId.ifEmpty { id }
|
||||
}
|
||||
|
||||
internal data class DiffWordDiffRange(
|
||||
val start: Int,
|
||||
val end: Int
|
||||
)
|
||||
|
||||
private data class DiffToken(
|
||||
val content: String,
|
||||
val color: Int?,
|
||||
val fontStyle: Int
|
||||
)
|
||||
|
||||
internal data class DiffTheme(
|
||||
private data class DiffTheme(
|
||||
val background: Int,
|
||||
val text: Int,
|
||||
val mutedText: Int,
|
||||
@@ -542,25 +511,14 @@ internal data class DiffTheme(
|
||||
}
|
||||
}
|
||||
|
||||
internal data class DiffStyle(
|
||||
private data class DiffStyle(
|
||||
val rowHeightPx: Float,
|
||||
val gutterWidthPx: Float,
|
||||
val codePaddingPx: Float,
|
||||
val changeBarWidthPx: Float,
|
||||
val fileHeaderHeightPx: Float,
|
||||
val fileHeaderHorizontalPaddingPx: Float,
|
||||
val codeFontSizePx: Float,
|
||||
val codeFontWeight: String,
|
||||
val lineNumberFontSizePx: Float,
|
||||
val lineNumberFontWeight: String,
|
||||
val hunkFontSizePx: Float,
|
||||
val hunkFontWeight: String,
|
||||
val fileHeaderFontSizePx: Float,
|
||||
val fileHeaderFontWeight: String,
|
||||
val fileHeaderMetaFontSizePx: Float,
|
||||
val fileHeaderMetaFontWeight: String,
|
||||
val fileHeaderSubtextFontSizePx: Float,
|
||||
val fileHeaderSubtextFontWeight: String
|
||||
val lineNumberFontSizePx: Float
|
||||
) {
|
||||
companion object {
|
||||
fun defaults(density: Float): DiffStyle = DiffStyle(
|
||||
@@ -569,19 +527,8 @@ internal data class DiffStyle(
|
||||
codePaddingPx = 10f * density,
|
||||
changeBarWidthPx = 3f * density,
|
||||
fileHeaderHeightPx = 44f * density,
|
||||
fileHeaderHorizontalPaddingPx = 10f * density,
|
||||
codeFontSizePx = 12f * density,
|
||||
codeFontWeight = "regular",
|
||||
lineNumberFontSizePx = 10f * density,
|
||||
lineNumberFontWeight = "regular",
|
||||
hunkFontSizePx = 11f * density,
|
||||
hunkFontWeight = "medium",
|
||||
fileHeaderFontSizePx = 11f * density,
|
||||
fileHeaderFontWeight = "semibold",
|
||||
fileHeaderMetaFontSizePx = 10f * density,
|
||||
fileHeaderMetaFontWeight = "semibold",
|
||||
fileHeaderSubtextFontSizePx = 11f * density,
|
||||
fileHeaderSubtextFontWeight = "medium",
|
||||
)
|
||||
|
||||
fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try {
|
||||
@@ -592,50 +539,11 @@ internal data class DiffStyle(
|
||||
codePaddingPx = json.floatDp("codePadding", fallback.codePaddingPx, density),
|
||||
changeBarWidthPx = json.floatDp("changeBarWidth", fallback.changeBarWidthPx, density),
|
||||
fileHeaderHeightPx = json.floatDp("fileHeaderHeight", fallback.fileHeaderHeightPx, density),
|
||||
fileHeaderHorizontalPaddingPx = json.floatDp(
|
||||
"fileHeaderHorizontalPadding",
|
||||
fallback.fileHeaderHorizontalPaddingPx,
|
||||
density,
|
||||
),
|
||||
codeFontSizePx = json.floatSp("codeFontSize", fallback.codeFontSizePx, density),
|
||||
codeFontWeight = json.optString("codeFontWeight", fallback.codeFontWeight),
|
||||
lineNumberFontSizePx = json.floatSp(
|
||||
"lineNumberFontSize",
|
||||
fallback.lineNumberFontSizePx,
|
||||
density,
|
||||
),
|
||||
lineNumberFontWeight = json.optString(
|
||||
"lineNumberFontWeight",
|
||||
fallback.lineNumberFontWeight,
|
||||
),
|
||||
hunkFontSizePx = json.floatSp("hunkFontSize", fallback.hunkFontSizePx, density),
|
||||
hunkFontWeight = json.optString("hunkFontWeight", fallback.hunkFontWeight),
|
||||
fileHeaderFontSizePx = json.floatSp(
|
||||
"fileHeaderFontSize",
|
||||
fallback.fileHeaderFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderFontWeight = json.optString(
|
||||
"fileHeaderFontWeight",
|
||||
fallback.fileHeaderFontWeight,
|
||||
),
|
||||
fileHeaderMetaFontSizePx = json.floatSp(
|
||||
"fileHeaderMetaFontSize",
|
||||
fallback.fileHeaderMetaFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderMetaFontWeight = json.optString(
|
||||
"fileHeaderMetaFontWeight",
|
||||
fallback.fileHeaderMetaFontWeight,
|
||||
),
|
||||
fileHeaderSubtextFontSizePx = json.floatSp(
|
||||
"fileHeaderSubtextFontSize",
|
||||
fallback.fileHeaderSubtextFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderSubtextFontWeight = json.optString(
|
||||
"fileHeaderSubtextFontWeight",
|
||||
fallback.fileHeaderSubtextFontWeight,
|
||||
density
|
||||
),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
@@ -646,54 +554,35 @@ internal data class DiffStyle(
|
||||
|
||||
private class DiffCanvasView(context: Context) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
private val drawing = ReviewDiffCanvasDrawing(context)
|
||||
private val backgroundPaint = drawing.backgroundPaint
|
||||
private val borderPaint = drawing.borderPaint
|
||||
private val textPaint = drawing.textPaint
|
||||
private val boldTextPaint = drawing.uiPaint
|
||||
private val backgroundPaint = Paint()
|
||||
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = Typeface.MONOSPACE }
|
||||
private val boldTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
private val gestureDetector = GestureDetector(
|
||||
context,
|
||||
object : GestureDetector.SimpleOnGestureListener() {
|
||||
override fun onDown(event: MotionEvent): Boolean = true
|
||||
|
||||
override fun onSingleTapUp(event: MotionEvent): Boolean {
|
||||
rowHitAt(event.y)?.let { hit ->
|
||||
val target = if (
|
||||
hit.row.kind == "file" &&
|
||||
drawing.fileHeaderCheckboxRect(
|
||||
hit.top,
|
||||
hit.bottom,
|
||||
width,
|
||||
style
|
||||
).contains(event.x, event.y)
|
||||
) {
|
||||
RowTapTarget.VIEWED_CHECKBOX
|
||||
} else {
|
||||
RowTapTarget.ROW
|
||||
}
|
||||
onRowTap?.invoke(hit.row, "tap", target)
|
||||
}
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "tap") }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onLongPress(event: MotionEvent) {
|
||||
rowHitAt(event.y)?.row
|
||||
?.takeIf { it.kind == "line" }
|
||||
?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) }
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "longPress") }
|
||||
}
|
||||
},
|
||||
)
|
||||
private var rowOffsets = intArrayOf(0)
|
||||
private var verticalOffset = 0
|
||||
private var horizontalOffset = 0
|
||||
private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()
|
||||
private var lastVisibleRange: Pair<Int, Int>? = null
|
||||
|
||||
var rows: List<DiffRow> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
headerPathOffsetsByFileId.keys.retainAll(
|
||||
value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),
|
||||
)
|
||||
rebuildOffsets()
|
||||
}
|
||||
var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()
|
||||
@@ -706,16 +595,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedFileIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedCommentIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
rebuildOffsets()
|
||||
}
|
||||
var selectedRowIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -724,7 +603,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
set(value) {
|
||||
field = value
|
||||
drawing.theme = value
|
||||
invalidate()
|
||||
}
|
||||
var style: DiffStyle = DiffStyle.defaults(density)
|
||||
@@ -736,10 +614,9 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
set(value) {
|
||||
field = max(value, suggestedMinimumWidth)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
invalidate()
|
||||
}
|
||||
var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null
|
||||
var onRowTap: ((DiffRow, String) -> Unit)? = null
|
||||
var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
@@ -753,7 +630,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
super.onSizeChanged(width, height, oldWidth, oldHeight)
|
||||
setVerticalOffset(verticalOffset)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -805,63 +681,27 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun scrollByHorizontal(delta: Int, target: HorizontalPanTarget) {
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
setHeaderPathOffset(
|
||||
target.fileId,
|
||||
(headerPathOffsetsByFileId[target.fileId] ?: 0) + delta,
|
||||
)
|
||||
} else {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
}
|
||||
fun scrollByHorizontal(delta: Int) {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
}
|
||||
|
||||
fun horizontalOffset(): Int = horizontalOffset
|
||||
|
||||
fun maxHorizontalOffset(): Int = max(0, contentWidthPx - width)
|
||||
|
||||
fun maxHorizontalOffset(target: HorizontalPanTarget): Int =
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
maxHeaderPathOffset(target.fileId)
|
||||
} else {
|
||||
maxHorizontalOffset()
|
||||
}
|
||||
|
||||
fun horizontalPanTarget(y: Float): HorizontalPanTarget? {
|
||||
val row = rowHitAt(y)?.row ?: return null
|
||||
return HorizontalPanTarget(
|
||||
fileId = row.resolvedFileId,
|
||||
kind = if (row.kind == "file") HorizontalPanKind.FILE_HEADER_PATH else HorizontalPanKind.CODE,
|
||||
)
|
||||
}
|
||||
|
||||
fun resetHorizontalOffsets() {
|
||||
setHorizontalOffset(0)
|
||||
if (headerPathOffsetsByFileId.isNotEmpty()) {
|
||||
headerPathOffsetsByFileId.clear()
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private fun rebuildOffsets() {
|
||||
rowOffsets = IntArray(rows.size + 1)
|
||||
rows.forEachIndexed { index, row ->
|
||||
rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)
|
||||
}
|
||||
setVerticalOffset(verticalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
requestLayout()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun rowHeight(row: DiffRow): Int = when (row.kind) {
|
||||
"file" -> style.fileHeaderHeightPx.toInt()
|
||||
"notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt())
|
||||
"comment" -> if (collapsedCommentIds.contains(row.id)) {
|
||||
(44 * density).toInt()
|
||||
} else {
|
||||
(124 * density).toInt()
|
||||
}
|
||||
"comment" -> max((style.rowHeightPx * 3.2f).toInt(), (56 * density).toInt())
|
||||
else -> style.rowHeightPx.toInt()
|
||||
}.coerceAtLeast(1)
|
||||
|
||||
@@ -881,20 +721,13 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
return low.coerceIn(0, rows.lastIndex)
|
||||
}
|
||||
|
||||
private fun rowHitAt(y: Float): RowHit? {
|
||||
private fun rowAt(y: Float): DiffRow? {
|
||||
stickyFileHeader(firstVisibleRow())?.let { sticky ->
|
||||
if (y >= max(0, sticky.top).toFloat() && y < sticky.bottom.toFloat()) {
|
||||
return rows.getOrNull(sticky.index)?.let { RowHit(it, sticky.top, sticky.bottom) }
|
||||
return rows.getOrNull(sticky.index)
|
||||
}
|
||||
}
|
||||
val index = rowIndexAt(verticalOffset + y.toInt())
|
||||
return rows.getOrNull(index)?.let {
|
||||
RowHit(
|
||||
row = it,
|
||||
top = rowOffsets[index] - verticalOffset,
|
||||
bottom = rowOffsets[index + 1] - verticalOffset,
|
||||
)
|
||||
}
|
||||
return rows.getOrNull(rowIndexAt(verticalOffset + y.toInt()))
|
||||
}
|
||||
|
||||
private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)
|
||||
@@ -921,140 +754,23 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
|
||||
private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
|
||||
val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.drawDisclosureChevron(
|
||||
canvas,
|
||||
chevronRect,
|
||||
theme.mutedText,
|
||||
collapsed = collapsedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
drawing.drawFileIcon(canvas, iconRect, row.changeType)
|
||||
drawing.drawViewedCheckbox(
|
||||
canvas,
|
||||
checkboxRect,
|
||||
viewedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val deleteText = "-${row.deletions}"
|
||||
val deleteWidth = boldTextPaint.measureText(deleteText)
|
||||
val addText = "+${row.additions}"
|
||||
val addWidth = boldTextPaint.measureText(addText)
|
||||
val countGap = 4f * density
|
||||
val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint)
|
||||
canvas.drawText(deleteText, countsX, baseline, boldTextPaint)
|
||||
boldTextPaint.color = theme.addText
|
||||
canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint)
|
||||
|
||||
val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX)
|
||||
val maxPathOffset = maxHeaderPathOffset(pathLayout)
|
||||
val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0)
|
||||
.coerceIn(0, maxPathOffset)
|
||||
canvas.save()
|
||||
canvas.clipRect(pathLayout.rect)
|
||||
canvas.drawText(
|
||||
pathLayout.displayPath,
|
||||
pathLayout.rect.left - pathOffset,
|
||||
centeredBaseline(top, bottom, boldTextPaint),
|
||||
boldTextPaint,
|
||||
)
|
||||
canvas.restore()
|
||||
drawing.drawFileHeaderPathScrollFades(
|
||||
canvas,
|
||||
pathLayout.rect,
|
||||
pathOffset,
|
||||
maxPathOffset,
|
||||
)
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint.apply { textSize = 13f * density })
|
||||
boldTextPaint.color = theme.text
|
||||
val marker = if (viewedFileIds.contains(row.resolvedFileId)) "[x] " else "[ ] "
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 11f * density
|
||||
val stats = "+${row.additions} -${row.deletions}"
|
||||
val statsX = max(12f * density, width - textPaint.measureText(stats) - 16f * density)
|
||||
val title = ellipsize(marker + row.filePath, boldTextPaint, statsX - 28f * density)
|
||||
canvas.drawText(title, 12f * density, baseline, boldTextPaint)
|
||||
canvas.drawText(stats, statsX, baseline, textPaint)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
private fun fileHeaderPathLayout(
|
||||
row: DiffRow,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
iconRect: RectF,
|
||||
countsX: Float
|
||||
): FileHeaderPathLayout {
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.text,
|
||||
size = style.fileHeaderFontSizePx,
|
||||
weight = style.fileHeaderFontWeight,
|
||||
)
|
||||
val pathX = iconRect.right + 10f * density
|
||||
val pathWidth = max(24f * density, countsX - pathX - 12f * density)
|
||||
val centerY = (top + bottom) / 2f
|
||||
val displayPath = if (
|
||||
!row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath
|
||||
) {
|
||||
"${row.previousPath} -> ${row.filePath}"
|
||||
} else {
|
||||
row.filePath
|
||||
}
|
||||
return FileHeaderPathLayout(
|
||||
displayPath = displayPath,
|
||||
rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density),
|
||||
)
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(fileId: String): Int {
|
||||
val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0
|
||||
val top = 0
|
||||
val bottom = rowHeight(row)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val countsX = checkboxRect.left - 10f * density -
|
||||
boldTextPaint.measureText("-${row.deletions}") - 4f * density -
|
||||
boldTextPaint.measureText("+${row.additions}")
|
||||
return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX))
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max(
|
||||
0,
|
||||
ceil(boldTextPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(),
|
||||
)
|
||||
|
||||
private fun setHeaderPathOffset(fileId: String, value: Int) {
|
||||
val nextOffset = value.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if ((headerPathOffsetsByFileId[fileId] ?: 0) == nextOffset) return
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun clampHeaderPathOffsets() {
|
||||
headerPathOffsetsByFileId.keys.toList().forEach { fileId ->
|
||||
val nextOffset = (headerPathOffsetsByFileId[fileId] ?: 0)
|
||||
.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if (nextOffset == 0) {
|
||||
headerPathOffsetsByFileId.remove(fileId)
|
||||
} else {
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
drawing.configureMonospacePaint(
|
||||
color = theme.hunkText,
|
||||
size = style.hunkFontSizePx,
|
||||
weight = style.hunkFontWeight,
|
||||
)
|
||||
textPaint.color = theme.hunkText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(
|
||||
row.text.ifEmpty { row.content },
|
||||
@@ -1066,82 +782,36 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val iconSize = 16f * density
|
||||
val iconRect = RectF(
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density,
|
||||
(top + bottom - iconSize) / 2f,
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
|
||||
(top + bottom + iconSize) / 2f,
|
||||
)
|
||||
drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val textX = iconRect.right + 10f * density
|
||||
canvas.drawText(
|
||||
ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx),
|
||||
textX,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(row.text, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val cardRect = RectF(
|
||||
8f * density,
|
||||
top + 5f * density,
|
||||
width - 8f * density,
|
||||
bottom - 5f * density,
|
||||
fill(
|
||||
canvas,
|
||||
theme.headerBackground,
|
||||
style.gutterWidthPx,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat()
|
||||
)
|
||||
backgroundPaint.color = theme.headerBackground
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint)
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = withAlpha(theme.border, 217)
|
||||
borderPaint.strokeWidth = density
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
|
||||
val collapsed = collapsedCommentIds.contains(row.id)
|
||||
val chevronRect = RectF(
|
||||
cardRect.left + 10f * density,
|
||||
cardRect.top + 11f * density,
|
||||
cardRect.left + 26f * density,
|
||||
cardRect.top + 27f * density,
|
||||
)
|
||||
drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}"
|
||||
canvas.drawText(
|
||||
ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density),
|
||||
chevronRect.right + 10f * density,
|
||||
cardRect.top + 22f * density,
|
||||
textPaint,
|
||||
)
|
||||
if (!collapsed) {
|
||||
textPaint.color = theme.text
|
||||
val bodyX = cardRect.left + 18f * density
|
||||
boldTextPaint.color = theme.text
|
||||
boldTextPaint.textSize = 12f * density
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(
|
||||
ellipsize(
|
||||
row.commentText.ifEmpty { "Comment" },
|
||||
textPaint,
|
||||
cardRect.right - bodyX - 18f * density
|
||||
),
|
||||
bodyX,
|
||||
cardRect.top + 58f * density,
|
||||
textPaint,
|
||||
row.commentSectionTitle.ifEmpty { row.commentRangeLabel.ifEmpty { "Comment" } },
|
||||
codeX,
|
||||
top + 20f * density,
|
||||
boldTextPaint,
|
||||
)
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 12f * density
|
||||
canvas.drawText(row.commentText, codeX, top + 42f * density, textPaint)
|
||||
}
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
@Suppress("CyclomaticComplexMethod")
|
||||
@@ -1152,79 +822,65 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
else -> theme.background
|
||||
}
|
||||
fill(canvas, background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
if (style.changeBarWidthPx > 0) {
|
||||
when (row.change) {
|
||||
"add" -> fill(
|
||||
canvas,
|
||||
theme.addBar,
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
"delete" -> drawing.drawDeleteStripes(
|
||||
canvas,
|
||||
top,
|
||||
bottom,
|
||||
style.changeBarWidthPx,
|
||||
theme.deleteBar,
|
||||
)
|
||||
}
|
||||
}
|
||||
val selected = selectedRowIds.contains(row.id)
|
||||
if (selected) {
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, 56),
|
||||
withAlpha(theme.hunkText, if (theme.background == Color.WHITE) 54 else 76),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat(),
|
||||
)
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, 242),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
}
|
||||
val barColor = when (row.change) {
|
||||
"add" -> theme.addBar
|
||||
"delete" -> theme.deleteBar
|
||||
else -> Color.TRANSPARENT
|
||||
}
|
||||
if (barColor != Color.TRANSPARENT && style.changeBarWidthPx > 0) {
|
||||
fill(canvas, barColor, 0f, top.toFloat(), style.changeBarWidthPx, bottom.toFloat())
|
||||
}
|
||||
|
||||
val tokens = tokensByRowId[row.id]
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
drawing.configureCodePaint(theme.text, 0, style)
|
||||
drawing.drawWordDiffRanges(canvas, row, codeX, top, bottom)
|
||||
if (tokens.isNullOrEmpty()) {
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = when (row.change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.text
|
||||
}
|
||||
canvas.drawText(row.content, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
} else {
|
||||
var x = codeX
|
||||
tokens.forEach { token ->
|
||||
drawing.configureCodePaint(token.color ?: theme.text, token.fontStyle, style)
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = token.color ?: theme.text
|
||||
textPaint.typeface = when {
|
||||
token.fontStyle and 1 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.ITALIC)
|
||||
token.fontStyle and 2 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
|
||||
else -> Typeface.MONOSPACE
|
||||
}
|
||||
canvas.drawText(token.content, x, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
x += textPaint.measureText(token.content)
|
||||
}
|
||||
textPaint.typeface = Typeface.MONOSPACE
|
||||
}
|
||||
}
|
||||
|
||||
drawLineNumber(canvas, row, top, bottom)
|
||||
}
|
||||
|
||||
private fun drawLineNumber(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
val lineNumber = row.newLineNumber ?: row.oldLineNumber ?: return
|
||||
drawing.configureMonospacePaint(
|
||||
color = drawing.lineNumberColor(row.change),
|
||||
size = style.lineNumberFontSizePx,
|
||||
weight = style.lineNumberFontWeight,
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.RIGHT
|
||||
textPaint.textSize = style.lineNumberFontSizePx
|
||||
textPaint.color = if (selected) theme.text else theme.mutedText
|
||||
val oldNumber = row.oldLineNumber?.toString().orEmpty()
|
||||
val newNumber = row.newLineNumber?.toString().orEmpty()
|
||||
val baseline = centeredBaseline(top, bottom, textPaint)
|
||||
canvas.drawText(oldNumber, style.changeBarWidthPx + 6f * density, baseline, textPaint)
|
||||
canvas.drawText(
|
||||
lineNumber.toString(),
|
||||
style.changeBarWidthPx + style.gutterWidthPx - style.codePaddingPx,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
newNumber,
|
||||
style.changeBarWidthPx + style.gutterWidthPx / 2f,
|
||||
baseline,
|
||||
textPaint
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.LEFT
|
||||
}
|
||||
|
||||
private fun drawScrollableCode(
|
||||
@@ -1316,17 +972,6 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class RowHit(
|
||||
val row: DiffRow,
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class FileHeaderPathLayout(
|
||||
val displayPath: String,
|
||||
val rect: RectF
|
||||
)
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
@@ -1350,7 +995,6 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
change = row.optString("change", "context"),
|
||||
oldLineNumber = row.optNullableInt("oldLineNumber"),
|
||||
newLineNumber = row.optNullableInt("newLineNumber"),
|
||||
wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
|
||||
commentText = row.optString("commentText"),
|
||||
commentRangeLabel = row.optString("commentRangeLabel"),
|
||||
commentSectionTitle = row.optString("commentSectionTitle"),
|
||||
@@ -1360,17 +1004,6 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {
|
||||
for (index in 0 until value.length()) {
|
||||
val range = value.optJSONObject(index) ?: continue
|
||||
val start = range.optInt("start", -1)
|
||||
val end = range.optInt("end", -1)
|
||||
if (start >= 0 && end > start) {
|
||||
add(DiffWordDiffRange(start = start, end = end))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTokensObject(value: String): Map<String, List<DiffToken>> = try {
|
||||
parseTokensObject(JSONObject(value))
|
||||
} catch (_: Exception) {
|
||||
@@ -1387,7 +1020,7 @@ private fun parseTokensObject(value: JSONObject): Map<String, List<DiffToken>> {
|
||||
val token = array.getJSONObject(index)
|
||||
DiffToken(
|
||||
content = token.optString("content"),
|
||||
color = token.optNullableString("color")?.let(::parseColorOrNull),
|
||||
color = token.optNullableString("color")?.let { parseColor(it, Color.TRANSPARENT) },
|
||||
fontStyle = token.optInt("fontStyle"),
|
||||
)
|
||||
}
|
||||
@@ -1410,12 +1043,6 @@ private fun parseColor(value: String, fallback: Int): Int = try {
|
||||
fallback
|
||||
}
|
||||
|
||||
private fun parseColorOrNull(value: String): Int? = try {
|
||||
Color.parseColor(value)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun JSONObject.optNullableString(key: String): String? =
|
||||
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
|
||||
|
||||
|
||||
@@ -440,9 +440,9 @@ export const RootStack = createNativeStackNavigator({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
options: {
|
||||
// A root-level Android formSheet does not host the native stack bar;
|
||||
// the route renders an embedded AndroidSheetHeader instead.
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
// Root screenOptions hide headers; formSheets that want the native
|
||||
// title bar opt back in with the sheet header preset.
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
|
||||
@@ -51,7 +51,6 @@ export function AndroidScreenHeader(props: {
|
||||
readonly actions?: ReadonlyArray<AndroidHeaderAction>;
|
||||
readonly trailing?: ReactNode;
|
||||
readonly onBack?: () => void;
|
||||
readonly embedded?: boolean;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
@@ -60,7 +59,7 @@ export function AndroidScreenHeader(props: {
|
||||
<View
|
||||
className="border-b border-header-border bg-header px-3 pb-2.5"
|
||||
style={{
|
||||
paddingTop: props.embedded ? 8 : Math.max(insets.top, 12),
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
}}
|
||||
>
|
||||
<View className="min-h-12 flex-row items-center gap-2">
|
||||
@@ -109,9 +108,3 @@ export function AndroidScreenHeader(props: {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function AndroidSheetHeader(
|
||||
props: Omit<Parameters<typeof AndroidScreenHeader>[0], "embedded">,
|
||||
) {
|
||||
return <AndroidScreenHeader {...props} embedded />;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { Image } from "expo-image";
|
||||
import { useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
|
||||
@@ -25,12 +24,11 @@ export function ProjectFavicon(props: {
|
||||
? null
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={faviconUrl}
|
||||
faviconUrl={renderableFaviconUrl}
|
||||
faviconUrl={faviconUrl}
|
||||
open={props.open}
|
||||
projectTitle={props.projectTitle}
|
||||
size={size}
|
||||
|
||||
@@ -2,11 +2,10 @@ import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
@@ -82,16 +81,9 @@ function ConfiguredConnectOnboardingRouteScreen() {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader
|
||||
title="Set up T3 Connect"
|
||||
actions={[{ accessibilityLabel: "Close", icon: "xmark", onPress: handleClose }]}
|
||||
/>
|
||||
) : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
<ScrollView
|
||||
alwaysBounceVertical
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useState } from "react";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -58,125 +57,115 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
|
||||
const disabledExistingBranches = new Set(disabledExistingBranchNames);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Branches & worktrees" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy ||
|
||||
worktreeBaseBranch.trim().length === 0 ||
|
||||
worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">Loading branches...</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
Loading branches...
|
||||
</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
</Text>
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -66,168 +65,160 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
|
||||
);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Commit changes" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
</Text>
|
||||
</View>
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
</Text>
|
||||
</View>
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">
|
||||
-{file.deletions}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -4,11 +4,10 @@ import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Platform, View } from "react-native";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
@@ -103,11 +102,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Confirm action" onBack={() => navigation.goBack()} />
|
||||
) : (
|
||||
<View className="min-h-4 pt-2" />
|
||||
)}
|
||||
<View className="min-h-4 pt-2" />
|
||||
|
||||
<View className="items-center gap-1 px-5 pb-3 pt-4">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
|
||||
@@ -5,12 +5,7 @@ import {
|
||||
requiresDefaultBranchConfirmation,
|
||||
} from "@t3tools/client-runtime/state/vcs";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommonActions,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
@@ -19,7 +14,6 @@ import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-scree
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../../native/StackHeader";
|
||||
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
|
||||
@@ -29,7 +23,6 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
|
||||
import { vcsEnvironment } from "../../../state/vcs";
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -262,14 +255,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
title="Review changes"
|
||||
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
|
||||
disabled={busy || !isRepo}
|
||||
onPress={() => {
|
||||
const params = { environmentId, threadId };
|
||||
navigation.dispatch(
|
||||
resolveGitOverviewReviewNavigationAction(presentation) === "replace"
|
||||
? StackActions.replace("ThreadReview", params)
|
||||
: CommonActions.navigate("ThreadReview", params),
|
||||
);
|
||||
}}
|
||||
onPress={() => navigation.navigate("ThreadReview", { environmentId, threadId })}
|
||||
/>
|
||||
<View className="ml-12 h-px bg-border" />
|
||||
<SheetListRow
|
||||
@@ -362,14 +348,12 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
collapsable={false}
|
||||
className={isInspector ? "flex-1 border-l border-border bg-sheet" : "flex-1 bg-sheet"}
|
||||
>
|
||||
{isInspector ? (
|
||||
<View
|
||||
style={{
|
||||
minHeight: props.headerInset ?? 0,
|
||||
paddingTop: props.headerInset ?? 0,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={{
|
||||
minHeight: isInspector ? (props.headerInset ?? 0) : 16,
|
||||
paddingTop: isInspector ? (props.headerInset ?? 0) : 8,
|
||||
}}
|
||||
/>
|
||||
|
||||
{isInspector ? (
|
||||
<View className="gap-1 border-b border-border px-4 pb-4 pt-3">
|
||||
@@ -399,19 +383,24 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<AndroidSheetHeader
|
||||
title={currentBranchLabel}
|
||||
subtitle={currentStatusSummary}
|
||||
onBack={() => navigation.goBack()}
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Refresh repository status",
|
||||
disabled: busy,
|
||||
icon: "arrow.clockwise",
|
||||
onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
// Compact header row: labeled branch on the left, status summary at
|
||||
// the trailing end. Horizontal padding lines the text up with the
|
||||
// rows' icon column inside the card below (20 screen + 16 card + 4
|
||||
// row). The sheet relies on pull-to-refresh instead of a corner
|
||||
// refresh button.
|
||||
<View className="flex-row items-end justify-between gap-3 px-10 pb-4 pt-4">
|
||||
<View className="shrink gap-0.5">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
Branch
|
||||
</Text>
|
||||
<Text className="text-xl font-t3-bold" numberOfLines={1}>
|
||||
{currentBranchLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-foreground-secondary pb-0.5 text-sm font-medium" numberOfLines={1}>
|
||||
{currentStatusSummary}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{content}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
|
||||
describe("resolveGitOverviewReviewNavigationAction", () => {
|
||||
it("replaces the sheet so Back returns directly to the thread", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("sheet")).toBe("replace");
|
||||
});
|
||||
|
||||
it("pushes Review normally when Git is a persistent inspector", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("inspector")).toBe("navigate");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
export function resolveGitOverviewReviewNavigationAction(
|
||||
presentation: "sheet" | "inspector",
|
||||
): "replace" | "navigate" {
|
||||
return presentation === "sheet" ? "replace" : "navigate";
|
||||
}
|
||||
@@ -348,7 +348,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
|
||||
const startFromOrigin =
|
||||
selectedProjectDraft.workspaceSelection?.startFromOrigin ??
|
||||
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
|
||||
true;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
@@ -598,8 +601,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
return;
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -229,7 +228,6 @@ describe("AssetAccess", () => {
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -237,7 +235,7 @@ describe("AssetAccess", () => {
|
||||
fallbackSuffix.slice(0, fallbackSeparatorIndex),
|
||||
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
|
||||
),
|
||||
).toBeNull();
|
||||
).toEqual({ kind: "project-favicon-fallback" });
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -41,6 +40,7 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
@@ -91,7 +91,9 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
|
||||
export type ResolvedAsset =
|
||||
| { readonly kind: "file"; readonly path: string }
|
||||
| { readonly kind: "project-favicon-fallback" };
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -324,7 +326,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -389,7 +391,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
if (claims.relativePath === null) return null;
|
||||
if (claims.relativePath === null) {
|
||||
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
|
||||
}
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
|
||||
@@ -25,7 +25,11 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import {
|
||||
ASSET_ROUTE_PREFIX,
|
||||
FALLBACK_PROJECT_FAVICON_SVG,
|
||||
resolveAsset,
|
||||
} from "./assets/AssetAccess.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
@@ -192,6 +196,17 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
if (!asset) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
if (asset.kind === "project-favicon-fallback") {
|
||||
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
|
||||
status: 200,
|
||||
contentType: "image/svg+xml",
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: {
|
||||
|
||||
@@ -137,7 +137,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
|
||||
});
|
||||
|
||||
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
|
||||
it("does not publish streaming content or non-awareness activity events", () => {
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const base = {
|
||||
sequence: 1,
|
||||
@@ -191,16 +191,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
streaming: false,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
|
||||
|
||||
@@ -67,13 +67,7 @@ export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
|
||||
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent":
|
||||
case "thread.turn-start-requested":
|
||||
// These events express intent to start work, but the shell still contains
|
||||
// the previous turn's terminal state until the provider acknowledges the
|
||||
// new turn. Publishing that snapshot can queue a fresh "Done" alert just
|
||||
// before the real running state arrives. Provider lifecycle events publish
|
||||
// the authoritative starting/running state instead.
|
||||
return false;
|
||||
return !event.payload.streaming;
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.runtime-mode-set":
|
||||
case "thread.interaction-mode-set":
|
||||
|
||||
@@ -523,6 +523,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks the origin default ref as default when no local copy exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
|
||||
yield* git(cwd, ["branch", "-D", initialBranch]);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
|
||||
assert.equal(remoteDefault?.isRemote, true);
|
||||
assert.equal(remoteDefault?.isDefault, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates, checks out, renames, and lists refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -2202,7 +2202,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
// origin/HEAD's target is the repo default even when no local
|
||||
// copy of the default branch exists.
|
||||
isDefault:
|
||||
defaultBranch !== null &&
|
||||
parsedRemoteRef?.remoteName === "origin" &&
|
||||
parsedRemoteRef.branchName === defaultBranch,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
|
||||
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
// Default the worktree base to the repo default branch (origin/HEAD), only
|
||||
// falling back to the checked-out branch when no default is known.
|
||||
const defaultBranchName = useMemo(
|
||||
() => refs.find((refName) => refName.isDefault)?.name ?? null,
|
||||
[refs],
|
||||
);
|
||||
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
|
||||
? null
|
||||
: (defaultBranchName ?? currentGitBranch);
|
||||
useEffect(() => {
|
||||
if (
|
||||
effectiveEnvMode !== "worktree" ||
|
||||
activeWorktreePath ||
|
||||
activeThreadBranch ||
|
||||
!currentGitBranch
|
||||
!worktreeBaseBranchCandidate
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setThreadBranch(currentGitBranch, null);
|
||||
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
|
||||
setThreadBranch(worktreeBaseBranchCandidate, null);
|
||||
}, [
|
||||
activeThreadBranch,
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
setThreadBranch,
|
||||
worktreeBaseBranchCandidate,
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combobox / list plumbing
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
@@ -16,7 +15,7 @@ export function ProjectFavicon(input: {
|
||||
cwd: input.cwd,
|
||||
});
|
||||
|
||||
if (!src || isProjectFaviconFallbackUrl(src)) {
|
||||
if (!src) {
|
||||
return <ProjectFaviconFallback className={input.className} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -771,7 +771,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TerminalIcon className="size-3" />
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
@@ -276,7 +276,7 @@ export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSumma
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TerminalIcon className="size-3" />
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
@@ -64,7 +64,6 @@ function makeAgentActivityRows(
|
||||
remove: () => Effect.void,
|
||||
pruneTerminal: () => Effect.void,
|
||||
listForUser: () => Effect.succeed([state]),
|
||||
getForUserThread: () => Effect.succeed(state),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -75,15 +75,6 @@ describe("AgentActivityRows", () => {
|
||||
const listError = yield* rows.listForUser({ userId: "user-2" }).pipe(Effect.flip);
|
||||
expect(listError).toMatchObject({ userId: "user-2", cause });
|
||||
expect(listError.message).toBe("Failed to list agent activity state for user user-2.");
|
||||
|
||||
const getError = yield* rows
|
||||
.getForUserThread({
|
||||
userId: "user-2",
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
expect(getError).toMatchObject({ userId: "user-2", cause });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, failingDb))),
|
||||
|
||||
@@ -83,11 +83,6 @@ export class AgentActivityRows extends Context.Service<
|
||||
ReadonlyArray<RelayAgentActivityState>,
|
||||
AgentActivityRowListPersistenceError
|
||||
>;
|
||||
readonly getForUserThread: (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
}) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;
|
||||
}
|
||||
>()("t3code-relay/agentActivity/AgentActivityRows") {}
|
||||
|
||||
@@ -246,54 +241,6 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {
|
||||
return yield* db
|
||||
.select({ stateJson: relayAgentActivityRows.stateJson })
|
||||
.from(relayAgentActivityRows)
|
||||
.innerJoin(
|
||||
relayEnvironmentLinks,
|
||||
and(
|
||||
eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
|
||||
eq(
|
||||
relayEnvironmentLinks.environmentPublicKey,
|
||||
relayAgentActivityRows.environmentPublicKey,
|
||||
),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(relayEnvironmentLinks.userId, input.userId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
eq(relayAgentActivityRows.environmentId, input.environmentId),
|
||||
eq(relayAgentActivityRows.threadId, input.threadId),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(relayAgentActivityRows.updatedAt))
|
||||
.pipe(
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
|
||||
concurrency: "unbounded",
|
||||
}),
|
||||
),
|
||||
Effect.map((rows) => {
|
||||
for (const row of rows) {
|
||||
const decoded = decodeRelayAgentActivityStateJson(row);
|
||||
if (Option.isSome(decoded)) {
|
||||
return decoded.value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AgentActivityRowListPersistenceError({
|
||||
userId: input.userId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -160,13 +161,10 @@ function makeLayer(input: {
|
||||
>;
|
||||
readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;
|
||||
readonly config?: RelayConfiguration.RelayConfiguration["Service"];
|
||||
// Live agent-activity rows returned by delivery-time state rechecks.
|
||||
// Defaults to the fixture row so queued updates match unless a test is
|
||||
// explicitly exercising stale-state behavior.
|
||||
// Live agent-activity rows returned by the delivery-time start recheck.
|
||||
// Defaults to one freshly-updated running thread so queued starts stay
|
||||
// deliverable in tests that don't care about the recheck.
|
||||
readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;
|
||||
// Current per-thread rows used to reject queued updates/notifications that
|
||||
// have been superseded before APNs delivery.
|
||||
readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;
|
||||
readonly execute?: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
|
||||
@@ -184,14 +182,9 @@ function makeLayer(input: {
|
||||
listForUser: () =>
|
||||
input.activityStates !== undefined
|
||||
? Effect.succeed([...input.activityStates])
|
||||
: Effect.succeed([state]),
|
||||
getForUserThread: ({ environmentId, threadId }) =>
|
||||
Effect.succeed(
|
||||
(input.currentActivityStates ?? input.activityStates ?? [state]).find(
|
||||
(current) =>
|
||||
current.environmentId === environmentId && current.threadId === threadId,
|
||||
) ?? null,
|
||||
),
|
||||
: DateTime.now.pipe(
|
||||
Effect.map((now) => [{ ...state, updatedAt: DateTime.formatIso(now) }]),
|
||||
),
|
||||
} satisfies AgentActivityRows.AgentActivityRows["Service"]),
|
||||
Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
|
||||
send: (body) =>
|
||||
@@ -681,8 +674,6 @@ describe("ApnsDeliveries", () => {
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/",
|
||||
phase: "waiting_for_input",
|
||||
updatedAt: state.updatedAt,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -787,30 +778,6 @@ describe("ApnsDeliveries", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("does not queue a push notification when a thread starts working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.sendForTarget({
|
||||
target: {
|
||||
...target,
|
||||
push_token: "apns-device-token",
|
||||
push_to_start_token: null,
|
||||
activity_push_token: null,
|
||||
remote_started_at: null,
|
||||
},
|
||||
aggregate,
|
||||
nowMs: 5_000,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(queuedJobs).toEqual([]);
|
||||
expect(attempts).toEqual([]);
|
||||
}).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));
|
||||
});
|
||||
|
||||
it.effect("queues bounded alert notification payloads", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
|
||||
@@ -1209,150 +1176,6 @@ describe("ApnsDeliveries", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
const completedAt = "1970-01-01T00:00:01.000Z";
|
||||
const completedAggregate: RelayAgentActivityAggregateState = {
|
||||
...aggregate,
|
||||
activeCount: 0,
|
||||
updatedAt: completedAt,
|
||||
activities: [
|
||||
{
|
||||
...aggregate.activities[0]!,
|
||||
phase: "completed",
|
||||
status: "Done",
|
||||
updatedAt: completedAt,
|
||||
},
|
||||
],
|
||||
};
|
||||
const payload = makeApnsDeliveryJobPayload({
|
||||
kind: "live_activity_update",
|
||||
userId: target.user_id,
|
||||
deviceId: target.device_id,
|
||||
token: target.activity_push_token ?? "activity-token",
|
||||
aggregate: completedAggregate,
|
||||
alert: { title: "Thread", body: "Done: Project" },
|
||||
createdAt: completedAt,
|
||||
expiresAt: "1970-01-01T00:10:00.000Z",
|
||||
jobId: "job-update-superseded-by-running",
|
||||
});
|
||||
const signed = signApnsDeliveryJob({
|
||||
secret: config.apnsDeliveryJobSigningSecret,
|
||||
payload,
|
||||
});
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
executeCount += 1;
|
||||
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.processSignedJob(signed);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: "live_activity_update",
|
||||
ok: true,
|
||||
apnsStatus: null,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
expect(executeCount).toBe(0);
|
||||
expect(attempts).toMatchObject([
|
||||
{
|
||||
sourceJobId: "job-update-superseded-by-running",
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
activityStates: [
|
||||
{
|
||||
...state,
|
||||
phase: "running",
|
||||
headline: "Running",
|
||||
updatedAt: "1970-01-01T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips a queued Done notification after the thread resumes working", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
const completedAt = "1970-01-01T00:00:01.000Z";
|
||||
const payload = makeApnsDeliveryJobPayload({
|
||||
kind: "push_notification",
|
||||
userId: target.user_id,
|
||||
deviceId: target.device_id,
|
||||
token: "apns-device-token",
|
||||
aggregate: null,
|
||||
notification: {
|
||||
title: "Thread",
|
||||
body: "Done: Project",
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/",
|
||||
phase: "completed",
|
||||
updatedAt: completedAt,
|
||||
},
|
||||
createdAt: completedAt,
|
||||
expiresAt: "1970-01-01T00:10:00.000Z",
|
||||
jobId: "job-push-superseded-by-running",
|
||||
});
|
||||
const signed = signApnsDeliveryJob({
|
||||
secret: config.apnsDeliveryJobSigningSecret,
|
||||
payload,
|
||||
});
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
executeCount += 1;
|
||||
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
|
||||
const result = yield* deliveries.processSignedJob(signed);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
kind: "push_notification",
|
||||
ok: true,
|
||||
apnsStatus: null,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
expect(executeCount).toBe(0);
|
||||
expect(attempts).toMatchObject([
|
||||
{
|
||||
sourceJobId: "job-push-superseded-by-running",
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
currentTargets: [{ ...target, push_token: "apns-device-token" }],
|
||||
currentActivityStates: [
|
||||
{
|
||||
...state,
|
||||
phase: "running",
|
||||
headline: "Running",
|
||||
updatedAt: "1970-01-01T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("retries signed queue jobs that are already claimed but not completed", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
let executeCount = 0;
|
||||
@@ -1504,15 +1327,7 @@ describe("ApnsDeliveries", () => {
|
||||
deviceId: target.device_id,
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
clearedStarts,
|
||||
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(makeLayer({ attempts, clearedStarts })));
|
||||
});
|
||||
|
||||
it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => {
|
||||
@@ -1558,15 +1373,7 @@ describe("ApnsDeliveries", () => {
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
attempts,
|
||||
invalidatedTokens,
|
||||
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
|
||||
config: signingConfig,
|
||||
execute,
|
||||
}),
|
||||
),
|
||||
Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -369,8 +369,6 @@ function notificationForAggregate(input: {
|
||||
environmentId: activity.environmentId,
|
||||
threadId: activity.threadId,
|
||||
deepLink: activity.deepLink,
|
||||
phase: activity.phase,
|
||||
updatedAt: activity.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -724,87 +722,6 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];
|
||||
readonly updatedAt: string;
|
||||
}) {
|
||||
return yield* activityRows
|
||||
.getForUserThread({
|
||||
userId: input.userId,
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(current) =>
|
||||
current !== null &&
|
||||
current.phase === input.phase &&
|
||||
current.updatedAt === input.updatedAt,
|
||||
),
|
||||
// A transient persistence failure must not permanently discard a
|
||||
// legitimate alert. Fail open and let the signed job's retry/dedupe
|
||||
// protections handle transport failures as usual.
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {
|
||||
cause,
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
}).pipe(Effect.as(true)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly aggregate: RelayAgentActivityAggregateState;
|
||||
}) {
|
||||
return yield* activityRows.listForUser({ userId: input.userId }).pipe(
|
||||
Effect.map((currentStates) => {
|
||||
const currentByThread = new Map(
|
||||
currentStates.map((current) => [
|
||||
`${current.environmentId}\u0000${current.threadId}`,
|
||||
current,
|
||||
]),
|
||||
);
|
||||
return input.aggregate.activities.every((row) => {
|
||||
const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);
|
||||
return (
|
||||
current !== undefined &&
|
||||
current.phase === row.phase &&
|
||||
current.updatedAt === row.updatedAt
|
||||
);
|
||||
});
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {
|
||||
cause,
|
||||
userId: input.userId,
|
||||
}).pipe(Effect.as(true)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {
|
||||
readonly userId: string;
|
||||
readonly notification: ApnsNotificationPayload;
|
||||
}) {
|
||||
// Jobs from older relay versions do not carry a state identity. Preserve
|
||||
// backwards compatibility and only revalidate newly queued jobs.
|
||||
if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {
|
||||
return true;
|
||||
}
|
||||
return yield* stateIdentityIsCurrent({
|
||||
userId: input.userId,
|
||||
environmentId: input.notification.environmentId,
|
||||
threadId: input.notification.threadId,
|
||||
phase: input.notification.phase,
|
||||
updatedAt: input.notification.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
|
||||
readonly target: LiveActivityDeliveryTarget;
|
||||
readonly kind: RelayDeliveryKind;
|
||||
@@ -874,20 +791,6 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
if (
|
||||
input.kind !== "live_activity_start" &&
|
||||
aggregate !== null &&
|
||||
!(yield* aggregateRowsAreCurrent({
|
||||
userId: input.target.user_id,
|
||||
aggregate,
|
||||
}))
|
||||
) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
}
|
||||
if (
|
||||
input.kind === "live_activity_start" &&
|
||||
@@ -1027,21 +930,6 @@ export const make = Effect.gen(function* () {
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
if (
|
||||
!(yield* notificationStateIsCurrent({
|
||||
userId: input.target.user_id,
|
||||
notification,
|
||||
}))
|
||||
) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale agent activity state skipped.",
|
||||
});
|
||||
return staleJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
}
|
||||
const result = yield* apns
|
||||
.sendPushNotificationRequest({
|
||||
|
||||
@@ -86,7 +86,6 @@ function makeAgentActivityRows(
|
||||
};
|
||||
return Effect.succeed([activeState]);
|
||||
},
|
||||
getForUserThread: () => Effect.succeed(null),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import {
|
||||
RelayAgentActivityAggregateState,
|
||||
RelayAgentAwarenessPhase,
|
||||
type RelayDeliveryKind,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -42,11 +38,6 @@ export const ApnsNotificationPayload = Schema.Struct({
|
||||
environmentId: Schema.String,
|
||||
threadId: Schema.String,
|
||||
deepLink: Schema.String,
|
||||
// Optional so delivery jobs queued by older relay builds still decode.
|
||||
// New jobs use these fields to avoid delivering a stale Done/attention
|
||||
// notification after the thread has moved to another phase.
|
||||
phase: Schema.optional(RelayAgentAwarenessPhase),
|
||||
updatedAt: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
|
||||
|
||||
|
||||
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
|
||||
});
|
||||
|
||||
describe("ServerSettings worktree defaults", () => {
|
||||
it("defaults start-from-origin off for legacy configs", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
|
||||
it("defaults start-from-origin on for legacy configs", () => {
|
||||
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts start-from-origin updates", () => {
|
||||
expect(
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
|
||||
).toBe(true);
|
||||
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ export const ServerSettings = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
|
||||
),
|
||||
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(false)),
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
),
|
||||
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
textGenerationModelSelection: ModelSelection.pipe(
|
||||
|
||||
@@ -3,10 +3,6 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./projectFavicon": {
|
||||
"types": "./src/projectFavicon.ts",
|
||||
"import": "./src/projectFavicon.ts"
|
||||
},
|
||||
"./model": {
|
||||
"types": "./src/model.ts",
|
||||
"import": "./src/model.ts"
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isProjectFaviconFallbackUrl, PROJECT_FAVICON_FALLBACK_MARKER } from "./projectFavicon.ts";
|
||||
|
||||
describe("project favicon", () => {
|
||||
it("identifies fallback asset URLs by their dedicated filename", () => {
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(
|
||||
`https://environment.example/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(`/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not mistake real favicons or query parameters for fallbacks", () => {
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl("https://environment.example/api/assets/token/favicon.svg"),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(
|
||||
`https://environment.example/api/assets/token/favicon.svg?name=${PROJECT_FAVICON_FALLBACK_MARKER}`,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(isProjectFaviconFallbackUrl(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
export const PROJECT_FAVICON_FALLBACK_MARKER = "project-favicon-missing";
|
||||
|
||||
export function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {
|
||||
if (!url) return false;
|
||||
|
||||
try {
|
||||
const pathname = new URL(url, "https://t3.invalid").pathname;
|
||||
return pathname.slice(pathname.lastIndexOf("/") + 1) === PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||