:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobile): add the Chart home screen widget on Android (#129760)
Chris Volzer0743b78a5058
diff --git a/products/mobile/app.config.ts b/products/mobile/app.config.tsindex eb74e424ce6f..5e4a1b2f4a7b 100644--- a/products/mobile/app.config.ts+++ b/products/mobile/app.config.ts@@ -125,7 +125,8 @@ export default ({ config, projectRoot }: ConfigContext): ExpoConfig => {},plugins: ['expo-router',- 'expo-secure-store',+ ['expo-secure-store', { configureAndroidBackup: false }],+ './plugins/withAndroidChartWidgetBackup','expo-notifications','expo-web-browser',[diff --git a/products/mobile/modules/chart-widget/README.md b/products/mobile/modules/chart-widget/README.mdindex 2bf790ab71b2..a725c1bffbb3 100644--- a/products/mobile/modules/chart-widget/README.md+++ b/products/mobile/modules/chart-widget/README.md@@ -269,7 +269,7 @@ RemoteViews only (no Glance, no Compose), API 24 and up. Code in `android/src/ma| `ChartStore.kt` | The two preferences files below. Every write uses `commit()`. || `TrendsParser.kt` | Insight response to snapshot: mirrors `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts`, `rangePresets.ts`. || `ChartFetcher.kt` | One `HttpURLConnection` read per pin, `refresh=force_cache`, 20 s timeouts, status to error kind. |-| `ChartWidgetRefresh.kt` | `refreshAll(context)`: render from the cache now, then queue one network pass. |+| `ChartWidgetRefresh.kt` | `refreshAll(context)`: render from the cache on a background executor, then queue one network pass. || `ChartRefreshWorker.kt` | The `WorkManager` pass: each distinct pin once, then a render of every widget. || `ChartRenderer.kt`, `ChartCanvas.kt` | Layout choice, states, text, deep links; the chart drawn on a `Canvas` into a `Bitmap`. || `ChartWidgetProvider.kt` | The `AppWidgetProvider`. Every callback is wrapped, because a receiver exception kills the app process. |@@ -291,22 +291,29 @@ The scheme comes from the package suffix (`.dev`, `.preview`, none), the same taThey let the widget say "In another project" after a project switch and name a pin that left the catalog.An Android snapshot also carries `inProgress`: the last bucket is still open, so the chart dashes its last segment and dims its last bar.A corrupt or restored keystore file is deleted and counts as signed out; the app writes the session again on its next token change or launch.+Credential writes retry once and throw if storage remains unavailable or persistence fails on both attempts.+The widget preferences and encrypted session copy are excluded from cloud backups and device transfers, alongside SecureStore.+After a device restore, choose the widget pins again and open the app to synchronize its session and catalog.+Catalog changes discard snapshots and errors for removed pins or changed insight, dashboard, host or project targets. Display-name changes keep the cache.### Cadence- `updatePeriodMillis` is 30 minutes. Each `onUpdate`, each module call and each configure Done calls `refreshAll`.-- `refreshAll` renders every placed widget from the cache on the calling thread, then queues the unique network pass.+- `refreshAll` renders every placed widget from the cache on a serial background executor, then queues the unique network pass.It queues nothing when no widget is placed or the token is missing or expired; the widget then shows its state.- The pass reads each distinct pin of every placed widget once, writes the snapshot (which clears its error) or the error, then renders all widgets.A rejected token stops the pass and marks the remaining pins `auth`. A new token from the app clears every `auth` error.+ Responses are discarded if the session or catalog changed, or if the worker was canceled.+ A 429 or 503 stops the pass and pauses every pin for at least one minute, or longer when `Retry-After` says so.- WorkManager disables its reschedule receiver when no work is pending, and that component change makes the system send `APPWIDGET_UPDATE` again.A no-op job 10 years out (`chart-widget-keep-enabled`) stays queued while a widget is placed, so that loop cannot start. `onDisabled` cancels both.-- The age text is computed at each render, from `lastRefreshAt` (when the server computed the numbers) or else `fetchedAt`.+- The age text is computed at each render from the oldest displayed snapshot, using `lastRefreshAt` (when the server computed the numbers) or else `fetchedAt`.+ Extra tiles hide cached values after a newer authentication or not-found error, as the primary pin does.### Layout and theme- Family from the launcher's portrait size: small when the width is under 250 dp or the height under 110 dp, large from 300 dp high, else medium.- A resize re-renders that widget (`onAppWidgetOptionsChanged`).+ A resize re-renders that widget (`onAppWidgetOptionsChanged`), keeping the broadcast pending until rendering finishes.- Text is `TextView`s, so it follows the user's font size. The chart bitmap is sized for the room the text leaves, capped at 1.5 MB.- The chart is drawn twice, light and dark. `@integer/chart_widget_{light,dark}_visibility` (in `values` and `values-night`) shows the one that matches the launcher's night mode, so a theme change needs no redraw.Colors come from `res/values{,-night}/colors.xml`. From Android 12, runtime text colors use `RemoteViews.setColorInt` with both themes.@@ -314,6 +321,7 @@ A corrupt or restored keystore file is deleted and counts as signed out; the app### Configure flow1. Placing a Chart widget opens "Choose a pin". It starts with `RESULT_CANCELED`, so backing out does not place the widget.+ The activity is exported for Android launchers. It accepts only IDs bound to the Chart widget, checks the ID again before saving, and returns only that ID after Done.2. Eligible pins are radio rows (name and the catalog `subtitle`). Ineligible pins follow, grayed, under "Can't show on the widget" with their `reason`.3. "Also show (large widget)" offers checkboxes for up to two more eligible pins, never the chosen one.4. Done writes `chart.widget.<id>`, calls `refreshAll`, and returns `RESULT_OK` with the widget id.diff --git a/products/mobile/modules/chart-widget/android/build.gradle b/products/mobile/modules/chart-widget/android/build.gradlenew file mode 100644index 000000000000..5315ddb783b9--- /dev/null+++ b/products/mobile/modules/chart-widget/android/build.gradle@@ -0,0 +1,26 @@+plugins {+ id 'com.android.library'+ id 'expo-module-gradle-plugin'+}++group = 'com.posthog.code.mobile'+version = '1.0.0'++android {+ namespace "com.posthog.code.mobile.chart"+ defaultConfig {+ versionCode 1+ versionName '1.0.0'+ }+ testOptions {+ unitTests.includeAndroidResources = true+ }+}++dependencies {+ // The widget fetches PostHog on a timer off the main thread; the session copy lives in encrypted preferences.+ implementation 'androidx.work:work-runtime-ktx:2.9.1'+ implementation 'androidx.security:security-crypto:1.1.0-alpha06'+ testImplementation 'junit:junit:4.13.2'+ testImplementation 'org.robolectric:robolectric:4.16.1'+}diff --git a/products/mobile/modules/chart-widget/android/src/main/AndroidManifest.xml b/products/mobile/modules/chart-widget/android/src/main/AndroidManifest.xmlnew file mode 100644index 000000000000..9e5b04ec6863--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/AndroidManifest.xml@@ -0,0 +1,31 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-permission android:name="android.permission.INTERNET" />+ <application>+ <receiver+ android:name=".ChartWidgetProvider"+ android:exported="false"+ android:label="@string/chart_widget_label">+ <intent-filter>+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />+ </intent-filter>+ <meta-data+ android:name="android.appwidget.provider"+ android:resource="@xml/chart_widget_info" />+ </receiver>++ <!-- The launcher starts it in its own task, so it must not bring the app's task forward. -->+ <!-- Android launchers require access; the activity validates a bound Chart widget and returns only its ID after confirmation. -->+ <!-- nosemgrep: java.android.security.exported_activity.exported_activity -->+ <activity+ android:name=".ChartWidgetConfigureActivity"+ android:excludeFromRecents="true"+ android:exported="true"+ android:label="@string/chart_widget_choose_pin"+ android:taskAffinity=""+ android:theme="@style/ChartWidgetConfigureTheme">+ <intent-filter>+ <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />+ </intent-filter>+ </activity>+ </application>+</manifest>diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.ktnew file mode 100644index 000000000000..cb737784e06f--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.kt@@ -0,0 +1,247 @@+package com.posthog.code.mobile.chart++import android.content.Context+import android.content.res.Configuration+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.DashPathEffect+import android.graphics.LinearGradient+import android.graphics.Paint+import android.graphics.Path+import android.graphics.Shader+import kotlin.math.abs+import kotlin.math.max+import kotlin.math.min+import kotlin.math.sqrt++/** Chart colors for one theme, read from the widget's color resources so the XML stays the only palette. */+internal class ChartColors(+ val series: List<Int>,+ val previous: Int,+ val barNeutral: Int,+ val ink: Int,+ val hairline: Int,+) {+ companion object {+ private val SERIES = listOf(+ R.color.chart_widget_series_1,+ R.color.chart_widget_series_2,+ R.color.chart_widget_series_3,+ R.color.chart_widget_series_4,+ R.color.chart_widget_series_5,+ )+ private val cache = HashMap<Boolean, ChartColors>()+ private val contexts = HashMap<Boolean, Context>()++ @Synchronized+ fun themed(context: Context, night: Boolean): Context = contexts.getOrPut(night) {+ val config = Configuration(context.resources.configuration)+ config.uiMode = (config.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or+ if (night) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO+ context.applicationContext.createConfigurationContext(config)+ }++ @Synchronized+ fun of(context: Context, night: Boolean): ChartColors = cache.getOrPut(night) {+ val themed = themed(context, night)+ ChartColors(+ series = SERIES.map(themed::getColor),+ previous = themed.getColor(R.color.chart_widget_previous),+ barNeutral = themed.getColor(R.color.chart_widget_bar_neutral),+ ink = themed.getColor(R.color.chart_widget_ink),+ hairline = themed.getColor(R.color.chart_widget_hairline),+ )+ }+ }+}++/** What to draw. `current` holds up to five series of the same length; `previous` pairs with the first one. */+internal class ChartSpec(+ val current: List<List<Double>>,+ val previous: List<Double>?,+ val bars: Boolean,+ val inProgress: Boolean,+ val grid: Boolean,+)++internal object ChartCanvas {+ private const val MAX_BITMAP_BYTES = 1.5 * 1024 * 1024+ private const val LINE_PADDING_RATIO = 0.1++ /** Null when there is nothing to draw or no room. `density` is px per dp at the size the launcher shows. */+ fun draw(spec: ChartSpec, colors: ChartColors, widthPx: Int, heightPx: Int, density: Float): Bitmap? {+ if (widthPx <= 0 || heightPx <= 0 || spec.current.isEmpty()) return null+ // The launcher stretches the image back to the cell, so a large widget trades sharpness for memory.+ val scale = min(1.0, sqrt(MAX_BITMAP_BYTES / (widthPx.toDouble() * heightPx * 4))).toFloat()+ val width = max(1, (widthPx * scale).toInt())+ val height = max(1, (heightPx * scale).toInt())+ val dp = density * scale+ val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bitmap)+ if (spec.bars) drawBars(canvas, spec, colors, width, height, dp) else drawLines(canvas, spec, colors, width, height, dp)+ return bitmap+ }++ private class Scale(val lo: Double, val hi: Double, val top: Float, val bottom: Float) {+ fun y(value: Double): Float = (bottom - (value - lo) / (hi - lo) * (bottom - top)).toFloat()+ }++ /**+ * `yAxisTicks` in src/ui/chart/chartMath.ts: bars start at zero, lines fit their values and never dip below zero+ * when every value is positive. There are no ticks to round to, so lines get twice the app's padding instead.+ */+ private fun scaleOf(values: List<Double>, bars: Boolean, top: Float, bottom: Float): Scale? {+ val finite = values.filter { it.isFinite() }+ if (finite.isEmpty()) return null+ var lo: Double+ var hi: Double+ if (bars) {+ lo = min(0.0, finite.min())+ hi = max(0.0, finite.max())+ } else {+ val span = finite.max() - finite.min()+ val pad = if (span > 0) span * LINE_PADDING_RATIO else abs(finite.max()) * 0.1+ lo = finite.min() - pad+ hi = finite.max() + pad+ if (finite.min() >= 0 && lo < 0) lo = 0.0+ }+ if (hi <= lo) hi = lo + 1+ return Scale(lo, hi, top, bottom)+ }++ private fun drawGrid(canvas: Canvas, colors: ChartColors, scale: Scale, width: Int, dp: Float) {+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = colors.hairline+ strokeWidth = max(1f, dp * 0.75f)+ }+ for (fraction in listOf(0f, 0.5f, 1f)) {+ val y = scale.top + (scale.bottom - scale.top) * fraction+ canvas.drawLine(0f, y, width.toFloat(), y, paint)+ }+ }++ private fun drawLines(canvas: Canvas, spec: ChartSpec, colors: ChartColors, width: Int, height: Int, dp: Float) {+ val stroke = if (spec.grid) 2f * dp else 1.75f * dp+ val dot = 2.75f * dp+ val padX = dot + 1f * dp+ val scale = scaleOf(spec.current.flatten() + spec.previous.orEmpty(), false, dot + 1f * dp, height - stroke / 2 - 1f * dp) ?: return+ if (spec.grid) drawGrid(canvas, colors, scale, width, dp)+ val count = spec.current.first().size+ fun x(index: Int): Float = if (count <= 1) width / 2f else padX + index * (width - 2 * padX) / (count - 1)++ val first = spec.current.first()+ val accent = colors.series.first()+ val area = Path()+ var runStart = -1+ fun closeRun(end: Int) {+ if (runStart < 0) return+ area.lineTo(x(end), scale.bottom)+ area.lineTo(x(runStart), scale.bottom)+ area.close()+ runStart = -1+ }+ first.forEachIndexed { index, value ->+ if (!value.isFinite()) {+ closeRun(index - 1)+ return@forEachIndexed+ }+ if (runStart < 0) {+ runStart = index+ area.moveTo(x(index), scale.y(value))+ } else {+ area.lineTo(x(index), scale.y(value))+ }+ }+ closeRun(first.lastIndex)+ val areaPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.FILL+ shader = LinearGradient(0f, scale.top, 0f, scale.bottom, withAlpha(accent, 0.22f), withAlpha(accent, 0.04f), Shader.TileMode.CLAMP)+ }+ canvas.drawPath(area, areaPaint)++ spec.previous?.let { previous ->+ val paint = linePaint(colors.previous, stroke * 0.7f).apply {+ pathEffect = DashPathEffect(floatArrayOf(3f * dp, 3f * dp), 0f)+ }+ canvas.drawPath(linePath(previous, previous.size, ::x, scale), paint)+ }++ spec.current.forEachIndexed { seriesIndex, values ->+ val color = colors.series[seriesIndex % colors.series.size]+ // The bucket that contains now is incomplete, so its segment is dashed like the app's chart.+ val solidEnd = if (spec.inProgress && values.size >= 2) values.size - 1 else values.size+ canvas.drawPath(linePath(values, solidEnd, ::x, scale), linePaint(color, stroke))+ if (solidEnd < values.size) {+ val a = values[values.size - 2]+ val b = values[values.size - 1]+ if (a.isFinite() && b.isFinite()) {+ val dashed = linePaint(color, stroke).apply { pathEffect = DashPathEffect(floatArrayOf(2.5f * dp, 2.5f * dp), 0f) }+ canvas.drawLine(x(values.size - 2), scale.y(a), x(values.size - 1), scale.y(b), dashed)+ }+ }+ }++ val lastIndex = first.indexOfLast { it.isFinite() }+ if (lastIndex >= 0) {+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = accent }+ canvas.drawCircle(x(lastIndex), scale.y(first[lastIndex]), dot, paint)+ }+ }++ private fun linePath(values: List<Double>, end: Int, x: (Int) -> Float, scale: Scale): Path {+ val path = Path()+ var drawing = false+ for (index in 0 until min(end, values.size)) {+ val value = values[index]+ if (!value.isFinite()) {+ drawing = false+ continue+ }+ if (drawing) path.lineTo(x(index), scale.y(value)) else path.moveTo(x(index), scale.y(value))+ drawing = true+ }+ return path+ }++ private fun linePaint(color: Int, width: Float): Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ this.color = color+ style = Paint.Style.STROKE+ strokeWidth = width+ strokeCap = Paint.Cap.ROUND+ strokeJoin = Paint.Join.ROUND+ }++ private fun drawBars(canvas: Canvas, spec: ChartSpec, colors: ChartColors, width: Int, height: Int, dp: Float) {+ val scale = scaleOf(spec.current.flatten(), true, if (spec.grid) 1f * dp else 0f, height.toFloat() - if (spec.grid) 1f * dp else 0f) ?: return+ if (spec.grid) drawGrid(canvas, colors, scale, width, dp)+ val count = spec.current.first().size+ val groups = spec.current.size+ val slot = width.toFloat() / max(1, count)+ val gap = max(1f, slot * if (count > 20) 0.2f else 0.28f)+ val barWidth = (slot - gap) / groups+ val radius = min(2f * dp, barWidth / 2)+ val zero = scale.y(0.0)+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)+ for (index in 0 until count) {+ spec.current.forEachIndexed { seriesIndex, values ->+ val value = values.getOrNull(index) ?: return@forEachIndexed+ if (!value.isFinite()) return@forEachIndexed+ val left = index * slot + gap / 2 + seriesIndex * barWidth+ val y = scale.y(value)+ val top = min(y, zero)+ val bottom = max(y, zero)+ if (bottom - top < 0.5f) return@forEachIndexed+ // One series reads like the app's pin: neutral bars and the newest in ink.+ val base = if (groups == 1) (if (index == count - 1) colors.ink else colors.barNeutral) else colors.series[seriesIndex % colors.series.size]+ paint.color = if (spec.inProgress && index == count - 1) withAlpha(base, 0.55f) else base+ val r = min(radius, bottom - top)+ val radii = if (value >= 0) floatArrayOf(r, r, r, r, 0f, 0f, 0f, 0f) else floatArrayOf(0f, 0f, 0f, 0f, r, r, r, r)+ val bar = Path().apply { addRoundRect(left, top, left + barWidth, bottom, radii, Path.Direction.CW) }+ canvas.drawPath(bar, paint)+ }+ }+ }++ private fun withAlpha(color: Int, alpha: Float): Int =+ (color and 0x00FFFFFF) or ((((color ushr 24) and 0xFF) * alpha).toInt().coerceIn(0, 255) shl 24)+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.ktnew file mode 100644index 000000000000..8a715ddb3fa8--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.kt@@ -0,0 +1,102 @@+package com.posthog.code.mobile.chart++import android.content.Context+import android.util.Log+import org.json.JSONException+import org.json.JSONObject+import java.io.IOException+import java.net.HttpURLConnection+import java.net.URL+import java.net.URLEncoder+import java.text.SimpleDateFormat+import java.util.Locale+import java.util.TimeZone++/** Reads one pin's insight. Only `force_cache`: the widget shows what the server already computed and never computes. */+object ChartFetcher {+ private const val TAG = "ChartWidget"+ private const val TIMEOUT_MS = 20_000++ sealed class Outcome {+ class Success(val snapshot: ChartSnapshot) : Outcome()+ class Failure(val kind: String, val retryAfterMs: Long = 60_000L) : Outcome()+ }++ fun fetch(context: Context, credentials: Credentials, pin: CatalogPin, now: Long = System.currentTimeMillis()): Outcome {+ val base = "${credentials.host}/api/projects/${credentials.projectId}/insights/"+ val insightId = pin.insightId+ val shortId = pin.shortId+ val url = when {+ insightId != null ->+ "$base$insightId/?refresh=force_cache" + (pin.dashboardId?.takeIf { pin.isDashboard }?.let { "&from_dashboard=$it" } ?: "")+ shortId != null -> "$base?short_id=${URLEncoder.encode(shortId, "UTF-8")}&refresh=force_cache"+ else -> return Outcome.Failure(ErrorKind.NOT_FOUND)+ }+ val connection = try {+ URL(url).openConnection() as HttpURLConnection+ } catch (e: IOException) {+ return Outcome.Failure(ErrorKind.NETWORK)+ }+ try {+ connection.connectTimeout = TIMEOUT_MS+ connection.readTimeout = TIMEOUT_MS+ connection.instanceFollowRedirects = false+ connection.setRequestProperty("Authorization", "Bearer ${credentials.accessToken}")+ connection.setRequestProperty("Accept", "application/json")+ connection.setRequestProperty("User-Agent", userAgent(context))+ val status = connection.responseCode+ when (status) {+ 401, 403 -> return Outcome.Failure(ErrorKind.AUTH)+ 404 -> return Outcome.Failure(ErrorKind.NOT_FOUND)+ 429, 503 -> return Outcome.Failure(ErrorKind.RATE_LIMITED, retryAfterMs(connection.getHeaderField("Retry-After"), now))+ 200 -> Unit+ else -> return Outcome.Failure(ErrorKind.NETWORK)+ }+ val body = connection.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }+ val json = JSONObject(body)+ val insight = if (insightId != null) json else findByShortId(json, shortId) ?: return Outcome.Failure(ErrorKind.NOT_FOUND)+ val queryStatus = insight.optJSONObject("query_status")+ if (queryStatus?.optString("error_code") == "rate_limited") return Outcome.Failure(ErrorKind.RATE_LIMITED)+ if (queryStatus != null && queryStatus.optBoolean("error", false)) return Outcome.Failure(ErrorKind.BAD_DATA)+ if (!insight.has("result") || insight.isNull("result")) return Outcome.Failure(ErrorKind.NO_RESULT)+ return Outcome.Success(TrendsParser.parse(insight, pin.id, now))+ } catch (e: IOException) {+ return Outcome.Failure(ErrorKind.NETWORK)+ } catch (e: JSONException) {+ Log.w(TAG, "Pin ${pin.id} answered with JSON the widget cannot read")+ return Outcome.Failure(ErrorKind.BAD_DATA)+ } catch (e: BadDataException) {+ Log.w(TAG, "Pin ${pin.id} is not a trends result: ${e.message}")+ return Outcome.Failure(ErrorKind.BAD_DATA)+ } finally {+ connection.disconnect()+ }+ }++ internal fun retryAfterMs(value: String?, now: Long): Long {+ val seconds = value?.trim()?.toLongOrNull()+ if (seconds != null) return seconds.coerceIn(0L, Long.MAX_VALUE / 1000L - now / 1000L).times(1000L).coerceAtLeast(60_000L)+ val retryAt = value?.let {+ runCatching {+ SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply {+ timeZone = TimeZone.getTimeZone("GMT")+ }.parse(it)?.time+ }.getOrNull()+ }+ return ((retryAt ?: now) - now).coerceAtLeast(60_000L)+ }++ private fun findByShortId(json: JSONObject, shortId: String?): JSONObject? {+ val results = json.optJSONArray("results") ?: return null+ return (0 until results.length()).mapNotNull { results.optJSONObject(it) }.firstOrNull { it.optString("short_id") == shortId }+ }++ private fun userAgent(context: Context): String {+ val version = try {+ context.packageManager.getPackageInfo(context.packageName, 0).versionName+ } catch (e: Exception) {+ null+ } ?: "unknown"+ return "posthog-mobile-widget/$version (android)"+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.ktnew file mode 100644index 000000000000..2d4d8f359dce--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.kt@@ -0,0 +1,246 @@+package com.posthog.code.mobile.chart++import org.json.JSONArray+import org.json.JSONObject++/** Field names follow the store contract in modules/chart-widget/README.md, which iOS shares. */++internal fun JSONObject.stringOrNull(key: String): String? =+ if (has(key) && !isNull(key)) optString(key).takeIf { it.isNotEmpty() } else null++internal fun JSONObject.longOrNull(key: String): Long? = (opt(key) as? Number)?.toLong()++internal fun JSONObject.doubleOrNull(key: String): Double? =+ (opt(key) as? Number)?.toDouble()?.takeIf { it.isFinite() }++private fun JSONArray?.strings(): List<String> =+ if (this == null) emptyList() else (0 until length()).mapNotNull { optString(it).takeIf { s -> s.isNotEmpty() } }++data class Credentials(+ val host: String,+ val projectId: Long,+ val projectName: String,+ val accessToken: String,+ /** Epoch ms, or null for a key that never expires. */+ val expiresAt: Long?,+ val userUuid: String?,+) {+ // A token inside its last minute would expire mid-refresh, so it counts as expired already.+ fun isExpired(now: Long): Boolean = expiresAt != null && now > expiresAt - EXPIRY_MARGIN_MS++ companion object {+ private const val EXPIRY_MARGIN_MS = 60_000L++ fun parse(json: String): Credentials? = runCatching {+ val o = JSONObject(json)+ Credentials(+ host = o.getString("host").trimEnd('/'),+ projectId = o.getLong("projectId"),+ projectName = o.optString("projectName"),+ accessToken = o.getString("accessToken"),+ expiresAt = o.longOrNull("expiresAt"),+ userUuid = o.stringOrNull("userUuid"),+ )+ }.getOrNull()+ }+}++data class CatalogPin(+ val id: String,+ val kind: String,+ val name: String,+ val subtitle: String,+ val insightId: Long?,+ val shortId: String?,+ val dashboardId: Long?,+ val eligible: Boolean,+ val number: Boolean,+ val chart: Boolean,+ val reason: String?,+) {+ val isDashboard: Boolean get() = kind == "dashboard"+}++data class Catalog(+ val host: String,+ val projectId: Long,+ val projectName: String,+ val writtenAt: Long,+ val pins: List<CatalogPin>,+) {+ fun pin(id: String): CatalogPin? = pins.firstOrNull { it.id == id }++ companion object {+ fun parse(json: String): Catalog? = runCatching {+ val o = JSONObject(json)+ val array = o.optJSONArray("pins") ?: JSONArray()+ val pins = (0 until array.length()).mapNotNull { index ->+ val p = array.optJSONObject(index) ?: return@mapNotNull null+ val id = p.stringOrNull("id") ?: return@mapNotNull null+ CatalogPin(+ id = id,+ kind = p.optString("kind", "insight"),+ name = p.stringOrNull("name") ?: "Untitled",+ subtitle = p.optString("subtitle"),+ insightId = p.longOrNull("insightId"),+ shortId = p.stringOrNull("shortId"),+ dashboardId = p.longOrNull("dashboardId"),+ eligible = p.optBoolean("eligible", false),+ number = p.optBoolean("number", false),+ chart = p.optBoolean("chart", false),+ reason = p.stringOrNull("reason"),+ )+ }+ Catalog(+ host = o.optString("host").trimEnd('/'),+ projectId = o.getLong("projectId"),+ projectName = o.optString("projectName"),+ writtenAt = o.optLong("writtenAt"),+ pins = pins,+ )+ }.getOrNull()+ }+}++/**+ * The pin a placed widget shows. `projectId`, `projectName` and `pinName` are remembered at configure time, so the+ * widget can still name the pin after it leaves the catalog or the app switches project.+ */+data class WidgetConfig(+ val pinId: String,+ val extraPinIds: List<String>,+ val projectId: Long?,+ val projectName: String?,+ val pinName: String?,+) {+ fun toJson(): String = JSONObject()+ .put("pinId", pinId)+ .put("extraPinIds", JSONArray(extraPinIds))+ .apply {+ projectId?.let { put("projectId", it) }+ projectName?.let { put("projectName", it) }+ pinName?.let { put("pinName", it) }+ }+ .toString()++ companion object {+ fun parse(json: String): WidgetConfig? = runCatching {+ val o = JSONObject(json)+ WidgetConfig(+ pinId = o.getString("pinId"),+ extraPinIds = o.optJSONArray("extraPinIds").strings(),+ projectId = o.longOrNull("projectId"),+ projectName = o.stringOrNull("projectName"),+ pinName = o.stringOrNull("pinName"),+ )+ }.getOrNull()+ }+}++object ErrorKind {+ const val NETWORK = "network"+ const val AUTH = "auth"+ const val NOT_FOUND = "not_found"+ const val RATE_LIMITED = "rate_limited"+ const val BAD_DATA = "bad_data"+ /** A 200 whose `result` is null: the server has not computed the insight, and the widget never asks it to. */+ const val NO_RESULT = "no_result"+}++data class SnapshotError(val at: Long, val kind: String) {+ fun toJson(): String = JSONObject().put("at", at).put("kind", kind).toString()++ companion object {+ fun parse(json: String): SnapshotError? = runCatching {+ val o = JSONObject(json)+ SnapshotError(o.getLong("at"), o.getString("kind"))+ }.getOrNull()+ }+}++/** `value` is NaN for a bucket without a number; JSON stores it as null. */+data class SnapshotPoint(val at: String, val value: Double)++data class SnapshotSeries(val label: String, val points: List<SnapshotPoint>, val previous: Boolean)++data class ChartSnapshot(+ val pinId: String,+ val fetchedAt: Long,+ val lastRefreshAt: String?,+ val rangeLabel: String?,+ val intervalLabel: String,+ val valueText: String?,+ val deltaPercent: Double?,+ val deltaText: String?,+ val deltaBasis: String?,+ val inProgress: Boolean,+ val series: List<SnapshotSeries>,+ val chartKind: String,+) {+ val deltaSign: Int get() = deltaPercent?.let { if (it > 0) 1 else if (it < 0) -1 else 0 } ?: 0++ fun toJson(): String {+ val seriesArray = JSONArray()+ series.forEach { s ->+ val points = JSONArray()+ s.points.forEach { p ->+ points.put(JSONObject().put("at", p.at).put("value", if (p.value.isFinite()) p.value else JSONObject.NULL))+ }+ seriesArray.put(JSONObject().put("label", s.label).put("points", points).put("previous", s.previous))+ }+ return JSONObject()+ .put("version", 1)+ .put("pinId", pinId)+ .put("fetchedAt", fetchedAt)+ .put("lastRefreshAt", lastRefreshAt ?: JSONObject.NULL)+ .put("rangeLabel", rangeLabel ?: JSONObject.NULL)+ .put("intervalLabel", intervalLabel)+ .put("valueText", valueText ?: JSONObject.NULL)+ .put("deltaPercent", deltaPercent ?: JSONObject.NULL)+ .put("deltaText", deltaText ?: JSONObject.NULL)+ .put("deltaBasis", deltaBasis ?: JSONObject.NULL)+ .put("inProgress", inProgress)+ .put("series", seriesArray)+ .put("chartKind", chartKind)+ .toString()+ }++ companion object {+ fun parse(json: String): ChartSnapshot? = runCatching {+ val o = JSONObject(json)+ val array = o.optJSONArray("series") ?: JSONArray()+ val series = (0 until array.length()).mapNotNull { index ->+ val s = array.optJSONObject(index) ?: return@mapNotNull null+ val pointsArray = s.optJSONArray("points") ?: JSONArray()+ val points = (0 until pointsArray.length()).mapNotNull { i ->+ val p = pointsArray.optJSONObject(i) ?: return@mapNotNull null+ SnapshotPoint(p.optString("at"), p.doubleOrNull("value") ?: Double.NaN)+ }+ SnapshotSeries(s.optString("label"), points, s.optBoolean("previous", false))+ }+ ChartSnapshot(+ pinId = o.getString("pinId"),+ fetchedAt = o.getLong("fetchedAt"),+ lastRefreshAt = o.stringOrNull("lastRefreshAt"),+ rangeLabel = o.stringOrNull("rangeLabel"),+ intervalLabel = o.optString("intervalLabel", "day"),+ valueText = o.stringOrNull("valueText"),+ deltaPercent = o.doubleOrNull("deltaPercent"),+ deltaText = o.stringOrNull("deltaText"),+ deltaBasis = o.stringOrNull("deltaBasis"),+ inProgress = o.optBoolean("inProgress", false),+ series = series,+ chartKind = o.optString("chartKind", "line"),+ )+ }.getOrNull()+ }+}++internal fun ChartSnapshot?.visibleAfter(error: SnapshotError?): ChartSnapshot? {+ if (this == null) return null+ return if (error != null && error.at >= fetchedAt &&+ (error.kind == ErrorKind.AUTH || error.kind == ErrorKind.NOT_FOUND)+ ) null else this+}++internal fun ChartSnapshot.updatedAt(): Long = lastRefreshAt?.let(DateText::parseInstant) ?: fetchedAtdiff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRefreshWorker.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRefreshWorker.ktnew file mode 100644index 000000000000..927eabce8843--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRefreshWorker.kt@@ -0,0 +1,24 @@+package com.posthog.code.mobile.chart++import android.content.Context+import android.util.Log+import androidx.work.Worker+import androidx.work.WorkerParameters++/** One network pass for every placed chart widget, then a render. Failures keep the cache, so it never retries. */+class ChartRefreshWorker(context: Context, params: WorkerParameters) : Worker(context, params) {+ override fun doWork(): Result {+ try {+ ChartWidgetRefresh.fetchShownPins(applicationContext, isStopped = { isStopped })+ if (!isStopped) ChartRenderer.renderAll(applicationContext).get()+ } catch (e: Exception) {+ Log.e("ChartWidget", "Chart widget refresh failed", e)+ }+ return Result.success()+ }+}++/** Never does anything; see `ChartWidgetRefresh.refreshAll` for why it stays queued. */+class ChartKeepEnabledWorker(context: Context, params: WorkerParameters) : Worker(context, params) {+ override fun doWork(): Result = Result.success()+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.ktnew file mode 100644index 000000000000..993f97d57479--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.kt@@ -0,0 +1,447 @@+package com.posthog.code.mobile.chart++import android.app.PendingIntent+import android.appwidget.AppWidgetManager+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.os.Build+import android.text.SpannableStringBuilder+import android.text.Spanned+import android.text.style.ForegroundColorSpan+import android.util.Log+import android.util.TypedValue+import android.view.View+import android.widget.RemoteViews+import java.util.concurrent.Executors+import java.util.concurrent.Future+import kotlin.math.max++object ChartRenderer {+ private val renderExecutor = Executors.newSingleThreadExecutor()++ const val TAG = "ChartWidget"++ private const val DEFAULT_SIZE_DP = 180+ private const val STALE_MS = 60 * 60_000L+ private const val SHORT_POINTS = 14+ private const val MIN_CHART_DP = 16f++ enum class Family(val key: String) { SMALL("small"), MEDIUM("medium"), LARGE("large") }++ private class Inputs(val credentials: Credentials?, val catalog: Catalog?, val now: Long)++ private sealed class Resolved {+ class Message(+ val title: String?,+ val message: String,+ val detail: String? = null,+ val placeholder: Boolean = false,+ val linkPin: CatalogPin? = null,+ ) : Resolved()++ class Data(val pin: CatalogPin, val snapshot: ChartSnapshot, val extras: List<Extra>) : Resolved()+ }++ private class Extra(val pin: CatalogPin, val snapshot: ChartSnapshot?, val error: SnapshotError?)++ private fun failureText(context: Context, kind: String): Pair<String, String?> = when (kind) {+ ErrorKind.AUTH -> context.getString(R.string.chart_widget_update_session) to null+ ErrorKind.NOT_FOUND -> context.getString(R.string.chart_widget_not_found_short) to null+ ErrorKind.BAD_DATA -> context.getString(R.string.chart_widget_bad_data) to null+ ErrorKind.NO_RESULT -> context.getString(R.string.chart_widget_no_result) to null+ else -> context.getString(R.string.chart_widget_refresh_failed) to context.getString(R.string.chart_widget_refresh_retry)+ }++ private class TileIds(+ val root: Int, val title: Int, val range: Int, val value: Int, val delta: Int, val frame: Int, val light: Int, val dark: Int,+ )++ private val TILES = listOf(+ TileIds(R.id.chart_tile_1, R.id.chart_tile_1_title, R.id.chart_tile_1_range, R.id.chart_tile_1_value, R.id.chart_tile_1_delta,+ R.id.chart_tile_1_frame, R.id.chart_tile_1_image_light, R.id.chart_tile_1_image_dark),+ TileIds(R.id.chart_tile_2, R.id.chart_tile_2_title, R.id.chart_tile_2_range, R.id.chart_tile_2_value, R.id.chart_tile_2_delta,+ R.id.chart_tile_2_frame, R.id.chart_tile_2_image_light, R.id.chart_tile_2_image_dark),+ )++ fun widgetIds(context: Context): IntArray =+ AppWidgetManager.getInstance(context).getAppWidgetIds(ComponentName(context, ChartWidgetProvider::class.java))++ /** Catches everything, because an exception thrown from a broadcast receiver crashes the whole app process. */+ fun renderAll(context: Context): Future<*> {+ val app = context.applicationContext+ return renderExecutor.submit { renderAllNow(app) }+ }++ private fun renderAllNow(context: Context) {+ try {+ val ids = widgetIds(context)+ if (ids.isEmpty()) return+ val manager = AppWidgetManager.getInstance(context)+ val inputs = inputs(context)+ ids.forEach { render(context, manager, it, inputs) }+ } catch (e: Exception) {+ Log.e(TAG, "Could not render the chart widgets", e)+ }+ }++ fun renderOne(context: Context, manager: AppWidgetManager, id: Int, onComplete: () -> Unit = {}): Future<*> {+ val app = context.applicationContext+ return renderExecutor.submit {+ try {+ render(app, manager, id, inputs(app))+ } catch (e: Exception) {+ Log.e(TAG, "Could not render chart widget $id", e)+ } finally {+ onComplete()+ }+ }+ }++ private fun inputs(context: Context) =+ Inputs(ChartStore.credentials(context), ChartStore.catalog(context), System.currentTimeMillis())++ private fun render(context: Context, manager: AppWidgetManager, id: Int, inputs: Inputs) {+ try {+ manager.updateAppWidget(id, build(context, manager, id, inputs))+ } catch (e: Exception) {+ Log.e(TAG, "Could not render chart widget $id", e)+ }+ }++ private fun build(context: Context, manager: AppWidgetManager, id: Int, inputs: Inputs): RemoteViews {+ val options = manager.getAppWidgetOptions(id)+ // Portrait size: the launcher reports min width and max height for the portrait cell grid.+ val widthDp = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH).takeIf { it > 0 } ?: DEFAULT_SIZE_DP+ val heightDp = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT).takeIf { it > 0 } ?: DEFAULT_SIZE_DP+ val family = when {+ widthDp < 250 || heightDp < 110 -> Family.SMALL+ heightDp >= 300 -> Family.LARGE+ else -> Family.MEDIUM+ }+ return when (val resolved = resolve(context, ChartStore.widgetConfig(context, id), inputs)) {+ is Resolved.Message -> stateViews(context, id, family, resolved)+ is Resolved.Data -> dataViews(context, id, family, widthDp, heightDp, resolved, inputs.now)+ }+ }++ private fun resolve(context: Context, config: WidgetConfig?, inputs: Inputs): Resolved {+ if (config == null) {+ return Resolved.Message(context.getString(R.string.chart_widget_choose_pin), context.getString(R.string.chart_widget_choose_pin_hint))+ }+ val credentials = inputs.credentials ?: return Resolved.Message(+ context.getString(R.string.chart_widget_signed_out_title),+ context.getString(R.string.chart_widget_signed_out_message),+ )+ if (config.projectId != null && config.projectId != credentials.projectId) {+ val project = config.projectName?.takeIf { it.isNotBlank() } ?: "its project"+ return Resolved.Message(+ context.getString(R.string.chart_widget_other_project_title),+ context.getString(R.string.chart_widget_other_project_message, project),+ )+ }+ val catalog = inputs.catalog?.takeIf { it.projectId == credentials.projectId && it.host == credentials.host }+ val pin = catalog?.pin(config.pinId)+ val name = pin?.name ?: config.pinName ?: context.getString(R.string.chart_widget_this_pin)+ if (pin == null) {+ // Without a catalog for this project the app has not listed its pins yet, so the pin may still be there.+ return if (catalog != null) {+ Resolved.Message(null, context.getString(R.string.chart_widget_no_longer_pinned, name))+ } else {+ Resolved.Message(name, context.getString(R.string.chart_widget_loading), placeholder = true)+ }+ }+ if (!pin.eligible) return Resolved.Message(name, pin.reason ?: context.getString(R.string.chart_widget_ineligible))+ if (credentials.isExpired(inputs.now)) return Resolved.Message(name, context.getString(R.string.chart_widget_update_session))+ val snapshot = ChartStore.snapshot(context, pin.id)+ val error = ChartStore.snapshotError(context, pin.id)?.takeIf { snapshot == null || it.at >= snapshot.fetchedAt }+ when (error?.kind) {+ ErrorKind.AUTH -> return Resolved.Message(name, context.getString(R.string.chart_widget_update_session))+ ErrorKind.NOT_FOUND -> return Resolved.Message(null, context.getString(R.string.chart_widget_not_found, name))+ }+ if (snapshot == null) {+ if (error == null) return Resolved.Message(name, context.getString(R.string.chart_widget_loading), placeholder = true)+ val (message, detail) = failureText(context, error.kind)+ // Opening the insight in the app computes it; the next refresh then finds the result.+ return Resolved.Message(name, message, detail, linkPin = pin.takeIf { error.kind == ErrorKind.NO_RESULT })+ }+ val extras = config.extraPinIds.asSequence()+ .filter { it != pin.id }+ .mapNotNull { catalog?.pin(it)?.takeIf { extra -> extra.eligible } }+ .take(TILES.size)+ .map { Extra(it, ChartStore.snapshot(context, it.id), ChartStore.snapshotError(context, it.id)) }+ .toList()+ return Resolved.Data(pin, snapshot, extras)+ }++ private fun stateViews(context: Context, id: Int, family: Family, state: Resolved.Message): RemoteViews {+ val views = RemoteViews(context.packageName, R.layout.chart_widget_state)+ if (state.title != null) {+ views.setTextViewText(R.id.chart_state_title, state.title)+ views.setViewVisibility(R.id.chart_state_title, View.VISIBLE)+ } else {+ views.setViewVisibility(R.id.chart_state_title, View.GONE)+ }+ views.setTextViewText(R.id.chart_state_message, state.message)+ views.setTextViewText(R.id.chart_state_detail, state.detail ?: "")+ views.setViewVisibility(R.id.chart_state_detail, if (state.detail != null) View.VISIBLE else View.GONE)+ views.setViewVisibility(R.id.chart_state_placeholder, if (state.placeholder) View.VISIBLE else View.GONE)+ val link = state.linkPin?.let { pinLink(context, it, family) } ?: "${scheme(context)}://views"+ views.setOnClickPendingIntent(R.id.chart_root, linkIntent(context, link, id, 0))+ views.setContentDescription(R.id.chart_root, listOfNotNull(state.title, state.message, state.detail).joinToString(". "))+ return views+ }++ private fun dataViews(context: Context, id: Int, family: Family, widthDp: Int, heightDp: Int, data: Resolved.Data, now: Long): RemoteViews {+ val layout = when (family) {+ Family.SMALL -> R.layout.chart_widget_small+ Family.MEDIUM -> R.layout.chart_widget_medium+ Family.LARGE -> R.layout.chart_widget_large+ }+ val views = RemoteViews(context.packageName, layout)+ val snapshot = data.snapshot+ val m = Metrics(context)+ views.setTextViewText(R.id.chart_title, data.pin.name)+ bindValue(context, views, R.id.chart_value, R.id.chart_delta, snapshot)+ views.setTextViewText(R.id.chart_range, snapshot.rangeLabel ?: "")+ val displayed = listOf(snapshot) + if (family == Family.LARGE) {+ data.extras.mapNotNull { it.snapshot.visibleAfter(it.error) }+ } else emptyList()+ val age = max(0L, now - displayed.minOf { it.updatedAt() })+ val updated = ageText(context, age)+ views.setTextViewText(R.id.chart_updated, updated)+ setTextColor(context, views, R.id.chart_updated, if (age > STALE_MS) R.color.chart_widget_orange else R.color.chart_widget_tertiary)++ val widthPx = widthDp * m.density+ val heightPx = heightDp * m.density+ val chartWidth: Float+ var chartHeight: Float+ if (family == Family.SMALL) {+ chartWidth = widthPx - m.dp(24f)+ chartHeight = heightPx - m.dp(24f) - m.line(12f) - m.dp(2f) - m.line(26f) - m.dp(2f) - m.pill() - m.dp(6f) - m.dp(4f) - m.line(10.5f)+ if (snapshot.valueText == null) chartHeight += m.line(26f) + m.dp(2f)+ } else {+ chartWidth = widthPx - m.dp(28f)+ val headline = if (snapshot.valueText != null) max(m.line(26f), m.pill()) else m.line(10.5f)+ chartHeight = heightPx - m.dp(28f) - max(m.dp(12f), m.line(12f)) - m.dp(2f) - headline - m.dp(8f) - m.dp(6f) - m.line(10.5f)+ bindHeadline(context, views, snapshot)+ }+ if (family == Family.LARGE) {+ chartHeight -= m.dp(4f) + m.line(10.5f)+ if (data.extras.isNotEmpty()) {+ chartHeight -= m.dp(10f) + m.dp(20f) + m.line(12f) + m.dp(1f) + m.line(10.5f) + m.dp(4f) + max(m.line(20f), m.pill()) + m.dp(6f) + m.dp(28f)+ }+ }+ val spec = specOf(snapshot, if (family == Family.LARGE) TrendsParser.MAX_POINTS else SHORT_POINTS, grid = family != Family.SMALL)+ bindChart(context, views, R.id.chart_frame, R.id.chart_image_light, R.id.chart_image_dark, spec, chartWidth, chartHeight, m.density)+ if (family == Family.LARGE) bindLarge(context, views, id, data, spec, chartWidth, m)++ views.setOnClickPendingIntent(R.id.chart_root, linkIntent(context, pinLink(context, data.pin, family), id, 0))+ val pill = snapshot.deltaText?.let { arrow(snapshot.deltaSign) + it }+ views.setContentDescription(+ R.id.chart_root,+ listOfNotNull(data.pin.name, snapshot.valueText, pill, snapshot.rangeLabel, updated).joinToString(", "),+ )+ return views+ }++ private fun bindHeadline(context: Context, views: RemoteViews, snapshot: ChartSnapshot) {+ val current = snapshot.series.filter { !it.previous }+ if (snapshot.valueText != null || current.size < 2) {+ views.setViewVisibility(R.id.chart_legend, View.GONE)+ val basis = snapshot.deltaBasis?.takeIf { snapshot.valueText != null && snapshot.deltaText != null }+ views.setTextViewText(R.id.chart_basis, basis ?: "")+ views.setViewVisibility(R.id.chart_basis, if (basis != null) View.VISIBLE else View.GONE)+ return+ }+ views.setViewVisibility(R.id.chart_value_row, View.GONE)+ // Spans cannot follow the launcher's night mode, so the legend dots use the current mode's palette.+ val palette = ChartColors.of(context, isNight(context)).series+ val legend = SpannableStringBuilder()+ current.take(TrendsParser.MAX_SERIES).forEachIndexed { index, series ->+ if (index > 0) legend.append(" ")+ val start = legend.length+ legend.append("■")+ legend.setSpan(ForegroundColorSpan(palette[index % palette.size]), start, legend.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ legend.append(" ").append(series.label)+ }+ views.setTextViewText(R.id.chart_legend, legend)+ views.setViewVisibility(R.id.chart_legend, View.VISIBLE)+ }++ private fun bindLarge(context: Context, views: RemoteViews, id: Int, data: Resolved.Data, spec: ChartSpec?, chartWidth: Float, m: Metrics) {+ val first = data.snapshot.series.firstOrNull { !it.previous }?.points?.takeLast(TrendsParser.MAX_POINTS)+ if (spec != null && first != null && first.isNotEmpty()) {+ views.setTextViewText(R.id.chart_axis_start, DateText.axisDate(first.first().at, data.snapshot.intervalLabel))+ views.setTextViewText(R.id.chart_axis_end, DateText.axisDate(first.last().at, data.snapshot.intervalLabel))+ views.setViewVisibility(R.id.chart_axis, View.VISIBLE)+ } else {+ views.setViewVisibility(R.id.chart_axis, View.GONE)+ }+ if (data.extras.isEmpty()) {+ views.setViewVisibility(R.id.chart_tiles, View.GONE)+ return+ }+ views.setViewVisibility(R.id.chart_tiles, View.VISIBLE)+ val tileWidth = (if (data.extras.size > 1) (chartWidth - m.dp(8f)) / 2 else chartWidth) - m.dp(20f)+ TILES.forEachIndexed { index, ids ->+ val extra = data.extras.getOrNull(index)+ if (extra == null) {+ views.setViewVisibility(ids.root, View.GONE)+ return@forEachIndexed+ }+ val pin = extra.pin+ val snapshot = extra.snapshot.visibleAfter(extra.error)+ views.setViewVisibility(ids.root, View.VISIBLE)+ views.setTextViewText(ids.title, pin.name)+ views.setOnClickPendingIntent(ids.root, linkIntent(context, pinLink(context, pin, Family.LARGE), id, index + 1))+ if (snapshot == null) {+ val status = extra.error?.let { failureText(context, it.kind).first } ?: context.getString(R.string.chart_widget_loading)+ views.setTextViewText(ids.range, status)+ views.setViewVisibility(ids.value, View.GONE)+ views.setViewVisibility(ids.delta, View.GONE)+ views.setViewVisibility(ids.frame, View.GONE)+ return@forEachIndexed+ }+ views.setTextViewText(ids.range, snapshot.rangeLabel ?: "")+ bindValue(context, views, ids.value, ids.delta, snapshot)+ val sparkline = specOf(snapshot, SHORT_POINTS, grid = false)+ bindChart(context, views, ids.frame, ids.light, ids.dark, sparkline, tileWidth, m.dp(28f), m.density)+ }+ }++ private fun bindValue(context: Context, views: RemoteViews, valueId: Int, deltaId: Int, snapshot: ChartSnapshot) {+ val value = snapshot.valueText+ if (value == null) {+ views.setViewVisibility(valueId, View.GONE)+ views.setViewVisibility(deltaId, View.GONE)+ return+ }+ views.setViewVisibility(valueId, View.VISIBLE)+ views.setTextViewText(valueId, value)+ val delta = snapshot.deltaText+ if (delta == null) {+ views.setViewVisibility(deltaId, View.GONE)+ return+ }+ views.setViewVisibility(deltaId, View.VISIBLE)+ views.setTextViewText(deltaId, arrow(snapshot.deltaSign) + delta)+ val (background, color) = when (snapshot.deltaSign) {+ 1 -> R.drawable.chart_widget_pill_up to R.color.chart_widget_green+ -1 -> R.drawable.chart_widget_pill_down to R.color.chart_widget_red+ else -> R.drawable.chart_widget_pill_flat to R.color.chart_widget_secondary+ }+ views.setInt(deltaId, "setBackgroundResource", background)+ setTextColor(context, views, deltaId, color)+ }++ private fun arrow(sign: Int): String = when (sign) {+ 1 -> "▲ "+ -1 -> "▼ "+ else -> ""+ }++ private fun specOf(snapshot: ChartSnapshot, maxPoints: Int, grid: Boolean): ChartSpec? {+ val current = snapshot.series.filter { !it.previous }.take(TrendsParser.MAX_SERIES)+ val length = current.firstOrNull()?.points?.size ?: return null+ if (length == 0) return null+ val start = max(0, length - maxPoints)+ val values = current.map { series -> series.points.take(length).drop(start).map { it.value } }+ val bars = snapshot.chartKind == "bar"+ val previous = snapshot.series.firstOrNull { it.previous }+ ?.takeIf { current.size == 1 && !bars }+ ?.points?.take(length)?.drop(start)?.map { it.value }+ return ChartSpec(values, previous, bars, snapshot.inProgress, grid)+ }++ /** Draws the chart for both themes; the layout shows the one that matches the launcher's night mode. */+ private fun bindChart(+ context: Context,+ views: RemoteViews,+ frameId: Int,+ lightId: Int,+ darkId: Int,+ spec: ChartSpec?,+ widthPx: Float,+ heightPx: Float,+ density: Float,+ ) {+ val fits = heightPx >= MIN_CHART_DP * density && widthPx >= MIN_CHART_DP * density+ val light = if (spec != null && fits) ChartCanvas.draw(spec, ChartColors.of(context, false), widthPx.toInt(), heightPx.toInt(), density) else null+ val dark = if (spec != null && light != null) ChartCanvas.draw(spec, ChartColors.of(context, true), widthPx.toInt(), heightPx.toInt(), density) else null+ if (light == null || dark == null) {+ views.setViewVisibility(frameId, View.GONE)+ return+ }+ views.setViewVisibility(frameId, View.VISIBLE)+ views.setImageViewBitmap(lightId, light)+ views.setImageViewBitmap(darkId, dark)+ }++ /** From Android 12 the launcher picks the color for its own night mode; before that, the current mode decides. */+ private fun setTextColor(context: Context, views: RemoteViews, viewId: Int, colorRes: Int) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ val light = ChartColors.themed(context, false).getColor(colorRes)+ val dark = ChartColors.themed(context, true).getColor(colorRes)+ views.setColorInt(viewId, "setTextColor", light, dark)+ } else {+ views.setTextColor(viewId, context.getColor(colorRes))+ }+ }++ private fun isNight(context: Context): Boolean =+ (context.resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==+ android.content.res.Configuration.UI_MODE_NIGHT_YES++ private fun ageText(context: Context, ageMs: Long): String {+ if (ageMs < 60_000) return context.getString(R.string.chart_widget_updated_just_now)+ val minutes = ageMs / 60_000+ if (minutes < 60) return context.getString(R.string.chart_widget_updated_minutes, minutes.toInt())+ val hours = minutes / 60+ if (hours < 24) return context.getString(R.string.chart_widget_updated_hours, hours.toInt())+ val days = hours / 24+ return if (days == 1L) context.getString(R.string.chart_widget_updated_one_day)+ else context.getString(R.string.chart_widget_updated_days, days.toInt())+ }++ // Mirrors src/lib/appVariants.json: each build variant appends its idSuffix to the package and has its own scheme.+ private val SCHEMES = listOf(".dev" to "posthog-dev", ".preview" to "posthog-preview")++ fun scheme(context: Context): String =+ SCHEMES.firstOrNull { context.packageName.endsWith(it.first) }?.second ?: "posthog"++ /** The deep links in docs/VIEWS.md "Routes"; `family` lets the app report which widget size was tapped. */+ private fun pinLink(context: Context, pin: CatalogPin, family: Family): String {+ val scheme = scheme(context)+ val query = "from=widget&family=${family.key}"+ val dashboardId = pin.dashboardId+ val shortId = pin.shortId+ return when {+ pin.isDashboard && dashboardId != null -> "$scheme://views/dashboard/$dashboardId?$query"+ shortId != null -> "$scheme://views/insight/${Uri.encode(shortId)}?$query"+ else -> "$scheme://views"+ }+ }++ private fun linkIntent(context: Context, link: String, widgetId: Int, slot: Int): PendingIntent {+ val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))+ .setPackage(context.packageName)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ return PendingIntent.getActivity(+ context,+ widgetId * 4 + slot,+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ }++ /** Text heights in px, so the chart bitmap matches the room the text leaves at the user's font size. */+ private class Metrics(context: Context) {+ private val display = context.resources.displayMetrics+ val density: Float = display.density+ fun dp(value: Float): Float = value * density+ fun line(sp: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, display) * 1.18f+ fun pill(): Float = line(10.5f) + dp(3f)+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.ktnew file mode 100644index 000000000000..f2972071cf34--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.kt@@ -0,0 +1,241 @@+package com.posthog.code.mobile.chart++import android.content.Context+import android.content.SharedPreferences+import android.util.Log+import androidx.security.crypto.EncryptedSharedPreferences+import androidx.security.crypto.MasterKey++/** The store contract shared with the app's JavaScript, see modules/chart-widget/README.md. */+object ChartStore {+ private const val TAG = "ChartWidget"+ private const val FILE = "chart_widget"+ private const val SECURE_FILE = "chart_widget_secure"+ private const val KEY_CREDENTIALS = "credentials"+ private const val KEY_CATALOG = "chart.catalog"+ private const val SNAPSHOT_PREFIX = "chart.snapshot."+ private const val ERROR_PREFIX = "chart.snapshotError."+ private const val KEY_RETRY_AT = "chart.retryAt"+ private var sessionGeneration = 0L++ internal data class Session(val generation: Long, val credentials: Credentials)++ private const val WIDGET_PREFIX = "chart.widget."++ private var secure: SharedPreferences? = null+ private var cachedCatalogJson: String? = null+ private var cachedCatalog: Catalog? = null++ private fun prefs(context: Context): SharedPreferences =+ context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)++ /**+ * Null when the keystore cannot open the file. A restored backup or a corrupt key fails the same way, so the file+ * is deleted and created once more; the app writes the session again on its next token change or launch.+ */+ @Synchronized+ private fun securePrefs(context: Context): SharedPreferences? {+ secure?.let { return it }+ val app = context.applicationContext+ for (attempt in 0..1) {+ try {+ val key = MasterKey.Builder(app).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()+ return EncryptedSharedPreferences.create(+ app,+ SECURE_FILE,+ key,+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,+ ).also { secure = it }+ } catch (e: Exception) {+ Log.e(TAG, "Could not open the widget credentials (attempt ${attempt + 1})", e)+ if (attempt == 0) app.deleteSharedPreferences(SECURE_FILE)+ }+ }+ return null+ }++ /** An entry the key can no longer decrypt would fail every later read and write, so the file starts over. */+ @Synchronized+ private fun resetSecure(context: Context) {+ secure = null+ context.applicationContext.deleteSharedPreferences(SECURE_FILE)+ }++ // commit() rather than apply() so the refresh that follows reads the new values.+ @Synchronized+ fun setCredentials(context: Context, json: String) {+ val previous = credentials(context)+ sessionGeneration += 1+ for (attempt in 0..1) {+ try {+ val store = checkNotNull(securePrefs(context)) { "Widget credential storage is unavailable" }+ check(store.edit().putString(KEY_CREDENTIALS, json).commit()) { "Could not persist widget credentials" }+ break+ } catch (e: Exception) {+ Log.e(TAG, "Could not store the widget credentials (attempt ${attempt + 1})", e)+ resetSecure(context)+ if (attempt == 1) throw IllegalStateException("Could not store widget credentials", e)+ }+ }+ val next = credentials(context)+ if (previous?.host != next?.host || previous?.projectId != next?.projectId || previous?.userUuid != next?.userUuid) {+ clearSnapshots(context)+ }+ // A new token answers a rejected one, so the next render may show the cache again.+ val prefs = prefs(context)+ val editor = prefs.edit()+ prefs.all.forEach { (key, value) ->+ if (key.startsWith(ERROR_PREFIX) && (value as? String)?.let(SnapshotError::parse)?.kind == ErrorKind.AUTH) {+ editor.remove(key)+ }+ }+ editor.commit()+ }++ @Synchronized+ fun clearCredentials(context: Context) {+ sessionGeneration += 1+ try {+ securePrefs(context)?.edit()?.remove(KEY_CREDENTIALS)?.commit()+ } catch (e: Exception) {+ Log.e(TAG, "Could not clear the widget credentials", e)+ resetSecure(context)+ }+ clearSnapshots(context)+ }++ private fun clearSnapshots(context: Context) {+ val prefs = prefs(context)+ val editor = prefs.edit().remove(KEY_RETRY_AT)+ prefs.all.keys.filter { it.startsWith(SNAPSHOT_PREFIX) || it.startsWith(ERROR_PREFIX) }.forEach { editor.remove(it) }+ editor.commit()+ }++ @Synchronized+ fun credentials(context: Context): Credentials? = try {+ securePrefs(context)?.getString(KEY_CREDENTIALS, null)?.let(Credentials::parse)+ } catch (e: Exception) {+ Log.e(TAG, "Could not read the widget credentials", e)+ resetSecure(context)+ null+ }++ @Synchronized+ fun setCatalogJson(context: Context, json: String?) {+ val previous = catalog(context)+ val next = json?.let(Catalog::parse)+ val prefs = prefs(context)+ val editor = prefs.edit()+ previous?.pins?.forEach { pin ->+ val replacement = next?.pin(pin.id)+ if (previous.host != next?.host || previous.projectId != next?.projectId ||+ replacement == null || pin.kind != replacement.kind || pin.insightId != replacement.insightId ||+ pin.dashboardId != replacement.dashboardId+ ) {+ editor.remove("$SNAPSHOT_PREFIX${pin.id}").remove("$ERROR_PREFIX${pin.id}")+ }+ }+ if (json == null) editor.remove(KEY_CATALOG) else editor.putString(KEY_CATALOG, json)+ editor.commit()+ }++ @Synchronized+ fun catalog(context: Context): Catalog? {+ val json = prefs(context).getString(KEY_CATALOG, null) ?: return null+ if (json != cachedCatalogJson) {+ cachedCatalogJson = json+ cachedCatalog = Catalog.parse(json)+ }+ return cachedCatalog+ }++ fun widgetConfig(context: Context, id: Int): WidgetConfig? =+ prefs(context).getString("$WIDGET_PREFIX$id", null)?.let(WidgetConfig::parse)++ fun setWidgetConfig(+ context: Context,+ id: Int,+ pinId: String,+ extraPinIds: List<String>,+ projectId: Long? = null,+ projectName: String? = null,+ pinName: String? = null,+ ) {+ val config = WidgetConfig(pinId, extraPinIds, projectId, projectName, pinName)+ prefs(context).edit().putString("$WIDGET_PREFIX$id", config.toJson()).commit()+ }++ fun removeWidget(context: Context, id: Int) {+ val prefs = prefs(context)+ val editor = prefs.edit().remove("$WIDGET_PREFIX$id")+ val keys = prefs.all.keys+ val shown = keys.filter { it.startsWith(WIDGET_PREFIX) && it != "$WIDGET_PREFIX$id" }+ .mapNotNull { prefs.getString(it, null)?.let(WidgetConfig::parse) }+ .flatMap { listOf(it.pinId) + it.extraPinIds }+ .toSet()+ keys.forEach { key ->+ val pinId = when {+ key.startsWith(SNAPSHOT_PREFIX) -> key.removePrefix(SNAPSHOT_PREFIX)+ key.startsWith(ERROR_PREFIX) -> key.removePrefix(ERROR_PREFIX)+ else -> return@forEach+ }+ if (pinId !in shown) editor.remove(key)+ }+ editor.commit()+ }++ /** A restored home screen gives each widget a new id. */+ fun moveWidget(context: Context, from: Int, to: Int) {+ val prefs = prefs(context)+ val json = prefs.getString("$WIDGET_PREFIX$from", null) ?: return+ prefs.edit().remove("$WIDGET_PREFIX$from").putString("$WIDGET_PREFIX$to", json).commit()+ }++ @Synchronized+ internal fun session(context: Context): Session? = credentials(context)?.let { Session(sessionGeneration, it) }++ internal fun retryAt(context: Context): Long = prefs(context).getLong(KEY_RETRY_AT, 0L)++ @Synchronized+ internal fun commitFetch(+ context: Context,+ expectedSession: Session,+ expectedCatalog: Catalog,+ pinIds: List<String>,+ outcome: ChartFetcher.Outcome,+ isStopped: () -> Boolean,+ ): Boolean {+ if (isStopped() || expectedSession != session(context) || expectedCatalog != catalog(context)) return false+ val editor = prefs(context).edit()+ when (outcome) {+ is ChartFetcher.Outcome.Success -> editor+ .putString("$SNAPSHOT_PREFIX${outcome.snapshot.pinId}", outcome.snapshot.toJson())+ .remove("$ERROR_PREFIX${outcome.snapshot.pinId}")+ is ChartFetcher.Outcome.Failure -> {+ val now = System.currentTimeMillis()+ val error = SnapshotError(now, outcome.kind)+ pinIds.forEach { editor.putString("$ERROR_PREFIX$it", error.toJson()) }+ if (outcome.kind == ErrorKind.RATE_LIMITED) editor.putLong(KEY_RETRY_AT, now + outcome.retryAfterMs)+ }+ }+ return editor.commit()+ }++ fun snapshot(context: Context, pinId: String): ChartSnapshot? =+ prefs(context).getString("$SNAPSHOT_PREFIX$pinId", null)?.let(ChartSnapshot::parse)++ fun setSnapshot(context: Context, snapshot: ChartSnapshot) {+ prefs(context).edit()+ .putString("$SNAPSHOT_PREFIX${snapshot.pinId}", snapshot.toJson())+ .remove("$ERROR_PREFIX${snapshot.pinId}")+ .commit()+ }++ fun snapshotError(context: Context, pinId: String): SnapshotError? =+ prefs(context).getString("$ERROR_PREFIX$pinId", null)?.let(SnapshotError::parse)++ fun setSnapshotError(context: Context, pinId: String, error: SnapshotError) {+ prefs(context).edit().putString("$ERROR_PREFIX$pinId", error.toJson()).commit()+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.ktnew file mode 100644index 000000000000..6b921c520a8c--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.kt@@ -0,0 +1,227 @@+package com.posthog.code.mobile.chart++import android.app.Activity+import android.appwidget.AppWidgetManager+import android.content.ComponentName+import android.content.Intent+import android.content.res.ColorStateList+import android.graphics.Typeface+import android.graphics.drawable.GradientDrawable+import android.os.Bundle+import android.text.SpannableStringBuilder+import android.text.Spanned+import android.text.style.AbsoluteSizeSpan+import android.text.style.ForegroundColorSpan+import android.view.Gravity+import android.view.View+import android.view.ViewGroup.LayoutParams.MATCH_PARENT+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT+import android.widget.Button+import android.widget.CheckBox+import android.widget.LinearLayout+import android.widget.RadioButton+import android.widget.RadioGroup+import android.widget.ScrollView+import android.widget.TextView++/** The launcher opens this when a Chart widget is placed or reconfigured. Plain views: React Native is not running. */+class ChartWidgetConfigureActivity : Activity() {+ private var widgetId = AppWidgetManager.INVALID_APPWIDGET_ID+ private var selected: String? = null+ private val extras = LinkedHashSet<String>()+ private val extraBoxes = mutableListOf<Pair<CatalogPin, CheckBox>>()+ private lateinit var content: LinearLayout+ private var footer: View? = null++ private fun isChartWidget(): Boolean = widgetId != AppWidgetManager.INVALID_APPWIDGET_ID &&+ AppWidgetManager.getInstance(this).getAppWidgetInfo(widgetId)?.provider ==+ ComponentName(this, ChartWidgetProvider::class.java)++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ // Leaving any other way than Done must not place the widget.+ setResult(RESULT_CANCELED)+ widgetId = intent?.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)+ ?: AppWidgetManager.INVALID_APPWIDGET_ID+ if (!isChartWidget()) {+ finish()+ return+ }+ content = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(20), dp(8), dp(20), dp(24))+ }+ content.addView(text("✕", 20f, R.color.chart_widget_ink).apply {+ contentDescription = getString(R.string.chart_widget_configure_close)+ layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)+ setPadding(0, dp(8), dp(16), dp(8))+ setOnClickListener { finish() }+ })+ content.addView(text(getString(R.string.chart_widget_choose_pin), 26f, R.color.chart_widget_ink, bold = true))+ content.addView(text(getString(R.string.chart_widget_configure_subtitle), 14f, R.color.chart_widget_secondary).apply {+ setPadding(0, dp(6), 0, dp(12))+ })+ val catalog = ChartStore.catalog(this)+ when {+ ChartStore.credentials(this) == null -> showMessage(getString(R.string.chart_widget_configure_signed_out))+ catalog == null || catalog.pins.isEmpty() -> showMessage(getString(R.string.chart_widget_configure_empty))+ else -> showPicker(catalog)+ }+ setContentView(LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL+ // The window draws behind the system bars, so the content keeps clear of them.+ fitsSystemWindows = true+ addView(ScrollView(this@ChartWidgetConfigureActivity).apply { addView(content, MATCH_PARENT, WRAP_CONTENT) },+ LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))+ // Done stays on screen however long the pin list is.+ footer?.let { addView(it) }+ })+ }++ private fun showMessage(message: String) {+ content.addView(text(message, 16f, R.color.chart_widget_ink).apply { setPadding(0, dp(24), 0, dp(16)) })+ content.addView(button(getString(R.string.chart_widget_configure_open_app)) {+ packageManager.getLaunchIntentForPackage(packageName)?.let(::startActivity)+ finish()+ })+ }++ private fun showPicker(catalog: Catalog) {+ val current = ChartStore.widgetConfig(this, widgetId)+ val eligible = catalog.pins.filter { it.eligible }+ val ineligible = catalog.pins.filter { !it.eligible }+ selected = current?.pinId?.takeIf { id -> eligible.any { it.id == id } }+ current?.extraPinIds?.filter { id -> eligible.any { it.id == id } }?.let(extras::addAll)+ lateinit var done: Button++ val group = RadioGroup(this)+ eligible.forEach { pin ->+ group.addView(RadioButton(this).apply {+ id = View.generateViewId()+ text = twoLines(pin.name, pin.subtitle)+ buttonTintList = ColorStateList.valueOf(color(R.color.chart_widget_ink))+ setPadding(dp(8), dp(10), 0, dp(10))+ isChecked = pin.id == selected+ setOnCheckedChangeListener { _, checked ->+ if (!checked) return@setOnCheckedChangeListener+ selected = pin.id+ extras.remove(pin.id)+ updateExtras()+ done.isEnabled = true+ done.alpha = 1f+ }+ })+ }+ content.addView(group)++ if (ineligible.isNotEmpty()) {+ content.addView(header(getString(R.string.chart_widget_configure_ineligible)))+ ineligible.forEach { pin ->+ content.addView(text("", 16f, R.color.chart_widget_ink).apply {+ text = twoLines(pin.name, pin.reason ?: getString(R.string.chart_widget_ineligible))+ alpha = 0.45f+ setPadding(dp(40), dp(10), 0, dp(10))+ })+ }+ }++ if (eligible.size > 1) {+ content.addView(header(getString(R.string.chart_widget_configure_extras)))+ eligible.forEach { pin ->+ val box = CheckBox(this).apply {+ text = pin.name+ textSize = 16f+ setTextColor(color(R.color.chart_widget_ink))+ buttonTintList = ColorStateList.valueOf(color(R.color.chart_widget_ink))+ setPadding(dp(8), dp(8), 0, dp(8))+ isChecked = pin.id in extras+ setOnCheckedChangeListener { _, checked ->+ if (checked) extras.add(pin.id) else extras.remove(pin.id)+ updateExtras()+ }+ }+ extraBoxes.add(pin to box)+ content.addView(box)+ }+ updateExtras()+ }++ done = button(getString(R.string.chart_widget_configure_done)) { save(catalog) }+ done.isEnabled = selected != null+ done.alpha = if (selected != null) 1f else 0.4f+ (done.layoutParams as LinearLayout.LayoutParams).topMargin = 0+ footer = LinearLayout(this).apply {+ setPadding(dp(20), dp(12), dp(20), dp(12))+ addView(done)+ }+ }++ /** The primary pin is not offered twice, and at most two extras fit the large widget. */+ private fun updateExtras() {+ extraBoxes.forEach { (pin, box) ->+ val primary = pin.id == selected+ if (primary && box.isChecked) box.isChecked = false+ box.isEnabled = !primary && (box.isChecked || extras.size < 2)+ box.alpha = if (box.isEnabled) 1f else 0.45f+ }+ }++ private fun save(catalog: Catalog) {+ if (!isChartWidget()) {+ finish()+ return+ }+ val pin = catalog.pin(selected ?: return) ?: return+ ChartStore.setWidgetConfig(+ this, widgetId, pin.id, extras.filter { it != pin.id }.take(2),+ projectId = catalog.projectId, projectName = catalog.projectName, pinName = pin.name,+ )+ ChartWidgetRefresh.refreshAll(this)+ setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId))+ finish()+ }++ private fun twoLines(title: String, subtitle: String): CharSequence {+ val text = SpannableStringBuilder(title)+ if (subtitle.isNotBlank()) {+ val start = text.length+ text.append("\n").append(subtitle)+ text.setSpan(AbsoluteSizeSpan(13, true), start, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ text.setSpan(ForegroundColorSpan(color(R.color.chart_widget_secondary)), start, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ }+ return text+ }++ private fun header(label: String): TextView = text(label, 12f, R.color.chart_widget_tertiary, bold = true).apply {+ isAllCaps = true+ letterSpacing = 0.08f+ setPadding(0, dp(20), 0, dp(6))+ }++ private fun text(value: String, size: Float, colorRes: Int, bold: Boolean = false): TextView = TextView(this).apply {+ text = value+ textSize = size+ setTextColor(color(colorRes))+ if (bold) typeface = Typeface.create("sans-serif-medium", Typeface.BOLD)+ }++ private fun button(label: String, onClick: () -> Unit): Button = Button(this).apply {+ text = label+ isAllCaps = false+ textSize = 16f+ typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)+ setTextColor(color(R.color.chart_widget_on_orange))+ background = GradientDrawable().apply {+ setColor(color(R.color.chart_widget_orange))+ cornerRadius = dp(24).toFloat()+ }+ stateListAnimator = null+ gravity = Gravity.CENTER+ layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, dp(48)).apply { topMargin = dp(24) }+ setOnClickListener { onClick() }+ }++ private fun color(res: Int): Int = getColor(res)++ private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.ktnew file mode 100644index 000000000000..557faaaea66f--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.kt@@ -0,0 +1,37 @@+package com.posthog.code.mobile.chart++import expo.modules.kotlin.exception.Exceptions+import expo.modules.kotlin.modules.Module+import expo.modules.kotlin.modules.ModuleDefinition++class ChartWidgetModule : Module() {+ override fun definition() = ModuleDefinition {+ Name("ChartWidget")++ Function("setCredentials") { json: String ->+ ChartStore.setCredentials(context(), json)+ ChartWidgetRefresh.refreshAll(context())+ }++ Function("clearCredentials") {+ ChartStore.clearCredentials(context())+ ChartWidgetRefresh.refreshAll(context())+ }++ Function("setCatalog") { json: String ->+ ChartStore.setCatalogJson(context(), json)+ ChartWidgetRefresh.refreshAll(context())+ }++ Function("clearCatalog") {+ ChartStore.setCatalogJson(context(), null)+ ChartWidgetRefresh.refreshAll(context())+ }++ Function("reloadWidgets") {+ ChartWidgetRefresh.refreshAll(context())+ }+ }++ private fun context() = appContext.reactContext?.applicationContext ?: throw Exceptions.ReactContextLost()+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetProvider.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetProvider.ktnew file mode 100644index 000000000000..27bb233fbe71--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetProvider.kt@@ -0,0 +1,45 @@+package com.posthog.code.mobile.chart++import android.appwidget.AppWidgetManager+import android.appwidget.AppWidgetProvider+import android.content.Context+import android.content.Intent+import android.os.Bundle+import android.util.Log++class ChartWidgetProvider : AppWidgetProvider() {+ /** Catches everything, because an exception thrown from a broadcast receiver crashes the whole app process. */+ override fun onReceive(context: Context, intent: Intent) {+ try {+ super.onReceive(context, intent)+ } catch (e: Exception) {+ Log.e(ChartRenderer.TAG, "Chart widget broadcast ${intent.action} failed", e)+ }+ }++ override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {+ ChartWidgetRefresh.refreshAll(context)+ }++ override fun onAppWidgetOptionsChanged(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, newOptions: Bundle) {+ val pendingResult = goAsync()+ try {+ ChartRenderer.renderOne(context, appWidgetManager, appWidgetId) { pendingResult?.finish() }+ } catch (e: Exception) {+ pendingResult?.finish()+ throw e+ }+ }++ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ appWidgetIds.forEach { ChartStore.removeWidget(context, it) }+ }++ override fun onDisabled(context: Context) {+ ChartWidgetRefresh.cancel(context)+ }++ override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {+ oldWidgetIds.zip(newWidgetIds).forEach { (from, to) -> ChartStore.moveWidget(context, from, to) }+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.ktnew file mode 100644index 000000000000..f8ad2a7edf53--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.kt@@ -0,0 +1,85 @@+package com.posthog.code.mobile.chart++import android.content.Context+import android.util.Log+import androidx.work.Constraints+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import java.util.concurrent.TimeUnit++object ChartWidgetRefresh {+ private const val TAG = "ChartWidget"+ private const val REFRESH_WORK = "chart-widget-refresh"+ private const val KEEP_ENABLED_WORK = "chart-widget-keep-enabled"+ private const val KEEP_ENABLED_DAYS = 3650L++ /** A new request replaces the queued pass so it uses the latest session and catalog. */+ fun refreshAll(context: Context) {+ val app = context.applicationContext+ ChartRenderer.renderAll(app)+ try {+ if (ChartRenderer.widgetIds(app).isEmpty()) return+ val credentials = ChartStore.credentials(app)+ if (credentials == null || credentials.isExpired(System.currentTimeMillis())) return+ val workManager = WorkManager.getInstance(app)+ // WorkManager disables its reschedule receiver when no work is pending. That component change makes the+ // system send APPWIDGET_UPDATE again, which would queue a new pass forever, so one far-off job stays queued.+ workManager.enqueueUniqueWork(+ KEEP_ENABLED_WORK,+ ExistingWorkPolicy.KEEP,+ OneTimeWorkRequestBuilder<ChartKeepEnabledWorker>().setInitialDelay(KEEP_ENABLED_DAYS, TimeUnit.DAYS).build(),+ )+ val request = OneTimeWorkRequestBuilder<ChartRefreshWorker>()+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())+ .build()+ workManager.enqueueUniqueWork(REFRESH_WORK, ExistingWorkPolicy.REPLACE, request)+ } catch (e: Exception) {+ Log.e(TAG, "Could not queue the chart widget refresh", e)+ }+ }++ fun cancel(context: Context) {+ try {+ val workManager = WorkManager.getInstance(context.applicationContext)+ workManager.cancelUniqueWork(REFRESH_WORK)+ workManager.cancelUniqueWork(KEEP_ENABLED_WORK)+ } catch (e: Exception) {+ Log.e(TAG, "Could not cancel the chart widget refresh", e)+ }+ }++ /**+ * Reads each distinct pin that a placed widget shows, once, and stores the snapshot or the error. A rejected token+ * fails every other pin too, so the pass stops there and marks the rest.+ */+ internal fun fetchShownPins(+ context: Context,+ isStopped: () -> Boolean,+ fetch: (Context, Credentials, CatalogPin) -> ChartFetcher.Outcome = { app, credentials, pin ->+ ChartFetcher.fetch(app, credentials, pin)+ },+ ) {+ val session = ChartStore.session(context) ?: return+ val credentials = session.credentials+ val now = System.currentTimeMillis()+ if (credentials.isExpired(now) || now < ChartStore.retryAt(context)) return+ val catalog = ChartStore.catalog(context)?.takeIf {+ it.projectId == credentials.projectId && it.host == credentials.host+ } ?: return+ val pins = ChartRenderer.widgetIds(context).asList()+ .mapNotNull { ChartStore.widgetConfig(context, it) }+ .flatMap { listOf(it.pinId) + it.extraPinIds }+ .distinct()+ .mapNotNull { catalog.pin(it)?.takeIf { pin -> pin.eligible } }+ for ((index, pin) in pins.withIndex()) {+ if (isStopped() || session != ChartStore.session(context)) return+ val outcome = fetch(context, credentials, pin)+ val stopsPass = outcome is ChartFetcher.Outcome.Failure &&+ (outcome.kind == ErrorKind.AUTH || outcome.kind == ErrorKind.RATE_LIMITED)+ val affected = if (stopsPass) pins.drop(index).map { it.id } else listOf(pin.id)+ if (!ChartStore.commitFetch(context, session, catalog, affected, outcome, isStopped) || stopsPass) return+ }+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.ktnew file mode 100644index 000000000000..7e2ef465d9ad--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.kt@@ -0,0 +1,438 @@+package com.posthog.code.mobile.chart++import org.json.JSONArray+import org.json.JSONObject+import java.math.BigDecimal+import java.math.MathContext+import java.math.RoundingMode+import java.text.DecimalFormat+import java.text.DecimalFormatSymbols+import java.util.Calendar+import java.util.Locale+import java.util.TimeZone+import kotlin.math.abs+import kotlin.math.floor+import kotlin.math.log10+import kotlin.math.max+import kotlin.math.min++class BadDataException(message: String) : Exception(message)++/**+ * Turns a `TrendsQuery` insight response into a widget snapshot. Mirrors `trendsEntries`, `seriesViews`, `pointsOf`,+ * `compareOf`, `numberParts` and `inProgressFrom` in `src/model/adapters/insightSnapshot.ts`, value formatting in+ * `src/model/adapters/insightFormatting.ts`, and the labels in `src/features/views/snapshotChart.ts` and `rangePresets.ts`.+ */+object TrendsParser {+ const val MAX_SERIES = 5+ const val MAX_POINTS = 60++ private val BAR_DISPLAYS = setOf("ActionsBar", "ActionsStackedBar", "ActionsUnstackedBar")+ private val INTERVALS = setOf("hour", "day", "week", "month")+ private val INTERVAL_MS = mapOf("hour" to 3_600_000L, "day" to 86_400_000L, "week" to 7 * 86_400_000L, "month" to 31 * 86_400_000L)+ // Distinct-user math counts a person once per bucket, so only these add up over a window.+ private val SUMMABLE_MATH = setOf(null, "total", "sum", "first_time_for_user", "first_matching_event_for_user")+ private const val BREAKDOWN_OTHER = "\$\$_posthog_breakdown_other_\$\$"+ private const val BREAKDOWN_NULL = "\$\$_posthog_breakdown_null_\$\$"++ private class Point(val at: String, val value: Double)+ private class Delta(val change: Double, val percent: Double?, val points: Boolean, val compare: Boolean, val previousAt: String?)+ private class NumberParts(val value: Double, val delta: Delta?)++ internal class ValueFormat(+ val style: String?,+ val prefix: String,+ val suffix: String,+ val decimalPlaces: Int?,+ val minDecimalPlaces: Int?,+ )++ fun parse(response: JSONObject, pinId: String, fetchedAt: Long): ChartSnapshot {+ val query = response.optJSONObject("query") ?: throw BadDataException("no query")+ val source = query.optJSONObject("source") ?: query+ if (source.optString("kind") != "TrendsQuery") throw BadDataException("not a trends query")+ val result = response.opt("result") as? JSONArray ?: throw BadDataException("no result")+ val entries = (0 until result.length()).mapNotNull { result.optJSONObject(it) }+ val interval = source.optString("interval").takeIf { it in INTERVALS } ?: "day"+ val trendsFilter = source.optJSONObject("trendsFilter")+ val display = trendsFilter?.stringOrNull("display") ?: query.stringOrNull("display")+ val resolved = response.optJSONObject("resolved_date_range")+ val resolvedFrom = resolved?.stringOrNull("date_from")+ val resolvedTo = resolved?.stringOrNull("date_to")++ val current = entries.filter { compareOf(it) != "previous" }+ val firstPoints = pointsOf(current.firstOrNull())+ val inProgressAt = inProgressFrom(firstPoints, resolvedTo, interval, fetchedAt)+ val format = formatOf(trendsFilter)+ val number = display == "BoldNumber" ||+ (!hasBreakdown(source) && (seriesNodes(source).size == 1 || current.size == 1))+ val parts = if (number) numberParts(source, entries, format, inProgressAt) else null+ // A change against zero has no percent, so it gets no pill, like iOS.+ val delta = parts?.delta?.takeIf { it.points || it.percent != null || it.change == 0.0 }++ return ChartSnapshot(+ pinId = pinId,+ fetchedAt = fetchedAt,+ lastRefreshAt = response.stringOrNull("last_refresh"),+ rangeLabel = rangeLabel(source, resolvedFrom, resolvedTo, interval),+ intervalLabel = interval,+ valueText = parts?.let { formatValue(it.value, format, compact = true) },+ deltaPercent = delta?.let { if (it.points) it.change else it.percent },+ deltaText = delta?.let { deltaText(it) },+ deltaBasis = delta?.let { deltaBasis(it, interval) },+ inProgress = inProgressAt != null,+ series = seriesOf(current, entries),+ chartKind = if (display in BAR_DISPLAYS) "bar" else "line",+ )+ }++ private fun compareOf(entry: JSONObject): String? = when (entry.optString("compare_label")) {+ "previous" -> "previous"+ "current" -> "current"+ else -> null+ }++ private fun seriesIndexOf(entry: JSONObject, fallback: Int): Int =+ (entry.optJSONObject("action")?.opt("order") as? Number)?.toInt() ?: fallback++ private fun breakdownKey(entry: JSONObject): String? =+ entry.opt("breakdown_value")?.takeIf { it != JSONObject.NULL }?.toString()++ private fun breakdownLabel(entry: JSONObject): String? {+ fun part(value: Any?): String? = when (value) {+ BREAKDOWN_OTHER -> "Other"+ BREAKDOWN_NULL -> "None"+ is String -> value+ is Number -> value.toString()+ else -> null+ }+ return when (val value = entry.opt("breakdown_value")) {+ is JSONArray -> (0 until value.length()).mapNotNull { part(value.opt(it)) }.takeIf { it.isNotEmpty() }?.joinToString(", ")+ else -> part(value)+ }+ }++ private fun labelOf(entry: JSONObject, index: Int): String {+ val raw = entry.stringOrNull("label")+ ?.replace(BREAKDOWN_OTHER, "Other")?.replace(BREAKDOWN_NULL, "None")+ ?: "Series ${seriesIndexOf(entry, index) + 1}"+ val breakdown = breakdownLabel(entry)+ return if (breakdown.isNullOrEmpty() || raw.contains(breakdown)) raw else "$raw · $breakdown"+ }++ private fun pointsOf(entry: JSONObject?): List<Point> {+ val days = entry?.optJSONArray("days") ?: return emptyList()+ val data = entry.optJSONArray("data") ?: return emptyList()+ val length = min(days.length(), data.length())+ return (0 until length).map { index ->+ Point(days.optString(index), (data.opt(index) as? Number)?.toDouble()?.takeIf { it.isFinite() } ?: Double.NaN)+ }+ }++ private fun seriesOf(current: List<JSONObject>, entries: List<JSONObject>): List<SnapshotSeries> {+ val shown = current.take(MAX_SERIES)+ val length = pointsOf(shown.firstOrNull()).size+ val start = max(0, length - MAX_POINTS)+ val result = shown.mapIndexed { index, entry ->+ SnapshotSeries(labelOf(entry, index), pointsOf(entry).drop(start).map { SnapshotPoint(it.at, it.value) }, false)+ }.toMutableList()+ val first = shown.firstOrNull()+ if (shown.size == 1 && first != null) {+ val partner = entries.firstOrNull {+ compareOf(it) == "previous" && seriesIndexOf(it, 0) == seriesIndexOf(first, 0) && breakdownKey(it) == breakdownKey(first)+ }+ if (partner != null) {+ val points = pointsOf(partner).take(length).drop(start).map { SnapshotPoint(it.at, it.value) }+ result.add(SnapshotSeries("Previous period", points, true))+ }+ }+ return result+ }++ private fun seriesNodes(source: JSONObject): List<JSONObject> {+ val series = source.optJSONArray("series") ?: return emptyList()+ return (0 until series.length()).mapNotNull { series.optJSONObject(it) }+ }++ private fun hasBreakdown(source: JSONObject): Boolean {+ val filter = source.optJSONObject("breakdownFilter") ?: return false+ val breakdown = filter.opt("breakdown")+ val single = breakdown != null && breakdown != JSONObject.NULL && breakdown != false && breakdown != ""+ return single || (filter.optJSONArray("breakdowns")?.length() ?: 0) > 0+ }++ private fun isSummable(source: JSONObject): Boolean =+ seriesNodes(source).firstOrNull()?.stringOrNull("math") in SUMMABLE_MATH++ private fun inProgressFrom(points: List<Point>, resolvedTo: String?, interval: String, now: Long): String? {+ val last = points.lastOrNull() ?: return null+ if (resolvedTo != null) {+ val to = DateText.parseInstant(resolvedTo) ?: return null+ return if (to > now) last.at else null+ }+ val start = DateText.parseInstant(last.at) ?: return null+ return if (start + (INTERVAL_MS[interval] ?: 0L) > now) last.at else null+ }++ /**+ * The big number and its delta, so both describe the same thing: the server aggregate against the previous+ * aggregate; with a compare series and summable math the window totals; else the last complete bucket against the+ * same bucket of the previous period, or the bucket before it.+ */+ private fun numberParts(source: JSONObject, entries: List<JSONObject>, format: ValueFormat, inProgressAt: String?): NumberParts? {+ val current = entries.firstOrNull { compareOf(it) != "previous" } ?: return null+ val index0 = seriesIndexOf(current, 0)+ val previousEntry = entries.firstOrNull {+ compareOf(it) == "previous" && seriesIndexOf(it, 0) == index0 && breakdownKey(it) == breakdownKey(current)+ }+ val aggregate = current.doubleOrNull("aggregated_value")+ if (aggregate != null) {+ val previousAggregate = previousEntry?.doubleOrNull("aggregated_value")+ return NumberParts(aggregate, previousAggregate?.let { makeDelta(aggregate, it, true, null, format) })+ }+ val points = pointsOf(current)+ val previousPoints = pointsOf(previousEntry)+ if (previousEntry != null && isSummable(source)) {+ val total = sumFinite(points) ?: return null+ val previousTotal = sumFinite(previousPoints)+ return NumberParts(total, previousTotal?.let { makeDelta(total, it, true, null, format) })+ }+ val complete = if (inProgressAt != null && points.lastOrNull()?.at == inProgressAt) points.dropLast(1) else points+ val index = complete.indexOfLast { it.value.isFinite() }+ if (index < 0) return null+ val point = complete[index]+ val against = if (previousEntry != null) previousPoints.getOrNull(index) else complete.getOrNull(index - 1)+ val delta = against?.takeIf { it.value.isFinite() }+ ?.let { makeDelta(point.value, it.value, previousEntry != null, it.at, format) }+ return NumberParts(point.value, delta)+ }++ private fun sumFinite(points: List<Point>): Double? =+ points.map { it.value }.filter { it.isFinite() }.takeIf { it.isNotEmpty() }?.sum()++ private fun makeDelta(value: Double, previous: Double, compare: Boolean, previousAt: String?, format: ValueFormat): Delta {+ val change = value - previous+ val points = format.style == "percentage" || format.style == "percentage_scaled"+ return Delta(+ change = if (format.style == "percentage_scaled") change * 100 else change,+ percent = if (previous == 0.0) null else change / abs(previous) * 100,+ points = points,+ compare = compare,+ previousAt = previousAt,+ )+ }++ private fun deltaText(delta: Delta): String {+ if (delta.change == 0.0) return "No change"+ if (delta.points) return "${number(abs(delta.change), 1, 1)} pts"+ val size = abs(delta.percent ?: 0.0)+ return "${number(size, if (size >= 10) 0 else 1)}%"+ }++ /** `deltaBasisText` in snapshotChart.ts: "vs previous period" or "vs Oct 12". */+ private fun deltaBasis(delta: Delta, interval: String): String {+ val at = delta.previousAt+ if (delta.compare || at == null) return "vs previous period"+ return "vs ${DateText.axisDate(at, interval)}"+ }++ private fun formatOf(filter: JSONObject?): ValueFormat {+ fun precision(key: String): Int? =+ (filter?.opt(key) as? Number)?.takeIf { it.toDouble() == floor(it.toDouble()) }?.toInt()?.takeIf { it in 0..100 }+ return ValueFormat(+ style = filter?.stringOrNull("aggregationAxisFormat"),+ prefix = filter?.stringOrNull("aggregationAxisPrefix") ?: "",+ suffix = filter?.stringOrNull("aggregationAxisPostfix") ?: "",+ decimalPlaces = precision("decimalPlaces"),+ minDecimalPlaces = precision("minDecimalPlaces"),+ )+ }++ /**+ * `formatInsightValue` for trends. `compact` writes counts and amounts from 10,000 up as "18.3k" or "1.2M", like the+ * pin cards, because a widget has room for few digits.+ */+ internal fun formatValue(value: Double, format: ValueFormat, compact: Boolean): String {+ val style = format.style+ val scaled = if (style == "percentage_scaled") value * 100 else value+ val formatted = when (style) {+ "percentage", "percentage_scaled" ->+ "${number(scaled, format.decimalPlaces ?: significantDecimals(scaled, format.minDecimalPlaces))}%"+ "currency" -> if (compact && abs(value) >= 10_000) "$${compactNumber(value)}" else "$${number(value, 2, 2)}"+ "short" -> shortNumber(value)+ "duration" -> duration(value * 1000)+ "duration_ms" -> duration(value)+ "duration_ns" -> when {+ abs(value) < 1000 -> "${number(value, 2)}ns"+ abs(value) < 1_000_000 -> "${number(value / 1000, 2)}µs"+ else -> duration(value / 1_000_000)+ }+ else -> if (compact && abs(scaled) >= 10_000) {+ compactNumber(scaled)+ } else {+ val minimum = format.minDecimalPlaces ?: 0+ number(scaled, format.decimalPlaces ?: significantDecimals(scaled, format.minDecimalPlaces), minimum)+ }+ }+ val prefix = if (style == "currency" && format.prefix.isNotEmpty() && formatted.startsWith(format.prefix)) "" else format.prefix+ return "$prefix$formatted${format.suffix}"+ }++ /** `toLocaleString('en-US')` with the given fraction digits, rounding half away from zero like ICU. */+ internal fun number(value: Double, maximumFractionDigits: Int, minimumFractionDigits: Int = 0): String {+ val format = DecimalFormat("#,##0", DecimalFormatSymbols(Locale.US))+ format.maximumFractionDigits = max(maximumFractionDigits, minimumFractionDigits)+ format.minimumFractionDigits = minimumFractionDigits+ format.roundingMode = RoundingMode.HALF_UP+ return format.format(value)+ }++ private fun significantDecimals(value: Double, minimum: Int?): Int {+ val floor = minimum ?: 2+ if (!value.isFinite() || value == 0.0) return floor+ return min(max(floor, 1 - floor(log10(abs(value))).toInt()), 10)+ }++ private fun compactNumber(value: Double): String {+ val units = listOf("k", "M", "B", "T")+ var scaled = value / 1000+ var unit = 0+ while (abs(BigDecimal(scaled).setScale(1, RoundingMode.HALF_UP).toDouble()) >= 1000 && unit < units.size - 1) {+ scaled /= 1000+ unit+++ }+ return "${number(scaled, 1)}${units[unit]}"+ }++ private fun shortNumber(value: Double): String {+ val magnitudes = listOf("", "K", "M", "B", "T", "P", "E", "Z", "Y")+ if (!value.isFinite()) return value.toString()+ var rounded = BigDecimal(value).round(MathContext(3)).toDouble()+ var magnitude = 0+ while (abs(rounded) >= 1000 && magnitude < magnitudes.size - 1) {+ magnitude+++ rounded /= 1000+ }+ val text = BigDecimal(rounded).round(MathContext(3)).stripTrailingZeros().toPlainString()+ return if (magnitude > 0) "$text ${magnitudes[magnitude]}" else text+ }++ private fun duration(milliseconds: Double): String {+ val absolute = abs(milliseconds)+ if (absolute == 0.0) return "0s"+ if (absolute < 60_000) {+ val value = if (absolute < 1000) milliseconds else milliseconds / 1000+ val decimals = min(max(0, 2 - floor(log10(abs(value))).toInt()), 4)+ return "${number(value, decimals)}${if (absolute < 1000) "ms" else "s"}"+ }+ val seconds = floor(absolute / 1000).toLong()+ val days = seconds / 86400+ val hours = (seconds % 86400) / 3600+ val minutes = (seconds % 3600) / 60+ val parts = if (days > 0) listOf(days to "d", hours to "h") else listOf(hours to "h", minutes to "m", seconds % 60 to "s")+ val sign = if (milliseconds < 0) "-" else ""+ return sign + parts.filter { it.first != 0L }.joinToString(" ") { "${it.first}${it.second}" }+ }++ private val PRESETS = mapOf(+ ("dStart" to null) to "Today",+ ("-1dStart" to "-1dEnd") to "Yesterday",+ ("-24h" to null) to "Last 24 hours",+ ("-7d" to null) to "Last 7 days",+ ("-30d" to null) to "Last 30 days",+ ("-90d" to null) to "Last 90 days",+ ("wStart" to null) to "This week",+ ("mStart" to null) to "This month",+ ("-1mStart" to "-1mEnd") to "Last month",+ ("yStart" to null) to "This year",+ ("all" to null) to "All time",+ ("-1h" to null) to "Last hour",+ ("-48h" to null) to "Last 48 hours",+ ("-14d" to null) to "Last 14 days",+ ("-180d" to null) to "Last 180 days",+ ("-1wStart" to "-1wEnd") to "Last week",+ )+ private val RELATIVE = Regex("""^-(\d+)([hdwmy])$""")+ private val RELATIVE_NOUNS = mapOf("h" to "hour", "d" to "day", "w" to "week", "m" to "month", "y" to "year")++ /** `rangeLabel` in rangePresets.ts for the saved range; an unknown range falls back to the resolved window. */+ private fun rangeLabel(source: JSONObject, resolvedFrom: String?, resolvedTo: String?, interval: String): String? {+ val range = source.optJSONObject("dateRange") ?: source.optJSONObject("filters")?.optJSONObject("dateRange")+ val dateFrom = range?.stringOrNull("date_from")+ val dateTo = range?.stringOrNull("date_to")+ val resolvedText = if (resolvedFrom != null && resolvedTo != null) {+ if (interval == "hour") DateText.rangeSpan(resolvedFrom, resolvedTo)+ else DateText.rangeSpan(resolvedFrom.take(10), resolvedTo.take(10))+ } else {+ null+ }+ if (dateFrom == null) return resolvedText+ PRESETS[dateFrom to dateTo]?.let { return it }+ val relative = RELATIVE.matchEntire(dateFrom)+ val noun = relative?.groupValues?.get(2)?.let(RELATIVE_NOUNS::get)+ if (relative != null && noun != null && dateTo == null) {+ val amount = relative.groupValues[1].toInt()+ return if (amount == 1) "Last $noun" else "Last $amount ${noun}s"+ }+ if (DateText.wallTime(dateFrom) != null) return DateText.rangeSpan(dateFrom, dateTo ?: dateFrom)+ return resolvedText ?: dateFrom+ }+}++/** Dates as the server writes them: bucket labels and resolved ranges are wall-clock time in the project timezone. */+internal object DateText {+ private val MONTHS = listOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")+ private val WALL = Regex("""^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?""")+ private val ISO = Regex("""^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?$""")++ class Wall(val year: Int, val month: Int, val day: Int, val time: String?) {+ val monthDay: String get() = "${MONTHS.getOrElse(month - 1) { "" }} $day"+ }++ fun wallTime(value: String): Wall? {+ val m = WALL.find(value) ?: return null+ val (year, month, day, hour, minute) = m.destructured+ return Wall(year.toInt(), month.toInt(), day.toInt(), if (hour.isEmpty()) null else "$hour:$minute")+ }++ /** Epoch ms. Without an offset the text is device-local wall time, like `parseBucketStart`. */+ fun parseInstant(value: String): Long? {+ val m = ISO.matchEntire(value.trim()) ?: return null+ val g = m.groupValues+ val zone = when {+ g[8].isEmpty() -> TimeZone.getDefault()+ g[8] == "Z" -> TimeZone.getTimeZone("UTC")+ else -> {+ val digits = g[8].substring(1).replace(":", "")+ TimeZone.getTimeZone("GMT${g[8][0]}${digits.take(2)}:${digits.drop(2).ifEmpty { "00" }}")+ }+ }+ val calendar = Calendar.getInstance(zone)+ calendar.clear()+ calendar.set(g[1].toInt(), g[2].toInt() - 1, g[3].toInt(), g[4].toIntOrNull() ?: 0, g[5].toIntOrNull() ?: 0, g[6].toIntOrNull() ?: 0)+ val millis = g[7].take(3).padEnd(3, '0').toIntOrNull() ?: 0+ return calendar.timeInMillis + millis+ }++ /** `formatAxisDate`: "14:00" for hours, "Oct 12" for days and weeks, "Oct 2026" for months. */+ fun axisDate(at: String, interval: String): String {+ val wall = wallTime(at) ?: return at+ return when (interval) {+ "hour" -> wall.time ?: "00:00"+ "month" -> "${MONTHS.getOrElse(wall.month - 1) { "" }} ${wall.year}"+ else -> wall.monthDay+ }+ }++ /** `formatRangeSpan` with " to ", the wording the widget uses instead of a dash: "Oct 22 to Nov 4". */+ fun rangeSpan(from: String, to: String, separator: String = " to "): String {+ val a = wallTime(from)+ val b = wallTime(to)+ if (a == null || b == null) return "$from$separator$to"+ if (a.time != null || b.time != null) return "${a.monthDay} ${a.time ?: "00:00"}$separator${b.monthDay} ${b.time ?: "00:00"}"+ if (a.year != b.year) return "${a.monthDay}, ${a.year}$separator${b.monthDay}, ${b.year}"+ if (a.month == b.month && a.day == b.day) return a.monthDay+ if (a.month == b.month) return "${a.monthDay}$separator${b.day}"+ return "${a.monthDay}$separator${b.monthDay}"+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xmlnew file mode 100644index 000000000000..78af2560e65d--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xml@@ -0,0 +1,5 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">+ <solid android:color="@color/chart_widget_surface" />+ <stroke android:width="1dp" android:color="@color/chart_widget_hairline" />+ <corners android:radius="24dp" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_glyph.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_glyph.xmlnew file mode 100644index 000000000000..7dadad927944--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_glyph.xml@@ -0,0 +1,12 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="12dp"+ android:height="12dp"+ android:viewportWidth="12"+ android:viewportHeight="12">+ <path+ android:pathData="M1,9.5 L4.2,6.3 L6.6,8 L11,3.2"+ android:strokeColor="@color/chart_widget_secondary"+ android:strokeWidth="1.4"+ android:strokeLineCap="round"+ android:strokeLineJoin="round" />+</vector>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_down.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_down.xmlnew file mode 100644index 000000000000..bc06f2e0c7c1--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_down.xml@@ -0,0 +1,4 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">+ <solid android:color="@color/chart_widget_red_tint" />+ <corners android:radius="6dp" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_flat.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_flat.xmlnew file mode 100644index 000000000000..6f0c8f365406--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_flat.xml@@ -0,0 +1,4 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">+ <solid android:color="@color/chart_widget_neutral_tint" />+ <corners android:radius="6dp" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_up.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_up.xmlnew file mode 100644index 000000000000..a63f3b529756--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_pill_up.xml@@ -0,0 +1,4 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">+ <solid android:color="@color/chart_widget_green_tint" />+ <corners android:radius="6dp" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_placeholder.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_placeholder.xmlnew file mode 100644index 000000000000..239484c5e37b--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_placeholder.xml@@ -0,0 +1,12 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="120dp"+ android:height="28dp"+ android:viewportWidth="120"+ android:viewportHeight="28">+ <path+ android:pathData="M2,22 L14,19 L26,21 L38,15 L50,17 L62,11 L74,14 L86,8 L98,10 L110,5 L118,6"+ android:strokeColor="@color/chart_widget_hairline"+ android:strokeWidth="2"+ android:strokeLineCap="round"+ android:strokeLineJoin="round" />+</vector>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_preview_chart.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_preview_chart.xmlnew file mode 100644index 000000000000..bc9376de7703--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_preview_chart.xml@@ -0,0 +1,25 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="240dp"+ android:height="60dp"+ android:viewportWidth="240"+ android:viewportHeight="60">+ <path+ android:pathData="M0,1 L240,1 M0,30 L240,30 M0,59 L240,59"+ android:strokeColor="@color/chart_widget_hairline"+ android:strokeWidth="1" />+ <path+ android:pathData="M3,46 L20,42 L38,44 L55,36 L72,39 L90,31 L107,34 L124,25 L141,28 L159,20 L176,23 L193,14 L211,16 L228,9 L237,6 L237,59 L3,59 Z"+ android:fillColor="@color/chart_widget_series_1"+ android:fillAlpha="0.12" />+ <path+ android:pathData="M3,50 L20,47 L38,49 L55,45 L72,46 L90,41 L107,43 L124,38 L141,40 L159,35 L176,37 L193,31 L211,33 L228,29 L237,28"+ android:strokeColor="@color/chart_widget_previous"+ android:strokeWidth="1.2"+ android:strokeLineCap="round" />+ <path+ android:pathData="M3,46 L20,42 L38,44 L55,36 L72,39 L90,31 L107,34 L124,25 L141,28 L159,20 L176,23 L193,14 L211,16 L228,9 L237,6"+ android:strokeColor="@color/chart_widget_series_1"+ android:strokeWidth="2"+ android:strokeLineCap="round"+ android:strokeLineJoin="round" />+</vector>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_tile_background.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_tile_background.xmlnew file mode 100644index 000000000000..de31dab40a6e--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_tile_background.xml@@ -0,0 +1,4 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">+ <solid android:color="@color/chart_widget_background" />+ <corners android:radius="14dp" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xmlnew file mode 100644index 000000000000..8e3ba66408ac--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xml@@ -0,0 +1,254 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/chart_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_padding">++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <ImageView+ android:layout_width="12dp"+ android:layout_height="12dp"+ android:importantForAccessibility="no"+ android:src="@drawable/chart_widget_glyph" />++ <TextView+ android:id="@+id/chart_title"+ style="@style/ChartWidgetText.Title"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:layout_weight="1" />+ </LinearLayout>++ <LinearLayout+ android:id="@+id/chart_value_row"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_value"+ style="@style/ChartWidgetText.Value"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_delta"+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp" />++ <TextView+ android:id="@+id/chart_basis"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:layout_weight="1" />+ </LinearLayout>++ <TextView+ android:id="@+id/chart_legend"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:visibility="gone" />++ <FrameLayout+ android:id="@+id/chart_frame"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_marginTop="8dp"+ android:layout_weight="1">+ <ImageView+ android:id="@+id/chart_image_light"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_light_visibility" />+ <ImageView+ android:id="@+id/chart_image_dark"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_dark_visibility" />+ </FrameLayout>++ <LinearLayout+ android:id="@+id/chart_axis"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_axis_start"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1" />++ <TextView+ android:id="@+id/chart_axis_end"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content" />+ </LinearLayout>++ <LinearLayout+ android:id="@+id/chart_tiles"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="10dp"+ android:orientation="horizontal"+ android:visibility="gone">++ <LinearLayout+ android:id="@+id/chart_tile_1"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:background="@drawable/chart_widget_tile_background"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_tile_padding">++ <TextView+ android:id="@+id/chart_tile_1_title"+ style="@style/ChartWidgetText.Title"+ android:layout_width="match_parent"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_tile_1_range"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="1dp" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_tile_1_value"+ style="@style/ChartWidgetText.Value.Tile"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_tile_1_delta"+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp" />+ </LinearLayout>++ <FrameLayout+ android:id="@+id/chart_tile_1_frame"+ android:layout_width="match_parent"+ android:layout_height="@dimen/chart_widget_tile_sparkline_height"+ android:layout_marginTop="6dp">+ <ImageView+ android:id="@+id/chart_tile_1_image_light"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_light_visibility" />+ <ImageView+ android:id="@+id/chart_tile_1_image_dark"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_dark_visibility" />+ </FrameLayout>+ </LinearLayout>++ <LinearLayout+ android:id="@+id/chart_tile_2"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:layout_marginStart="@dimen/chart_widget_tile_gap"+ android:background="@drawable/chart_widget_tile_background"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_tile_padding">++ <TextView+ android:id="@+id/chart_tile_2_title"+ style="@style/ChartWidgetText.Title"+ android:layout_width="match_parent"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_tile_2_range"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="1dp" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_tile_2_value"+ style="@style/ChartWidgetText.Value.Tile"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_tile_2_delta"+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp" />+ </LinearLayout>++ <FrameLayout+ android:id="@+id/chart_tile_2_frame"+ android:layout_width="match_parent"+ android:layout_height="@dimen/chart_widget_tile_sparkline_height"+ android:layout_marginTop="6dp">+ <ImageView+ android:id="@+id/chart_tile_2_image_light"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_light_visibility" />+ <ImageView+ android:id="@+id/chart_tile_2_image_dark"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_dark_visibility" />+ </FrameLayout>+ </LinearLayout>+ </LinearLayout>++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_range"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1" />++ <TextView+ android:id="@+id/chart_updated"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp" />+ </LinearLayout>+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xmlnew file mode 100644index 000000000000..e176f8852327--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xml@@ -0,0 +1,105 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/chart_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_padding">++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <ImageView+ android:layout_width="12dp"+ android:layout_height="12dp"+ android:importantForAccessibility="no"+ android:src="@drawable/chart_widget_glyph" />++ <TextView+ android:id="@+id/chart_title"+ style="@style/ChartWidgetText.Title"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:layout_weight="1" />+ </LinearLayout>++ <LinearLayout+ android:id="@+id/chart_value_row"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_value"+ style="@style/ChartWidgetText.Value"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_delta"+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp" />++ <TextView+ android:id="@+id/chart_basis"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:layout_weight="1" />+ </LinearLayout>++ <TextView+ android:id="@+id/chart_legend"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:visibility="gone" />++ <FrameLayout+ android:id="@+id/chart_frame"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_marginTop="8dp"+ android:layout_weight="1">+ <ImageView+ android:id="@+id/chart_image_light"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_light_visibility" />+ <ImageView+ android:id="@+id/chart_image_dark"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_dark_visibility" />+ </FrameLayout>++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_range"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1" />++ <TextView+ android:id="@+id/chart_updated"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp" />+ </LinearLayout>+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_preview.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_preview.xmlnew file mode 100644index 000000000000..9cfb695717da--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_preview.xml@@ -0,0 +1,79 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_padding">++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <ImageView+ android:layout_width="12dp"+ android:layout_height="12dp"+ android:importantForAccessibility="no"+ android:src="@drawable/chart_widget_glyph" />++ <TextView+ style="@style/ChartWidgetText.Title"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="6dp"+ android:text="@string/chart_widget_preview_title" />+ </LinearLayout>++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ style="@style/ChartWidgetText.Value"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="@string/chart_widget_preview_value" />++ <TextView+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp"+ android:text="@string/chart_widget_preview_delta" />++ </LinearLayout>++ <ImageView+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_marginTop="8dp"+ android:layout_weight="1"+ android:importantForAccessibility="no"+ android:scaleType="fitXY"+ android:src="@drawable/chart_widget_preview_chart" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:orientation="horizontal">++ <TextView+ style="@style/ChartWidgetText.Footer"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:text="@string/chart_widget_preview_range" />++ <TextView+ style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="@string/chart_widget_preview_updated" />+ </LinearLayout>+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_small.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_small.xmlnew file mode 100644index 000000000000..ef9201101eb5--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_small.xml@@ -0,0 +1,67 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/chart_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:orientation="vertical"+ android:padding="@dimen/chart_widget_padding_small">++ <TextView+ android:id="@+id/chart_title"+ style="@style/ChartWidgetText.Title"+ android:layout_width="match_parent"+ android:layout_height="wrap_content" />++ <TextView+ android:id="@+id/chart_value"+ style="@style/ChartWidgetText.Value"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:gravity="center_vertical"+ android:orientation="horizontal">++ <TextView+ android:id="@+id/chart_delta"+ style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginEnd="6dp" />++ <TextView+ android:id="@+id/chart_range"+ style="@style/ChartWidgetText.Meta"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1" />+ </LinearLayout>++ <FrameLayout+ android:id="@+id/chart_frame"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_marginTop="6dp"+ android:layout_weight="1">+ <ImageView+ android:id="@+id/chart_image_light"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_light_visibility" />+ <ImageView+ android:id="@+id/chart_image_dark"+ style="@style/ChartWidgetChartImage"+ android:visibility="@integer/chart_widget_dark_visibility" />+ </FrameLayout>++ <TextView+ android:id="@+id/chart_updated"+ style="@style/ChartWidgetText.Footer"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp" />+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_state.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_state.xmlnew file mode 100644index 000000000000..b9ab025df6b8--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_state.xml@@ -0,0 +1,44 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/chart_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:gravity="center"+ android:orientation="vertical"+ android:padding="16dp">++ <TextView+ android:id="@+id/chart_state_title"+ style="@style/ChartWidgetText.State.Title"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone" />++ <TextView+ android:id="@+id/chart_state_message"+ style="@style/ChartWidgetText.State"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:text="@string/chart_widget_loading" />++ <TextView+ android:id="@+id/chart_state_detail"+ style="@style/ChartWidgetText.State"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="2dp"+ android:textColor="@color/chart_widget_tertiary"+ android:visibility="gone" />++ <ImageView+ android:id="@+id/chart_state_placeholder"+ android:layout_width="match_parent"+ android:layout_height="28dp"+ android:layout_marginTop="10dp"+ android:importantForAccessibility="no"+ android:scaleType="fitXY"+ android:src="@drawable/chart_widget_placeholder"+ android:visibility="gone" />+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values-night/colors.xml b/products/mobile/modules/chart-widget/android/src/main/res/values-night/colors.xmlnew file mode 100644index 000000000000..48f3d6347421--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values-night/colors.xml@@ -0,0 +1,23 @@+<resources>+ <!-- The app's dark tokens (src/ui/tokens.ts) and chart palette (src/ui/chart/palette.ts). -->+ <color name="chart_widget_surface">#23262E</color>+ <color name="chart_widget_background">#1D1F27</color>+ <color name="chart_widget_ink">#F4F4F2</color>+ <color name="chart_widget_secondary">#B4B5BA</color>+ <color name="chart_widget_tertiary">#8C8E95</color>+ <color name="chart_widget_hairline">#2E3139</color>+ <color name="chart_widget_bar_neutral">#5E6068</color>+ <color name="chart_widget_green">#3FB950</color>+ <color name="chart_widget_red">#F85149</color>+ <color name="chart_widget_orange">#FF6B35</color>+ <color name="chart_widget_previous">#6F727A</color>+ <color name="chart_widget_series_1">#6B8AFF</color>+ <color name="chart_widget_series_2">#7F26D9</color>+ <color name="chart_widget_series_3">#3E7A76</color>+ <color name="chart_widget_series_4">#BF0D6C</color>+ <color name="chart_widget_series_5">#F0474F</color>+ <color name="chart_widget_green_tint">#293FB950</color>+ <color name="chart_widget_red_tint">#29F85149</color>+ <color name="chart_widget_neutral_tint">#1FF4F4F2</color>+ <color name="chart_widget_on_orange">#FFFFFF</color>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values-night/integers.xml b/products/mobile/modules/chart-widget/android/src/main/res/values-night/integers.xmlnew file mode 100644index 000000000000..61f0a45dabe2--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values-night/integers.xml@@ -0,0 +1,4 @@+<resources>+ <integer name="chart_widget_light_visibility">2</integer>+ <integer name="chart_widget_dark_visibility">0</integer>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values-night/themes.xml b/products/mobile/modules/chart-widget/android/src/main/res/values-night/themes.xmlnew file mode 100644index 000000000000..eb1ac325524b--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values-night/themes.xml@@ -0,0 +1,9 @@+<resources>+ <style name="ChartWidgetConfigureTheme" parent="@android:style/Theme.Material.NoActionBar">+ <item name="android:windowBackground">@color/chart_widget_background</item>+ <item name="android:statusBarColor">@color/chart_widget_background</item>+ <item name="android:navigationBarColor">@color/chart_widget_background</item>+ <item name="android:windowLightStatusBar">false</item>+ <item name="android:colorAccent">@color/chart_widget_ink</item>+ </style>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/colors.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/colors.xmlnew file mode 100644index 000000000000..ec78490ec83e--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/colors.xml@@ -0,0 +1,23 @@+<resources>+ <!-- The app's light tokens (src/ui/tokens.ts) and chart palette (src/ui/chart/palette.ts). -->+ <color name="chart_widget_surface">#FFFFFF</color>+ <color name="chart_widget_background">#F6F6F3</color>+ <color name="chart_widget_ink">#1F1F1C</color>+ <color name="chart_widget_secondary">#6B6B65</color>+ <color name="chart_widget_tertiary">#8A8A84</color>+ <color name="chart_widget_hairline">#E4E4E0</color>+ <color name="chart_widget_bar_neutral">#D6D6D1</color>+ <color name="chart_widget_green">#1A7F37</color>+ <color name="chart_widget_red">#CF222E</color>+ <color name="chart_widget_orange">#F54E00</color>+ <color name="chart_widget_previous">#A3A39D</color>+ <color name="chart_widget_series_1">#1D4AFF</color>+ <color name="chart_widget_series_2">#621DA6</color>+ <color name="chart_widget_series_3">#42827E</color>+ <color name="chart_widget_series_4">#CE0E74</color>+ <color name="chart_widget_series_5">#F14F58</color>+ <color name="chart_widget_green_tint">#1F1A7F37</color>+ <color name="chart_widget_red_tint">#1FCF222E</color>+ <color name="chart_widget_neutral_tint">#141F1F1C</color>+ <color name="chart_widget_on_orange">#FFFFFF</color>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/dimens.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/dimens.xmlnew file mode 100644index 000000000000..d8432630507e--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/dimens.xml@@ -0,0 +1,7 @@+<resources>+ <dimen name="chart_widget_padding_small">12dp</dimen>+ <dimen name="chart_widget_padding">14dp</dimen>+ <dimen name="chart_widget_tile_padding">10dp</dimen>+ <dimen name="chart_widget_tile_gap">8dp</dimen>+ <dimen name="chart_widget_tile_sparkline_height">28dp</dimen>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/integers.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/integers.xmlnew file mode 100644index 000000000000..f7b0a1b1e15e--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/integers.xml@@ -0,0 +1,7 @@+<resources>+ <!-- The renderer draws each chart for both themes. The launcher resolves these with its own night mode, so the+ chart follows a theme change without a redraw. Values are indexes of the android:visibility enum: 0 visible,+ 2 gone (not the View.GONE flag value, which overflows the inflater's table). -->+ <integer name="chart_widget_light_visibility">0</integer>+ <integer name="chart_widget_dark_visibility">2</integer>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xmlnew file mode 100644index 000000000000..193ce68b2277--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xml@@ -0,0 +1,47 @@+<resources>+ <string name="chart_widget_label">Chart</string>+ <string name="chart_widget_description">A pinned insight from your Views tab, with its latest value.</string>++ <!-- Widget states. -->+ <string name="chart_widget_choose_pin">Choose a pin</string>+ <string name="chart_widget_choose_pin_hint">Touch and hold to pick a pin from your Views tab</string>+ <string name="chart_widget_signed_out_title">Sign in to see your pins</string>+ <string name="chart_widget_signed_out_message">Open PostHog to sign in</string>+ <string name="chart_widget_update_session">Open PostHog to update</string>+ <string name="chart_widget_no_longer_pinned">%1$s is no longer pinned</string>+ <string name="chart_widget_other_project_title">In another project</string>+ <string name="chart_widget_other_project_message">Switch to %1$s in PostHog</string>+ <string name="chart_widget_not_found">%1$s was unpinned or deleted. Touch and hold to pick another.</string>+ <string name="chart_widget_loading">Loading…</string>+ <string name="chart_widget_refresh_failed">Couldn\'t refresh</string>+ <string name="chart_widget_refresh_retry">Trying again soon</string>+ <string name="chart_widget_bad_data">Can\'t show this insight here</string>+ <string name="chart_widget_no_result">Open it in PostHog to load this insight</string>+ <string name="chart_widget_not_found_short">Not found</string>+ <string name="chart_widget_this_pin">This pin</string>+ <string name="chart_widget_ineligible">Not a chart over time</string>++ <!-- Freshness, from when the server computed the numbers. -->+ <string name="chart_widget_updated_just_now">Updated just now</string>+ <string name="chart_widget_updated_minutes">Updated %1$d min ago</string>+ <string name="chart_widget_updated_hours">Updated %1$d h ago</string>+ <string name="chart_widget_updated_one_day">Updated 1 day ago</string>+ <string name="chart_widget_updated_days">Updated %1$d days ago</string>++ <!-- Configure screen. -->+ <string name="chart_widget_configure_subtitle">This widget shows one pin. Touch and hold the widget to change it later.</string>+ <string name="chart_widget_configure_ineligible">Can\'t show on the widget</string>+ <string name="chart_widget_configure_extras">Also show (large widget)</string>+ <string name="chart_widget_configure_done">Done</string>+ <string name="chart_widget_configure_close">Close</string>+ <string name="chart_widget_configure_signed_out">Sign in to PostHog to see your pins</string>+ <string name="chart_widget_configure_empty">Pin a dashboard or insight in Views first</string>+ <string name="chart_widget_configure_open_app">Open PostHog</string>++ <!-- Sample data for the widget picker's preview. -->+ <string name="chart_widget_preview_title" translatable="false">Signups</string>+ <string name="chart_widget_preview_value" translatable="false">1,284</string>+ <string name="chart_widget_preview_delta" translatable="false">▲ 12%</string>+ <string name="chart_widget_preview_range" translatable="false">Last 14 days</string>+ <string name="chart_widget_preview_updated" translatable="false">Updated 12 min ago</string>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xmlnew file mode 100644index 000000000000..605d5d6dbf49--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xml@@ -0,0 +1,57 @@+<resources>+ <style name="ChartWidgetText">+ <item name="android:includeFontPadding">false</item>+ <item name="android:maxLines">1</item>+ <item name="android:ellipsize">end</item>+ </style>+ <style name="ChartWidgetText.Title">+ <item name="android:textSize">12sp</item>+ <item name="android:fontFamily">sans-serif-medium</item>+ <item name="android:textColor">@color/chart_widget_ink</item>+ </style>+ <style name="ChartWidgetText.Value">+ <item name="android:textSize">26sp</item>+ <item name="android:textStyle">bold</item>+ <item name="android:fontFeatureSettings">tnum</item>+ <item name="android:textColor">@color/chart_widget_ink</item>+ </style>+ <style name="ChartWidgetText.Value.Tile">+ <item name="android:textSize">20sp</item>+ </style>+ <style name="ChartWidgetText.Meta">+ <item name="android:textSize">10.5sp</item>+ <item name="android:textColor">@color/chart_widget_secondary</item>+ </style>+ <style name="ChartWidgetText.Footer">+ <item name="android:textSize">10.5sp</item>+ <item name="android:textColor">@color/chart_widget_tertiary</item>+ </style>+ <style name="ChartWidgetText.Pill">+ <item name="android:textSize">10.5sp</item>+ <item name="android:fontFamily">sans-serif-medium</item>+ <item name="android:fontFeatureSettings">tnum</item>+ <item name="android:textColor">@color/chart_widget_green</item>+ <item name="android:background">@drawable/chart_widget_pill_up</item>+ <item name="android:paddingStart">5dp</item>+ <item name="android:paddingEnd">5dp</item>+ <item name="android:paddingTop">1.5dp</item>+ <item name="android:paddingBottom">1.5dp</item>+ </style>+ <style name="ChartWidgetText.State">+ <item name="android:textSize">12sp</item>+ <item name="android:textColor">@color/chart_widget_secondary</item>+ <item name="android:gravity">center</item>+ <item name="android:maxLines">4</item>+ </style>+ <style name="ChartWidgetText.State.Title">+ <item name="android:fontFamily">sans-serif-medium</item>+ <item name="android:textColor">@color/chart_widget_ink</item>+ <item name="android:maxLines">2</item>+ </style>+ <style name="ChartWidgetChartImage">+ <item name="android:layout_width">match_parent</item>+ <item name="android:layout_height">match_parent</item>+ <item name="android:scaleType">fitXY</item>+ <item name="android:importantForAccessibility">no</item>+ </style>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/themes.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/themes.xmlnew file mode 100644index 000000000000..56c51ec37e7b--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/themes.xml@@ -0,0 +1,9 @@+<resources>+ <style name="ChartWidgetConfigureTheme" parent="@android:style/Theme.Material.Light.NoActionBar">+ <item name="android:windowBackground">@color/chart_widget_background</item>+ <item name="android:statusBarColor">@color/chart_widget_background</item>+ <item name="android:navigationBarColor">@color/chart_widget_background</item>+ <item name="android:windowLightStatusBar">true</item>+ <item name="android:colorAccent">@color/chart_widget_ink</item>+ </style>+</resources>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_backup_rules.xml b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_backup_rules.xmlnew file mode 100644index 000000000000..ebbf96f0c9a6--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_backup_rules.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<full-backup-content>+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="SecureStore" />+ <exclude domain="sharedpref" path="chart_widget.xml" />+ <exclude domain="sharedpref" path="chart_widget_secure.xml" />+</full-backup-content>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_data_extraction_rules.xml b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_data_extraction_rules.xmlnew file mode 100644index 000000000000..153b70cee58b--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_data_extraction_rules.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<data-extraction-rules>+ <cloud-backup>+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="SecureStore" />+ <exclude domain="sharedpref" path="chart_widget.xml" />+ <exclude domain="sharedpref" path="chart_widget_secure.xml" />+ </cloud-backup>+ <device-transfer>+ <include domain="sharedpref" path="." />+ <exclude domain="sharedpref" path="SecureStore" />+ <exclude domain="sharedpref" path="chart_widget.xml" />+ <exclude domain="sharedpref" path="chart_widget_secure.xml" />+ </device-transfer>+</data-extraction-rules>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_info.xml b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_info.xmlnew file mode 100644index 000000000000..aff1e9f3ab5f--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/xml/chart_widget_info.xml@@ -0,0 +1,15 @@+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"+ android:minWidth="110dp"+ android:minHeight="110dp"+ android:minResizeWidth="110dp"+ android:minResizeHeight="110dp"+ android:targetCellWidth="2"+ android:targetCellHeight="2"+ android:resizeMode="horizontal|vertical"+ android:widgetCategory="home_screen"+ android:updatePeriodMillis="1800000"+ android:initialLayout="@layout/chart_widget_state"+ android:previewLayout="@layout/chart_widget_preview"+ android:configure="com.posthog.code.mobile.chart.ChartWidgetConfigureActivity"+ android:widgetFeatures="reconfigurable"+ android:description="@string/chart_widget_description" />diff --git a/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.kt b/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.ktnew file mode 100644index 000000000000..72830fc81d69--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.kt@@ -0,0 +1,345 @@+package com.posthog.code.mobile.chart++import android.app.Activity+import android.appwidget.AppWidgetManager+import android.appwidget.AppWidgetProviderInfo+import android.content.ComponentName+import android.content.Context+import android.content.BroadcastReceiver+import android.content.ContextWrapper+import android.content.Intent+import android.content.SharedPreferences+import android.os.Bundle+import android.view.View+import android.view.ViewGroup+import android.widget.Button+import android.widget.TextView+import java.util.concurrent.TimeUnit+import java.util.concurrent.CountDownLatch+import org.json.JSONObject+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowBroadcastPendingResult+import org.robolectric.util.ReflectionHelpers+import org.robolectric.util.ReflectionHelpers.ClassParameter++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class ChartWidgetRefreshTest {+ private lateinit var context: Context++ private fun credentials(token: String = "test-token"): String = JSONObject()+ .put("host", "https://example.com").put("projectId", 1).put("projectName", "Example")+ .put("accessToken", token).put("userUuid", "example-user").toString()++ private fun snapshot(pin: String = "first"): ChartSnapshot = ChartSnapshot(+ pin, 1000L, null, null, "day", "42", null, null, null, false, emptyList(), "line",+ )++ @Before+ fun setUp() {+ context = RuntimeEnvironment.getApplication()+ val secure = context.getSharedPreferences("test-credentials", Context.MODE_PRIVATE)+ secure.edit().clear().commit()+ ReflectionHelpers.setStaticField(ChartStore::class.java, "secure", secure)+ context.getSharedPreferences("chart_widget", Context.MODE_PRIVATE).edit().clear().commit()+ ChartStore.setCredentials(context, credentials())+ ChartStore.setCatalogJson(context, """{"host":"https://example.com","projectId":1,"pins":[+ {"id":"first","insightId":1,"eligible":true},+ {"id":"second","insightId":2,"eligible":true}+ ]}""")+ val provider = ComponentName(context, ChartWidgetProvider::class.java)+ shadowOf(AppWidgetManager.getInstance(context)).addBoundWidget(1, AppWidgetProviderInfo().apply {+ this.provider = provider+ })+ ChartStore.setWidgetConfig(context, 1, "first", listOf("second"))+ }++ private fun doneButton(activity: Activity): Button {+ fun descendants(view: View): Sequence<View> = sequence {+ yield(view)+ if (view is ViewGroup) {+ for (index in 0 until view.childCount) yieldAll(descendants(view.getChildAt(index)))+ }+ }+ return descendants(activity.findViewById(android.R.id.content)).filterIsInstance<Button>()+ .single { it.text == context.getString(R.string.chart_widget_configure_done) }+ }++ @Test+ fun configurationRejectsMissingUnknownAndOtherProvidersWidgetIds() {+ shadowOf(AppWidgetManager.getInstance(context)).addBoundWidget(2, AppWidgetProviderInfo().apply {+ provider = ComponentName("com.example.other", "com.example.other.WidgetProvider")+ })+ for (id in listOf(AppWidgetManager.INVALID_APPWIDGET_ID, 999, 2)) {+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)+ val controller = Robolectric.buildActivity(ChartWidgetConfigureActivity::class.java, intent).create()+ val activity = controller.get()+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ assertNull(ChartStore.widgetConfig(context, id))+ controller.destroy()+ }+ }++ @Test+ fun configurationReturnsOnlyTheConfirmedWidgetId() {+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 1)+ val controller = Robolectric.buildActivity(ChartWidgetConfigureActivity::class.java, intent).create()+ val activity = controller.get()+ assertFalse(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ doneButton(activity).performClick()+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode)+ val result = shadowOf(activity).resultIntent+ assertEquals(setOf(AppWidgetManager.EXTRA_APPWIDGET_ID), result.extras!!.keySet())+ assertEquals(1, result.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1))+ controller.destroy()+ }++ @Test+ fun configurationRechecksWidgetOwnershipBeforeSaving() {+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 1)+ val controller = Robolectric.buildActivity(ChartWidgetConfigureActivity::class.java, intent).create()+ val activity = controller.get()+ ChartStore.removeWidget(context, 1)+ shadowOf(AppWidgetManager.getInstance(context)).addBoundWidget(1, AppWidgetProviderInfo().apply {+ provider = ComponentName("com.example.other", "com.example.other.WidgetProvider")+ })+ doneButton(activity).performClick()+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ assertNull(ChartStore.widgetConfig(context, 1))+ controller.destroy()+ }++ @Test+ fun discardsResultsFromAnEndedOrReplacedSession() {+ for (change in listOf<() -> Unit>(+ { ChartStore.clearCredentials(context) },+ { ChartStore.setCredentials(context, credentials("new-token")) },+ { ChartStore.clearCredentials(context); ChartStore.setCredentials(context, credentials()) },+ )) {+ ChartStore.setCredentials(context, credentials())+ ChartWidgetRefresh.fetchShownPins(context, { false }) { _, _, _ ->+ change()+ ChartFetcher.Outcome.Success(snapshot())+ }+ assertNull(ChartStore.snapshot(context, "first"))+ }+ }++ @Test+ fun discardsCanceledFetchAndErrorsFromAReplacedToken() {+ var stopped = false+ ChartWidgetRefresh.fetchShownPins(context, { stopped }) { _, _, _ ->+ stopped = true+ ChartFetcher.Outcome.Success(snapshot())+ }+ assertNull(ChartStore.snapshot(context, "first"))+ ChartWidgetRefresh.fetchShownPins(context, { false }) { _, _, _ ->+ ChartStore.setCredentials(context, credentials("new-token"))+ ChartFetcher.Outcome.Failure(ErrorKind.AUTH)+ }+ assertNull(ChartStore.snapshotError(context, "first"))+ assertNull(ChartStore.snapshotError(context, "second"))+ }++ @Test+ fun rejectsAnotherHostsCatalogAndAnUpdatedCatalog() {+ val catalog = ChartStore.catalog(context)!!+ ChartStore.setCatalogJson(context, """{"host":"https://other.example.com","projectId":1,"pins":[{"id":"first","eligible":true}]}""")+ var calls = 0+ ChartWidgetRefresh.fetchShownPins(context, { false }) { _, _, _ ->+ calls+++ ChartFetcher.Outcome.Success(snapshot())+ }+ assertEquals(0, calls)+ ChartStore.setCatalogJson(context, """{"host":"https://example.com","projectId":1,"pins":[]}""")+ assertFalse(ChartStore.commitFetch(context, ChartStore.session(context)!!, catalog, listOf("first"),+ ChartFetcher.Outcome.Success(snapshot()), { false }))+ assertNull(ChartStore.snapshot(context, "first"))+ }++ @Test+ fun catalogChangesDiscardOnlySnapshotsForChangedTargets() {+ val original = JSONObject().put("host", "https://example.com").put("projectId", 1)+ .put("pins", org.json.JSONArray().put(JSONObject()+ .put("id", "first").put("kind", "dashboard").put("dashboardId", 10).put("insightId", 1)))+ val replacements = listOf(+ original.toString(),+ JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("name", "Renamed") }.toString(),+ JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("insightId", 2) }.toString(),+ JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("dashboardId", 11) }.toString(),+ JSONObject(original.toString()).put("projectId", 2).toString(),+ JSONObject(original.toString()).put("host", "https://other.example.com").toString(),+ JSONObject(original.toString()).put("pins", org.json.JSONArray()).toString(),+ null,+ )+ for ((index, replacement) in replacements.withIndex()) {+ ChartStore.setCatalogJson(context, original.toString())+ ChartStore.setSnapshot(context, snapshot())+ ChartStore.setSnapshotError(context, "first", SnapshotError(2000L, ErrorKind.NETWORK))+ ChartStore.setCatalogJson(context, replacement)+ assertEquals("snapshot for case $index", index < 2, ChartStore.snapshot(context, "first") != null)+ assertEquals("error for case $index", index < 2, ChartStore.snapshotError(context, "first") != null)+ }+ }++ @Test+ fun credentialWritesReportUnavailableStorageAndFailedCommits() {+ for (unavailable in listOf(true, false)) {+ val backing = context.getSharedPreferences("test-credentials", Context.MODE_PRIVATE)+ val failing = object : SharedPreferences by backing {+ override fun edit(): SharedPreferences.Editor = object : SharedPreferences.Editor by backing.edit() {+ override fun putString(key: String?, value: String?): SharedPreferences.Editor = this+ override fun commit(): Boolean = false+ }+ }+ ReflectionHelpers.setStaticField(ChartStore::class.java, "secure", if (unavailable) null else failing)+ val wrapper = object : ContextWrapper(context) {+ override fun getApplicationContext(): Context = this+ override fun getSharedPreferences(name: String, mode: Int): SharedPreferences {+ if (name == "chart_widget_secure") throw IllegalStateException("Storage unavailable")+ return super.getSharedPreferences(name, mode)+ }+ }+ assertThrows(IllegalStateException::class.java) { ChartStore.setCredentials(wrapper, credentials("replacement")) }+ }+ }++ @Test+ fun resizeKeepsBroadcastPendingUntilTheWidgetIsUpdated() {+ val started = CountDownLatch(1)+ val release = CountDownLatch(1)+ val wrapper = object : ContextWrapper(context) {+ override fun getApplicationContext(): Context = this+ override fun getSharedPreferences(name: String, mode: Int): SharedPreferences {+ if (name == "chart_widget") {+ started.countDown()+ check(release.await(10, TimeUnit.SECONDS))+ }+ return super.getSharedPreferences(name, mode)+ }+ }+ val receiver = ChartWidgetProvider()+ val pending = ReflectionHelpers.callStaticMethod<BroadcastReceiver.PendingResult>(+ ShadowBroadcastPendingResult::class.java, "create",+ ClassParameter.from(Int::class.javaPrimitiveType, 0),+ ClassParameter.from(String::class.java, null),+ ClassParameter.from(Bundle::class.java, null),+ ClassParameter.from(Boolean::class.javaPrimitiveType, false),+ )+ ReflectionHelpers.setField(receiver, "mPendingResult", pending)+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_OPTIONS_CHANGED)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 1)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, Bundle())+ try {+ receiver.onReceive(wrapper, intent)+ assertTrue(started.await(10, TimeUnit.SECONDS))+ assertTrue(shadowOf(receiver).wentAsync())+ assertFalse(shadowOf(pending).future.isDone)+ } finally {+ release.countDown()+ }+ shadowOf(pending).future.get(10, TimeUnit.SECONDS)+ assertNotNull(shadowOf(AppWidgetManager.getInstance(context)).getViewFor(1))+ }++ @Test+ fun rateLimitStopsThePassAndSurvivesLaterRefreshes() {+ var calls = 0+ val fetch: (Context, Credentials, CatalogPin) -> ChartFetcher.Outcome = { _, _, _ ->+ calls+++ ChartFetcher.Outcome.Failure(ErrorKind.RATE_LIMITED, 120_000L)+ }+ val before = System.currentTimeMillis()+ ChartWidgetRefresh.fetchShownPins(context, { false }, fetch)+ ChartWidgetRefresh.fetchShownPins(context, { false }, fetch)+ assertEquals(1, calls)+ assertTrue(ChartStore.retryAt(context) >= before + 120_000L)+ assertEquals(ErrorKind.RATE_LIMITED, ChartStore.snapshotError(context, "second")?.kind)+ context.getSharedPreferences("chart_widget", Context.MODE_PRIVATE).edit().putLong("chart.retryAt", 0L).commit()+ ChartWidgetRefresh.fetchShownPins(context, { false }, fetch)+ assertEquals(2, calls)+ }++ @Test+ fun honorsRetryAfterWithAMinimumCooldown() {+ val now = 1_000_000L+ assertEquals(120_000L, ChartFetcher.retryAfterMs("120", now))+ assertEquals(120_000L, ChartFetcher.retryAfterMs("Thu, 01 Jan 1970 00:18:40 GMT", now))+ for (value in listOf(null, "invalid", "0", "-5")) {+ assertEquals(60_000L, ChartFetcher.retryAfterMs(value, now))+ }+ }++ @Test+ fun rendersOutsideTheCallingThread() {+ var renderingThread: Thread? = null+ val wrapper = object : ContextWrapper(context) {+ override fun getApplicationContext(): Context = this+ override fun getSystemService(name: String): Any? {+ if (name == Context.APPWIDGET_SERVICE) renderingThread = Thread.currentThread()+ return super.getSystemService(name)+ }+ }+ ChartRenderer.renderAll(wrapper).get(10, TimeUnit.SECONDS)+ assertNotNull(renderingThread)+ assertNotEquals(Thread.currentThread(), renderingThread)+ }++ @Test+ fun largeWidgetShowsTheAgeOfItsOldestVisibleTile() {+ val now = System.currentTimeMillis()+ val cached = snapshot("second").copy(fetchedAt = now - 3 * 60 * 60_000L)+ ChartStore.setSnapshot(context, snapshot().copy(fetchedAt = now))+ ChartStore.setSnapshot(context, cached)+ ChartStore.setSnapshotError(context, "second", SnapshotError(now, ErrorKind.NETWORK))+ val manager = AppWidgetManager.getInstance(context)+ manager.updateAppWidgetOptions(1, Bundle().apply {+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 320)+ putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 400)+ })+ fun rendered(): View {+ ChartRenderer.renderOne(context, manager, 1).get(10, TimeUnit.SECONDS)+ return shadowOf(manager).getViewFor(1)+ }+ val view = rendered()+ assertEquals(context.getString(R.string.chart_widget_updated_hours, 3),+ view.findViewById<TextView>(R.id.chart_updated).text.toString())+ assertEquals(View.VISIBLE, view.findViewById<View>(R.id.chart_tile_1_value).visibility)+ for (kind in listOf(ErrorKind.AUTH, ErrorKind.NOT_FOUND)) {+ ChartStore.setSnapshotError(context, "second", SnapshotError(now, kind))+ val hidden = rendered()+ assertEquals(View.GONE, hidden.findViewById<View>(R.id.chart_tile_1_value).visibility)+ assertEquals(View.GONE, hidden.findViewById<View>(R.id.chart_tile_1_frame).visibility)+ assertEquals(context.getString(R.string.chart_widget_updated_just_now),+ hidden.findViewById<TextView>(R.id.chart_updated).text.toString())+ }+ }++ @Test+ fun onlyNewerAccessErrorsHideCachedTiles() {+ val cached = snapshot()+ for (kind in listOf(ErrorKind.AUTH, ErrorKind.NOT_FOUND)) {+ assertNull(cached.visibleAfter(SnapshotError(1000L, kind)))+ assertEquals(cached, cached.visibleAfter(SnapshotError(999L, kind)))+ }+ for (kind in listOf(ErrorKind.NETWORK, ErrorKind.RATE_LIMITED, ErrorKind.NO_RESULT)) {+ assertEquals(cached, cached.visibleAfter(SnapshotError(2000L, kind)))+ }+ assertEquals(1000L, cached.updatedAt())+ assertEquals(0L, cached.copy(lastRefreshAt = "1970-01-01T00:00:00Z").updatedAt())+ }+}diff --git a/products/mobile/modules/chart-widget/expo-module.config.json b/products/mobile/modules/chart-widget/expo-module.config.jsonindex eb94d6734085..4be4287db4e4 100644--- a/products/mobile/modules/chart-widget/expo-module.config.json+++ b/products/mobile/modules/chart-widget/expo-module.config.json@@ -1,6 +1,9 @@{- "platforms": ["apple"],+ "platforms": ["apple", "android"],"apple": {"modules": ["ChartWidgetModule"]+ },+ "android": {+ "modules": ["com.posthog.code.mobile.chart.ChartWidgetModule"]}}diff --git a/products/mobile/plugins/withAndroidChartWidgetBackup.js b/products/mobile/plugins/withAndroidChartWidgetBackup.jsnew file mode 100644index 000000000000..59f4a03ebb11--- /dev/null+++ b/products/mobile/plugins/withAndroidChartWidgetBackup.js@@ -0,0 +1,10 @@+const { AndroidConfig, withAndroidManifest } = require('expo/config-plugins')++module.exports = function withAndroidChartWidgetBackup(config) {+ return withAndroidManifest(config, (cfg) => {+ const application = AndroidConfig.Manifest.getMainApplicationOrThrow(cfg.modResults)+ application.$['android:fullBackupContent'] = '@xml/chart_widget_backup_rules'+ application.$['android:dataExtractionRules'] = '@xml/chart_widget_data_extraction_rules'+ return cfg+ })+}diff --git a/products/mobile/plugins/withAndroidChartWidgetBackup.test.js b/products/mobile/plugins/withAndroidChartWidgetBackup.test.jsnew file mode 100644index 000000000000..a7fff0a983c7--- /dev/null+++ b/products/mobile/plugins/withAndroidChartWidgetBackup.test.js@@ -0,0 +1,59 @@+const assert = require('node:assert/strict')+const { mkdtemp, mkdir, readFile, rm, writeFile } = require('node:fs/promises')+const { tmpdir } = require('node:os')+const { dirname, join, resolve } = require('node:path')++const { compileModsAsync, XML } = require('expo/config-plugins')+const withSecureStore = require('expo-secure-store/app.plugin').default++const appConfig = require('../app.config').default+const withAndroidChartWidgetBackup = require('./withAndroidChartWidgetBackup')++describe('Android chart widget backups', () => {+ test('excludes widget data from each backup transport while preserving SecureStore exclusions', async () => {+ const projectRoot = await mkdtemp(join(tmpdir(), 'posthog-widget-backup-'))+ try {+ const exp = appConfig({ config: { name: 'test', slug: 'test' }, projectRoot: resolve('.') })+ assert.ok(exp.plugins.includes('./plugins/withAndroidChartWidgetBackup'))+ const manifestPath = join(projectRoot, 'android/app/src/main/AndroidManifest.xml')+ await mkdir(dirname(manifestPath), { recursive: true })+ await writeFile(+ manifestPath,+ '<manifest xmlns:android="http://schemas.android.com/apk/res/android"><application android:name=".MainApplication" /></manifest>'+ )+ await compileModsAsync(+ withAndroidChartWidgetBackup(+ withSecureStore({ name: 'test', slug: 'test' }, { configureAndroidBackup: false })+ ),+ { projectRoot, platforms: ['android'] }+ )+ const manifest = await XML.readXMLAsync({ path: manifestPath })+ const application = manifest.manifest.application[0].$+ const readRules = async (attribute) => {+ const resource = application[attribute]+ assert.ok(resource.startsWith('@xml/chart_widget_'))+ return XML.parseXMLAsync(+ await readFile(+ join('modules/chart-widget/android/src/main/res/xml', `${resource.slice(5)}.xml`),+ 'utf8'+ )+ )+ }+ const legacy = await readRules('android:fullBackupContent')+ const modern = await readRules('android:dataExtractionRules')+ for (const policy of [+ legacy['full-backup-content'],+ modern['data-extraction-rules']['cloud-backup'][0],+ modern['data-extraction-rules']['device-transfer'][0],+ ]) {+ const excluded = policy.exclude.map((entry) => entry.$)+ for (const path of ['SecureStore', 'chart_widget.xml', 'chart_widget_secure.xml']) {+ assert.ok(excluded.some((entry) => entry.domain === 'sharedpref' && entry.path === path))+ }+ assert.ok(policy.include.some((entry) => entry.$.domain === 'sharedpref' && entry.$.path === '.'))+ }+ } finally {+ await rm(projectRoot, { recursive: true, force: true })+ }+ })+})