: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 iOS (#129759)
Chris Volzer284f451c70b2
diff --git a/products/mobile/modules/chart-widget/README.md b/products/mobile/modules/chart-widget/README.mdnew file mode 100644index 000000000000..2bf790ab71b2--- /dev/null+++ b/products/mobile/modules/chart-widget/README.md@@ -0,0 +1,395 @@+# Chart widget++A home-screen widget for iOS and Android that shows a pinned insight from the Views tab and reads PostHog by itself.+See the sections below for the store contract, the fetch rules and the identifiers.++The widget shows one pin as a number and sparkline (small), one pin as a chart with its value and change (medium), or one chart plus up to two number tiles (large).+The person picks the pin in the OS: the Edit widget sheet on iOS, the configure screen on Android.+The app itself shows nothing about widgets.++## How it works++The app and the widget share a small store.+The app writes the session copy and the pin catalog; the widget writes one snapshot per pin.+The widget never runs the app's JavaScript and never refreshes the OAuth token.++```text+app: src/features/widgets/chartWidgetSync.ts+ token, account or project change ──> setCredentials ──> Keychain item (iOS), EncryptedSharedPreferences (Android)+ complete pin list read, pin display change ──> setCatalog ──> chart.catalog+ session end, demo mode ──> clearCatalog + clearCredentials (also every chart.snapshot.* key)++widget: targets/HedgehogWidget/Chart*.swift (iOS), modules/chart-widget/android/ (Android)+ picker and render ──> chart.catalog+ timer ──> credentials ──> GET insights/{id}/?refresh=force_cache ──> chart.snapshot.<pinId> or chart.snapshotError.<pinId>+```++`useChartWidgetSync()` runs in `app/_layout.tsx` next to the hedgehog sync and calls `startChartWidgetSync()`.+That function subscribes to the stores below, so auth and Views do not import the widget code:++| Trigger | What the app writes |+| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------- |+| Launch, after the session restores | Credentials (`launch`) |+| Sign in, demo mode ends | Credentials (`sign_in`) |+| Token refresh (`onSessionTokensChanged` in `src/auth/tokens.ts`) | Credentials (`refresh`) |+| Project switch, project rename | Credentials (`project_switch`) |+| A success write of the signed-in project's pin list in the query cache: a read, pin, unpin | Catalog, when the list is complete |+| A change of the project's pin prefs (`usePinPrefs`): mode, tile, order | Catalog, from the cached pin list |+| A project with no catalog and no cached pin list: sign in, project switch, launch | Reads the pin list once, then the catalog |+| Sign out, expired session (`addSessionEndTask`), signed-out launch, demo mode starts | Clears the catalog, the credentials and every cached chart |++Each write makes the OS reload every placed widget, so the app keeps the last JSON it wrote in memory and skips an identical write.+A clear resets that memory, so the next sign in writes again even with the same token.+Writes happen only while the auth store and the stored session name the same host and user, so a sign in never pairs one account's token with another account's project.+When the signed-in project has no catalog and no cached pin list, the sync reads the pin list itself, with the query key, fetcher (`readShortcuts` in `src/features/views/listReads.ts`) and lane that `usePins` uses.+It does that once per project per session, and only when the session has the Views scopes; a failure leaves the catalog for the next Views read.+Until the new project's catalog lands after a project switch, the widget shows "In another project".++The widget never refreshes the OAuth token.+On each return to the foreground, the app refreshes an OAuth access token with less than 24 hours left (`FOREGROUND_REFRESH_MARGIN_MS` in `src/auth/authStore.ts`), then writes the new copy, so the widget's token stays valid between app opens.++The catalog takes each pin's insight from what the Views list already read: the pin metadata cache (`viewsKeys.pinMetadata`), else the pin's Number or Chart snapshot.+For up to 30 pins without either, the sync reads `GET insights/?short_id=&basic=true&refresh=force_cache` through the list-read lane (`listRead('insights')`), one at a time, and stores the answer in the same metadata cache.+A 429, a 503, an empty budget bucket or no connection stops the reads; those pins say "Open it in Views first" until the next sync.+The sync never forces a compute.++Analytics: `mobile_widget_credentials_synced` (`reason`: `launch`, `sign_in`, `refresh` or `project_switch`) and `mobile_widget_catalog_synced` (`pin_count`, `eligible_count`) on each real write.+A widget tap opens `/views/insight/<short_id>?from=widget&family=<family>` or `/views/dashboard/<id>?from=widget&family=<family>`, which sends `mobile_view_opened` with `from: widget` and `mobile_widget_opened` (`kind`, `family`).++## Store contract++| Data | iOS | Android | Writer |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------ |+| Credentials | Keychain generic password: service `com.posthog.code.mobile.chart-widget`, account `credentials`, access group `group.<app bundle id>`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`; data is the UTF-8 JSON | `EncryptedSharedPreferences` file `chart_widget_secure` (MasterKey AES256_GCM), key `credentials`, written with `commit()` | App |+| Catalog | `UserDefaults(suiteName: "group.<app bundle id>")`, key `chart.catalog` | `SharedPreferences` file `chart_widget`, key `chart.catalog` | App |+| Snapshot of one pin | same suite, key `chart.snapshot.<pinId>` | `chart_widget`, key `chart.snapshot.<pinId>` | Widget |+| Last error of one pin | same suite, key `chart.snapshotError.<pinId>` | `chart_widget`, key `chart.snapshotError.<pinId>` | Widget |+| Project of one pin | same suite, key `chart.pinProject.<pinId>` = `{ "projectId": number, "projectName": string }` | kept per widget in `chart.widget.<appWidgetId>` as `projectId`, `projectName` and `pinName`, written at configure time | Widget |+| Widget configuration | the widget's configuration intent, kept by WidgetKit | `chart_widget`, key `chart.widget.<appWidgetId>` = `{ "pinId": string, "extraPinIds": string[] }` | Widget |++The suite is the hedgehog widget's App Group.+An App Group id is also a keychain access group of every target in the group, so the extension reads the credentials without a keychain-sharing entitlement.+The credentials stay out of `UserDefaults` because the suite is a plain file in the group container.++### Credentials JSON++```json+{+ "version": 1,+ "host": "https://us.posthog.com",+ "projectId": 2,+ "projectName": "PostHog App",+ "accessToken": "phx_...",+ "expiresAt": 1762400000000,+ "userUuid": "..."+}+```++`host` has no trailing slash.+`expiresAt` is epoch ms, or null for a personal API key, which does not expire.+The widget treats `now > expiresAt - 60000` as expired and sends no request.++### Catalog JSON++Replaced whole on each write.+Pins are in Views order, at most 30.++```json+{+ "version": 1,+ "host": "https://us.posthog.com",+ "projectId": 2,+ "projectName": "PostHog App",+ "writtenAt": 1762400000000,+ "pins": [+ {+ "id": "<shortcut id>",+ "kind": "insight",+ "name": "Signups",+ "subtitle": "Insight",+ "insightId": 123,+ "shortId": "abc123",+ "dashboardId": null,+ "eligible": true,+ "number": true,+ "chart": true,+ "reason": null+ },+ {+ "id": "<shortcut id>",+ "kind": "dashboard",+ "name": "Product KPIs",+ "subtitle": "Product KPIs · Daily active users",+ "insightId": 456,+ "shortId": "def456",+ "dashboardId": 12,+ "eligible": true,+ "number": true,+ "chart": true,+ "reason": null+ },+ {+ "id": "<shortcut id>",+ "kind": "insight",+ "name": "Checkout funnel",+ "subtitle": "Insight",+ "insightId": 789,+ "shortId": "ghi789",+ "dashboardId": null,+ "eligible": false,+ "number": false,+ "chart": false,+ "reason": "Not a chart over time"+ }+ ]+}+```++| Field | Meaning |+| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |+| `id` | The pin's `shortcutId` (`PinView.shortcutId`). The widget configuration stores it. |+| `subtitle` | "Insight" for an insight pin. For a dashboard pin, "<dashboard name> · <tile name>", or "Dashboard" before a tile is chosen. |+| `insightId` | Null when the app has not read the insight. The widget then reads by `shortId`. |+| `shortId` | The insight's `short_id`: the pin's `ref`, or the chosen tile's insight. Null for a dashboard pin without a tile. |+| `dashboardId` | The dashboard's numeric id, sent as `from_dashboard`. Null for an insight pin. |+| `number` | `capabilitiesOf(query).number` (`src/model/adapters/insightSnapshot.ts`): one series or a big number, without a breakdown. |+| `chart` | `capabilitiesOf(query).chart`: a line or bar trends chart over time. |+| `eligible` | A `TrendsQuery` with `number` or `chart`. iOS leaves other pins out of the picker; Android shows them grayed with `reason`. |+| `reason` | Null when eligible, else one of the reasons below. |++| Reason | When |+| --------------------------------- | --------------------------------------------------------------------------------------------------------- |+| "Choose a tile in Views first" | A dashboard pin without a tile chosen on this phone (`PinDisplay.insightId`). |+| "Open it in Views first" | The app has not read the insight yet. |+| "Couldn't find this insight" | The server no longer returns the insight, or it is deleted. |+| "Not supported on the widget yet" | A SQL insight (`HogQLQuery`). |+| "Not a chart over time" | Any other kind, or a trends insight that is neither a number nor a line or bar chart (`tileLimitReason`). |++### Snapshot JSON++Written by the widget after a good read, the same shape on both platforms.+The widget renders from it when a later read fails.+The age it shows is from `lastRefreshAt` (when the server computed the numbers), else `fetchedAt`; with several pins on screen, the oldest.++```json+{+ "version": 1,+ "pinId": "...",+ "fetchedAt": 1762400000000,+ "lastRefreshAt": "2026-11-04T17:00:00Z",+ "rangeLabel": "Last 14 days",+ "intervalLabel": "day",+ "valueText": "1,284",+ "deltaPercent": 12.3,+ "deltaText": "12%",+ "deltaBasis": "vs. previous 14 days",+ "series": [{ "label": "Signups", "points": [{ "at": "2026-10-22", "value": 72 }], "previous": false }],+ "chartKind": "line"+}+```++The error record is `{ "at": <epoch ms>, "kind": "network" | "auth" | "not_found" | "rate_limited" | "bad_data" | "no_result" }`.++### Reads++`{host}/api/projects/{projectId}/insights/{insightId}/?refresh=force_cache`, plus `&from_dashboard={dashboardId}` for a dashboard pin.+Without `insightId`: `insights/?short_id={shortId}&refresh=force_cache`, taking the result whose `short_id` matches.+Headers: `Authorization: Bearer {accessToken}`, `Accept: application/json`, `User-Agent: posthog-mobile-widget/<app version> (<ios|android>)`.+Timeout 20 s.+The widget only reads what the server already computed: never `blocking`, never `force_blocking`.++| Answer | Error kind | Render |+| ------------------------------------ | -------------- | ------------------------------------------------------------------- |+| 200 with `result` and no query error | none (cleared) | The new snapshot |+| 401, 403, or an expired token | `auth` | "Open PostHog to update" |+| 404 | `not_found` | "<name> was unpinned or deleted." and how to pick another pin |+| 429, 503 | `rate_limited` | The cached snapshot |+| No connection | `network` | The cached snapshot |+| A response the parser cannot read | `bad_data` | The cached snapshot, else the error |+| 200 with `result: null`, no error | `no_result` | The cached snapshot, else "Open it in PostHog to load this insight" |++### Cadence++- iOS: the timeline reloads after 30 minutes, with entries at +0 and +15 minutes so the age text stays true. Only the first entry fetches.+- Android: `updatePeriodMillis` 1800000, and a one-time WorkManager request (network connected) on each update and configuration change.+- Both: one request per distinct pin per refresh, shared by every widget that shows it.+- Every render shows the age of its data, "Updated 12 min ago", in orange past 60 minutes.++### States++| State | Text |+| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| Not configured | "Choose a pin", then "Touch and hold to pick a pin from your Views tab" |+| No credentials, demo mode | "Sign in to see your pins", then "Open PostHog to sign in" |+| Expired or rejected token | "Open PostHog to update" |+| Pin missing from catalog | "<name> is no longer pinned" |+| Catalog of another project | "In another project", then "Switch to <projectName> in PostHog" |+| Pin from another project | iOS: a pin missing from the catalog whose `chart.pinProject` marker names another project. Same text, with that project's name |+| Ineligible pin | The pin's `reason` |+| First read pending | The title, "Loading…" and a placeholder sparkline. Only for a pin never read |+| No cached result | The title, then "Open it in PostHog to load this insight"; links to the insight |++A state links to `<scheme>://views`; a chart links to the pin's view with `from=widget` (see "How it works").+The scheme is `posthog`, `posthog-dev` or `posthog-preview` by build variant (`src/lib/appVariants.json`).++### Identifiers++| | iOS | Android |+| ------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------- |+| Widget | kind `ChartWidget`, in the `HedgehogWidget` extension target | see "Chart widget (Android)" |+| Native module | `ChartWidget`, pod `PostHogChartWidget` (`ios/ChartWidgetModule.swift`) | `ChartWidget`, class `com.posthog.code.mobile.chart.ChartWidgetModule` |+| App Group | `group.<app bundle id>`, shared with the hedgehog widget | n/a |++The pod is not named `ChartWidget`, because the extension target owns the widget's Swift module names and a pod of the same name would shadow them.++## Native module API++```ts+// Imported by path: local Expo modules have no node_modules entry.+import { isAvailable, setCredentials, clearCredentials, setCatalog, clearCatalog, reloadWidgets } from '../../../modules/chart-widget'++isAvailable(): boolean // false on web and in a build without the native module+setCredentials(credentials: WidgetCredentials): void // store the session copy, then refresh every placed widget; throws when the store write fails+clearCredentials(): void // remove the session copy and every chart.snapshot.*, chart.snapshotError.* and chart.pinProject.* key, then refresh+setCatalog(json: string): void // replace chart.catalog, then refresh+clearCatalog(): void // remove chart.catalog, then refresh+reloadWidgets(): void // refresh every placed Chart widget+```++App code calls `syncWidgetCredentials`, `syncWidgetCatalog` and `clearWidgetState` in `src/features/widgets/chartWidgetSync.ts` instead of the module, so the writes stay idempotent.+`buildCatalog` (`src/features/widgets/chartWidgetCatalog.ts`) is the pure catalog builder.++## Chart widget (Android)++RemoteViews only (no Glance, no Compose), API 24 and up. Code in `android/src/main/java/com/posthog/code/mobile/chart/`:++| File | Role |+| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |+| `ChartModels.kt` | Credentials, catalog, widget config, snapshot and error JSON (`org.json`). |+| `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. |+| `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. |+| `ChartWidgetConfigureActivity.kt` | "Choose a pin", a plain `Activity` built from views. |++### Identifiers++| | Android |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Provider | receiver `com.posthog.code.mobile.chart.ChartWidgetProvider`, info `res/xml/chart_widget_info.xml` |+| Configure activity | `com.posthog.code.mobile.chart.ChartWidgetConfigureActivity` (`APPWIDGET_CONFIGURE`, exported) |+| Plain preferences | `chart_widget`: `chart.catalog`, `chart.snapshot.<pinId>`, `chart.snapshotError.<pinId>`, `chart.widget.<appWidgetId>` |+| Secure preferences | `chart_widget_secure` (`EncryptedSharedPreferences`, `MasterKey` AES256_GCM): `credentials` |+| Work | unique `chart-widget-refresh` (REPLACE, network required), `chart-widget-keep-enabled` |+| Deep links | `<scheme>://views/insight/<shortId>?from=widget&family=<small\|medium\|large>`, `<scheme>://views/dashboard/<dashboardId>?from=widget&family=…`, states open `<scheme>://views` |++The scheme comes from the package suffix (`.dev`, `.preview`, none), the same table as `src/lib/appVariants.json`.+`chart.widget.<appWidgetId>` also keeps `projectId`, `projectName` and `pinName` from the moment the pin was chosen.+They 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.++### 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.+ 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.+- 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`.++### 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`).+- 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.++### Configure flow++1. Placing a Chart widget opens "Choose a pin". It starts with `RESULT_CANCELED`, so backing out does not place the widget.+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.+5. Signed out: "Sign in to PostHog to see your pins". No pins: "Pin a dashboard or insight in Views first". Both offer "Open PostHog".+6. `widgetFeatures="reconfigurable"` lets Android 12+ reopen the screen from a long press; it preselects the current choice.++## Chart widget (iOS)++The iOS widget is a second kind in the `HedgehogWidget` extension (`targets/HedgehogWidget/`).+It reads the catalog and its snapshots from the App Group suite and the credentials from the keychain, and it reads PostHog itself.++| File | What it holds |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |+| `AppGroup.swift` | The App Group id from the extension's bundle id, shared with the hedgehog's `SharedStore` |+| `ChartModels.swift` | `Codable` shapes of the credentials, catalog, snapshot and snapshot error JSON |+| `ChartStore.swift` | Store keys, snapshot, error and pin project reads and writes, the keychain read (Foundation + Security) |+| `ChartFetcher.swift` | The cache-only insight read, status mapping, and `ChartRefresh` (one request per pin at a time) |+| `TrendsParser.swift` | `TrendsQuery` response to snapshot, mirroring `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts` and `rangePresets.ts` |+| `ChartState.swift` | Which state each slot shows, which pins a refresh reads, deep links, age text, gallery sample data |+| `ChartWidgetIntent.swift` | `ChartWidgetIntent`, `PinEntity` and `PinQuery` (the Edit widget picker) |+| `ChartTimelineProvider.swift` | `AppIntentTimelineProvider`: reads, writes snapshots, builds entries |+| `ChartViews.swift` | SwiftUI for small, medium and large, light and dark |+| `ChartWidget.swift` | The `AppIntentConfiguration`, registered in `HedgehogWidgetBundle.swift` |++### Native check++From `products/mobile` on macOS:++```sh+swiftc targets/HedgehogWidget/{AppGroup,ChartModels,ChartStore,ChartFetcher,TrendsParser,ChartState}.swift scripts/check_chart_widget.swift -o /tmp/check-chart+/tmp/check-chart+```++It prints one line per check and exits non-zero on a failure.+It covers a big number with a compare aggregate, a 14-day line with compare totals, bars with an open last bucket, two and six series, breakdown placeholders, every value format including durations outside the integer range, range labels, the catalog picker filter, fetch URLs, headers and status mapping, response size limits, tile changes during a refresh, the store round trip, pin project markers, and every widget state.+The SwiftUI, WidgetKit and AppIntents files do not compile there; `xcodebuild` checks them.++### Identifiers++| | iOS |+| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Widget | kind `ChartWidget`, target `HedgehogWidget`, families small, medium, large |+| Configuration | `ChartWidgetIntent` ("Chart"): `pin: PinEntity?`, `extraPins: [PinEntity]?` (large only) |+| Picker entity | `PinEntity`, id = the catalog pin id; `PinQuery` lists eligible pins in Views order |+| Store | `UserDefaults(suiteName: "group.<app bundle id>")`, keys `chart.catalog`, `chart.snapshot.<pinId>`, `chart.snapshotError.<pinId>`, `chart.pinProject.<pinId>` |+| Credentials | keychain generic password, service `com.posthog.code.mobile.chart-widget`, account `credentials`, access group `group.<app bundle id>` |+| Deep links | `<scheme>://views/insight/<shortId>?from=widget&family=<small\|medium\|large>`, `<scheme>://views/dashboard/<dashboardId>?from=widget&family=...`; states open `<scheme>://views` |++The scheme follows the bundle id's variant suffix, as in `src/lib/appVariants.json`: `posthog`, `posthog-dev` or `posthog-preview`.++### Timeline++- Each timeline call reads the configured pins (the primary pin, plus up to two extra pins on large), each distinct pin once, concurrently.+- A pin is read again only when its snapshot is 5 minutes old, it has an error, or the catalog was written after the snapshot (a new tile).+ Widgets that show the same pin and resolved insight URL share the read; a second widget in the same process waits for the running one.+ If the catalog points the pin at another insight or dashboard context before a read completes, that read's result is discarded.+- iOS reads at most 1 MiB of a response before decoding JSON and cancels larger responses, including responses without a content length.+ An oversized response counts as `bad_data` and keeps any cached chart.+- After a 429 or 503, the pin waits a minute before the next read.+- Each timeline call writes `chart.pinProject.<pinId>` for every configured pin the catalog lists, when it changed.+ A configured pin that later leaves the catalog shows "In another project" when its marker names a project other than the token's, else "<name> is no longer pinned".+- A 200 with `result: null` writes `no_result`: the server has not computed the insight, and the widget never asks it to.+ With a cached snapshot the widget keeps showing it; without one it asks to open the insight, which links to it.+- Entries at now and now + 15 minutes, which only move the age label. Reload policy `.after(now + 30 min)`.+- An expired token (`now > expiresAt - 60 s`), a missing token or a catalog of another project sends no request.+- The gallery shows sample numbers; a placed widget's snapshot shows the store without a read.++### Snapshot fields++- `valueText` follows `numberParts`: `aggregated_value`; else the window total with a compare series and summable math; else the last complete bucket.+ It is absent when the insight has no single number (several series or a breakdown).+- `deltaPercent` is the signed change behind the pill: a percent, or points for a `percentage` or `percentage_scaled` insight.+ `deltaText` has no sign or arrow: "12%" (whole above 10, one decimal below), "0.7 pts", or "No change".+ A change against zero has no pill.+- `deltaBasis` follows `deltaBasisText`: "vs previous period", or "vs Nov 2" against the bucket before.+- `series` holds up to five current series, then the previous-period series of those, aligned to the first current series and cut to the last 60 buckets.+ A bucket without a number has `value: null`.+- The age label reads `lastRefreshAt` (when the server computed the numbers), else `fetchedAt`.+ With several pins on screen it shows the oldest. It turns orange after 60 minutes.diff --git a/products/mobile/modules/chart-widget/expo-module.config.json b/products/mobile/modules/chart-widget/expo-module.config.jsonnew file mode 100644index 000000000000..eb94d6734085--- /dev/null+++ b/products/mobile/modules/chart-widget/expo-module.config.json@@ -0,0 +1,6 @@+{+ "platforms": ["apple"],+ "apple": {+ "modules": ["ChartWidgetModule"]+ }+}diff --git a/products/mobile/modules/chart-widget/index.ts b/products/mobile/modules/chart-widget/index.tsnew file mode 100644index 000000000000..f79d6e13a98d--- /dev/null+++ b/products/mobile/modules/chart-widget/index.ts@@ -0,0 +1,49 @@+import { requireOptionalNativeModule } from 'expo-modules-core'++export interface WidgetCredentials {+ host: string+ projectId: number+ projectName: string+ accessToken: string+ /** Epoch ms, or null when the token does not expire. */+ expiresAt: number | null+ userUuid: string+}++interface ChartWidgetNativeModule {+ setCredentials(json: string): void+ clearCredentials(): void+ setCatalog(json: string): void+ clearCatalog(): void+ reloadWidgets(): void+}++const native = requireOptionalNativeModule<ChartWidgetNativeModule>('ChartWidget')++/** False on web and in any build without the native module, so callers can skip the sync. */+export function isAvailable(): boolean {+ return native !== null+}++/** Stores a read-only copy of the session for the widget's own reads, then refreshes every placed widget. */+export function setCredentials(credentials: WidgetCredentials): void {+ native?.setCredentials(JSON.stringify({ version: 1, ...credentials }))+}++/** Removes the stored session and every cached snapshot; widgets then ask to sign in. */+export function clearCredentials(): void {+ native?.clearCredentials()+}++/** Replaces the pin catalog the OS pickers list, then refreshes every placed widget. */+export function setCatalog(json: string): void {+ native?.setCatalog(json)+}++export function clearCatalog(): void {+ native?.clearCatalog()+}++export function reloadWidgets(): void {+ native?.reloadWidgets()+}diff --git a/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swift b/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swiftnew file mode 100644index 000000000000..5d1141bf0527--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swift@@ -0,0 +1,100 @@+import ExpoModulesCore+import Security+import WidgetKit++// The suite, keys, keychain item and widget kind must match targets/HedgehogWidget/Chart*.swift and+// modules/chart-widget/README.md.+// app.config.ts names the App Group "group." plus the bundle id, so each app variant (dev, preview, store) has its own.+private let suiteName = "group.\(Bundle.main.bundleIdentifier ?? "com.posthog.code.mobile")"+private let catalogKey = "chart.catalog"+private let snapshotKeyPrefixes = ["chart.snapshot.", "chart.snapshotError.", "chart.pinProject."]+private let widgetKind = "ChartWidget"+private let keychainService = "com.posthog.code.mobile.chart-widget"+private let keychainAccount = "credentials"++enum ChartWidgetKeychainError: Error, CustomStringConvertible {+ case status(OSStatus)++ var description: String {+ switch self {+ case let .status(status):+ return "The widget session could not be saved to the keychain (OSStatus \(status))"+ }+ }+}++// An App Group id is also a keychain access group of every target in that group, so the widget extension reads this+// item without a keychain-sharing entitlement.+private func credentialsItem() -> [String: Any] {+ [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: keychainService,+ kSecAttrAccount as String: keychainAccount,+ kSecAttrAccessGroup as String: suiteName,+ ]+}++private func writeCredentials(_ json: String) throws {+ // The widget refreshes on a timer while the phone is locked, so the item must stay readable after the first unlock.+ let attributes: [String: Any] = [+ kSecValueData as String: Data(json.utf8),+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,+ ]+ var status = SecItemUpdate(credentialsItem() as CFDictionary, attributes as CFDictionary)+ if status == errSecItemNotFound {+ let item = credentialsItem().merging(attributes) { _, new in new }+ status = SecItemAdd(item as CFDictionary, nil)+ }+ if status != errSecSuccess {+ throw ChartWidgetKeychainError.status(status)+ }+}++private func deleteCredentials() -> OSStatus {+ SecItemDelete(credentialsItem() as CFDictionary)+}++private func removeSnapshots() {+ guard let defaults = UserDefaults(suiteName: suiteName) else {+ return+ }+ for key in defaults.dictionaryRepresentation().keys+ where snapshotKeyPrefixes.contains(where: { key.hasPrefix($0) }) {+ defaults.removeObject(forKey: key)+ }+}++public class ChartWidgetModule: Module {+ public func definition() -> ModuleDefinition {+ Name("ChartWidget")++ Function("setCredentials") { (json: String) throws in+ try writeCredentials(json)+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }++ Function("clearCredentials") { () throws in+ let status = deleteCredentials()+ // Charts of the previous account must not show to whoever signs in next, even when the delete failed.+ removeSnapshots()+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ if status != errSecSuccess && status != errSecItemNotFound {+ throw ChartWidgetKeychainError.status(status)+ }+ }++ Function("setCatalog") { (json: String) in+ UserDefaults(suiteName: suiteName)?.set(json, forKey: catalogKey)+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }++ Function("clearCatalog") {+ UserDefaults(suiteName: suiteName)?.removeObject(forKey: catalogKey)+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }++ Function("reloadWidgets") {+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }+ }+}diff --git a/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspec b/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspecnew file mode 100644index 000000000000..4e45a824729d--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspec@@ -0,0 +1,27 @@+require 'json'++package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))++# Not named ChartWidget: the widget extension target owns the HedgehogWidget Swift module, and a pod named after a+# widget kind would shadow it the same way.+Pod::Spec.new do |s|+ s.name = 'PostHogChartWidget'+ s.version = package['version']+ s.summary = 'Hands the session and pin catalog to the iOS Chart home-screen widget'+ s.license = 'MIT'+ s.author = 'PostHog'+ s.homepage = 'https://posthog.com'+ s.platforms = { :ios => '16.4' }+ s.swift_version = '5.9'+ s.source = { git: 'https://github.com/PostHog/posthog.git' }+ s.static_framework = true++ s.dependency 'ExpoModulesCore'+ s.frameworks = 'WidgetKit', 'Security'++ s.source_files = '**/*.{h,m,swift}'+ s.pod_target_xcconfig = {+ 'DEFINES_MODULE' => 'YES',+ 'SWIFT_COMPILATION_MODE' => 'wholemodule'+ }+enddiff --git a/products/mobile/modules/chart-widget/package.json b/products/mobile/modules/chart-widget/package.jsonnew file mode 100644index 000000000000..6de1ee542cd2--- /dev/null+++ b/products/mobile/modules/chart-widget/package.json@@ -0,0 +1,6 @@+{+ "name": "chart-widget",+ "version": "1.0.0",+ "private": true,+ "main": "index.ts"+}diff --git a/products/mobile/modules/hedgehog-widget/README.md b/products/mobile/modules/hedgehog-widget/README.mdindex 2b9fb446d786..6439f7140c8e 100644--- a/products/mobile/modules/hedgehog-widget/README.md+++ b/products/mobile/modules/hedgehog-widget/README.md@@ -150,7 +150,7 @@ There is no runtime image download.From `products/mobile` on macOS:```sh-swiftc targets/HedgehogWidget/{Choreography,HedgehogTimelineProvider}.swift scripts/check_hedgehog_timeline.swift -o /tmp/check-hoglet+swiftc targets/HedgehogWidget/{AppGroup,Choreography,HedgehogTimelineProvider}.swift scripts/check_hedgehog_timeline.swift -o /tmp/check-hoglet/tmp/check-hoglet [choreography.json ...]```diff --git a/products/mobile/scripts/check_chart_widget.swift b/products/mobile/scripts/check_chart_widget.swiftnew file mode 100644index 000000000000..7db49832243c--- /dev/null+++ b/products/mobile/scripts/check_chart_widget.swift@@ -0,0 +1,566 @@+import Foundation++// Usage: check-chart++@main+struct CheckChartWidget {+ static var failures = 0++ static func check(_ name: String, _ passed: Bool, _ detail: @autoclosure () -> String = "") {+ if passed {+ print("ok \(name)")+ } else {+ failures += 1+ print("FAIL \(name) \(detail())")+ }+ }++ static func main() async throws {+ // Bucket labels are wall-clock times, so the in-progress rule depends on the zone. Pin one.+ NSTimeZone.default = TimeZone(identifier: "America/New_York")!+ let now = ChartDates.parse("2026-11-04T17:00:00Z")!++ try checkBoldNumber(now: now)+ try checkLineWithCompare(now: now)+ try checkBarInProgress(now: now)+ try checkTwoSeries(now: now)+ try checkPercentagePoints(now: now)+ checkFormats()+ checkRangeLabels()+ try checkCatalog()+ checkFetcher(now: now)+ await checkResponseLimits()+ try checkStore(now: now)+ try await checkRefresh(now: now)+ try checkState(now: now)++ if failures > 0 {+ print("\(failures) check(s) failed")+ exit(1)+ }+ print("Passed: big number, compare totals, bars with an open bucket, two series, formats, ranges, catalog, fetch, store, states")+ }++ static func days(from start: String, count: Int) -> [String] {+ let first = ChartDates.bucketStart(start)!+ let calendar = Calendar(identifier: .gregorian)+ return (0..<count).map { ChartDates.dayLabel(calendar.date(byAdding: .day, value: $0, to: first)!) }+ }++ static func json(_ object: Any) -> String {+ String(data: try! JSONSerialization.data(withJSONObject: object), encoding: .utf8)!+ }++ static func response(_ text: String) -> JSONObject {+ try! JSONSerialization.jsonObject(with: Data(text.utf8)) as! JSONObject+ }++ static func trends(+ display: String? = nil, dateFrom: String? = "-14d", interval: String = "day", series: Int = 1,+ math: String? = nil, format: String? = nil, prefix: String? = nil, suffix: String? = nil+ ) -> JSONObject {+ var filter: JSONObject = [:]+ if let display { filter["display"] = display }+ if let format { filter["aggregationAxisFormat"] = format }+ if let prefix { filter["aggregationAxisPrefix"] = prefix }+ if let suffix { filter["aggregationAxisPostfix"] = suffix }+ var node: JSONObject = ["kind": "EventsNode", "event": "$pageview"]+ if let math { node["math"] = math }+ var source: JSONObject = [+ "kind": "TrendsQuery", "interval": interval, "trendsFilter": filter,+ "series": Array(repeating: node, count: series),+ ]+ if let dateFrom { source["dateRange"] = ["date_from": dateFrom] }+ return ["kind": "InsightVizNode", "source": source]+ }++ static func checkBoldNumber(now: Date) throws {+ let labels = days(from: "2026-10-22", count: 14)+ let text = json([+ "id": 1, "short_id": "abc123", "last_refresh": "2026-11-04T16:48:00Z",+ "query": trends(display: "BoldNumber", math: "dau"),+ "resolved_date_range": ["date_from": "2026-10-22T00:00:00-04:00", "date_to": "2026-11-04T23:59:59.999999-05:00"],+ "result": [+ ["label": "Signups", "action": ["order": 0], "compare_label": "current", "aggregated_value": 1284,+ "data": Array(repeating: 90, count: 14), "days": labels],+ ["label": "Signups", "action": ["order": 0], "compare_label": "previous", "aggregated_value": 1143,+ "data": Array(repeating: 80, count: 14), "days": days(from: "2026-10-08", count: 14)],+ ],+ ] as JSONObject)+ let snapshot = try TrendsParser.snapshot(data: Data(text.utf8), pinId: "pin-1", now: now)+ check("big number: aggregate is the value", snapshot.valueText == "1,284", "\(String(describing: snapshot.valueText))")+ check("big number: delta against the previous aggregate", snapshot.deltaText == "12%" && abs((snapshot.deltaPercent ?? 0) - 12.336) < 0.01,+ "\(String(describing: snapshot.deltaText)) \(String(describing: snapshot.deltaPercent))")+ check("big number: basis is the previous period", snapshot.deltaBasis == "vs previous period")+ check("big number: pill reads up", snapshot.pillText == "▲ 12%", "\(String(describing: snapshot.pillText))")+ check("big number: draws a line from data", snapshot.chartKind == .line && snapshot.currentSeries.first?.points.count == 14)+ check("big number: range label", snapshot.rangeLabel == "Last 14 days", "\(String(describing: snapshot.rangeLabel))")+ check("big number: snapshot JSON round trip", try JSONDecoder().decode(ChartSnapshot.self, from: JSONEncoder().encode(snapshot)) == snapshot)+ }++ static func checkLineWithCompare(now: Date) throws {+ let current: [Double] = [72, 80, 77, 85, 91, 88, 79, 94, 98, 90, 101, 97, 108, 124]+ let previous: [Double] = [70, 75, 70, 80, 81, 80, 70, 84, 88, 80, 91, 87, 98, 101]+ let text = json([+ "last_refresh": "2026-11-04T15:30:00Z",+ "query": trends(display: "ActionsLineGraph"),+ "resolved_date_range": ["date_from": "2026-10-22T00:00:00-04:00", "date_to": "2026-11-04T23:59:59.999999-05:00"],+ "result": [+ ["label": "$pageview", "action": ["order": 0], "compare_label": "current", "data": current, "days": days(from: "2026-10-22", count: 14)],+ ["label": "$pageview", "action": ["order": 0], "compare_label": "previous", "data": previous, "days": days(from: "2026-10-08", count: 14)],+ ],+ ] as JSONObject)+ let snapshot = try TrendsParser.snapshot(data: Data(text.utf8), pinId: "pin-2", now: now)+ let total = current.reduce(0, +)+ let previousTotal = previous.reduce(0, +)+ let percent = (total - previousTotal) / previousTotal * 100+ check("line + compare: summable math totals the window", snapshot.valueText == TrendsParser.formatValue(total, .init()),+ "\(String(describing: snapshot.valueText)) vs \(total)")+ check("line + compare: delta against the previous total", abs((snapshot.deltaPercent ?? 0) - percent) < 1e-9 && snapshot.deltaBasis == "vs previous period")+ check("line + compare: current then previous series", snapshot.series.map(\.previous) == [false, true] && snapshot.series[1].label == "Previous period")+ check("line + compare: 14 points each", snapshot.series.allSatisfy { $0.points.count == 14 })+ check("line + compare: interval and range", snapshot.intervalLabel == "day" && snapshot.rangeLabel == "Last 14 days")+ check("line + compare: axis end labels", snapshot.axisLabels(limit: 60).map { [$0.0, $0.1] } == ["Oct 22", "Nov 4"],+ "\(String(describing: snapshot.axisLabels(limit: 60)))")+ }++ static func checkBarInProgress(now: Date) throws {+ let labels = days(from: "2026-10-29", count: 7)+ func snapshot(dateTo: String?) throws -> ChartSnapshot {+ var body: JSONObject = [+ "query": trends(display: "ActionsBar", dateFrom: "-7d"),+ "result": [["label": "Signups", "action": ["order": 0], "data": [10, 12, 9, 14, 20, 18, 3], "days": labels]],+ ]+ if let dateTo { body["resolved_date_range"] = ["date_from": "2026-10-29T00:00:00-04:00", "date_to": dateTo] }+ return try TrendsParser.snapshot(data: Data(json(body).utf8), pinId: "pin-3", now: now)+ }+ let open = try snapshot(dateTo: "2026-11-04T23:59:59.999999-05:00")+ check("bars: chart kind", open.chartKind == .bar)+ check("bars: open last bucket is not the value", open.valueText == "18", "\(String(describing: open.valueText))")+ check("bars: delta against the bucket before", open.deltaText == "10%" && (open.deltaPercent ?? 0) < 0 && open.pillText == "▼ 10%",+ "\(String(describing: open.deltaText)) \(String(describing: open.deltaPercent))")+ check("bars: basis names the bucket", open.deltaBasis == "vs Nov 2", "\(String(describing: open.deltaBasis))")+ check("bars: the open bucket still draws", open.series.first?.points.last?.value == 3)+ let closed = try snapshot(dateTo: "2026-11-03T23:59:59.999999-05:00")+ check("bars: a closed window uses its last bucket", closed.valueText == "3", "\(String(describing: closed.valueText))")+ let unresolved = try snapshot(dateTo: nil)+ check("bars: without a resolved range, today's bucket is open", unresolved.valueText == "18", "\(String(describing: unresolved.valueText))")+ }++ static func checkTwoSeries(now: Date) throws {+ let labels = days(from: "2026-10-22", count: 14)+ let text = json([+ "query": trends(display: "ActionsLineGraph", series: 2),+ "result": [+ ["label": "Signups", "action": ["order": 0], "data": Array(repeating: 5, count: 14), "days": labels],+ ["label": "Logins", "action": ["order": 1], "data": Array(repeating: 9, count: 14), "days": labels],+ ],+ ] as JSONObject)+ let snapshot = try TrendsParser.snapshot(data: Data(text.utf8), pinId: "pin-4", now: now)+ check("two series: no headline value", snapshot.valueText == nil && snapshot.pillText == nil)+ check("two series: both drawn in order", snapshot.series.map(\.label) == ["Signups", "Logins"])++ let six = json([+ "query": trends(series: 6),+ "result": (0..<6).map { ["label": "S\($0)", "action": ["order": $0], "data": [1, 2], "days": ["2026-11-03", "2026-11-04"]] as JSONObject },+ ] as JSONObject)+ let capped = try TrendsParser.snapshot(data: Data(six.utf8), pinId: "pin-5", now: now)+ check("many series: capped at five", capped.series.count == 5)++ let breakdown = json([+ "query": trends(),+ "result": [["label": "$pageview - $$_posthog_breakdown_other_$$", "breakdown_value": "$$_posthog_breakdown_other_$$",+ "action": ["order": 0], "data": [1], "days": ["2026-11-04"]]],+ ] as JSONObject)+ let other = try TrendsParser.snapshot(data: Data(breakdown.utf8), pinId: "pin-6", now: now)+ check("breakdown placeholders read Other", other.series.first?.label == "$pageview - Other", "\(String(describing: other.series.first?.label))")+ }++ static func checkPercentagePoints(now: Date) throws {+ let text = json([+ "query": trends(dateFrom: "-7d", format: "percentage_scaled"),+ "resolved_date_range": ["date_from": "2026-10-28T00:00:00-04:00", "date_to": "2026-11-03T23:59:59-05:00"],+ "result": [["label": "Conversion", "action": ["order": 0], "data": [0.42, 0.45, 0.4567],+ "days": ["2026-11-01", "2026-11-02", "2026-11-03"]]],+ ] as JSONObject)+ let snapshot = try TrendsParser.snapshot(data: Data(text.utf8), pinId: "pin-7", now: now)+ check("percentage: value scaled", snapshot.valueText == "45.67%", "\(String(describing: snapshot.valueText))")+ check("percentage: delta in points", snapshot.pillText == "▲ 0.7 pts", "\(String(describing: snapshot.pillText))")+ }++ static func checkFormats() {+ let nbsp = "\u{00a0}"+ let cases: [(String, Double, TrendsParser.ValueFormat, String)] = [+ ("numeric", 1284, .init(), "1,284"),+ ("numeric decimals", 1284.567, .init(), "1,284.57"),+ ("numeric large", 1_234_567, .init(), "1,234,567"),+ ("numeric small", 0.012345, .init(), "0.012"),+ ("percentage", 12.3, .init(style: "percentage"), "12.3%"),+ ("percentage_scaled", 0.4567, .init(style: "percentage_scaled"), "45.67%"),+ ("duration", 125, .init(style: "duration"), "2m\(nbsp)5s"),+ ("duration seconds", 45.2, .init(style: "duration"), "45.2s"),+ ("duration hours", 7384, .init(style: "duration"), "2h\(nbsp)3m\(nbsp)4s"),+ ("duration_ms", 850, .init(style: "duration_ms"), "850ms"),+ ("duration outside integer range", 1e20, .init(style: "duration"), "1e+20s"),+ ("negative duration outside integer range", -1e20, .init(style: "duration"), "-1e+20s"),+ ("duration_ms outside integer range", 1e23, .init(style: "duration_ms"), "1e+20s"),+ ("duration_ns outside integer range", 1e29, .init(style: "duration_ns"), "1e+20s"),+ ("duration at integer boundary", Double(Int.max), .init(style: "duration"), "9.22337e+18s"),+ ("prefix and postfix", 1284, .init(prefix: "~", suffix: " users"), "~1,284 users"),+ ("currency", 12.5, .init(style: "currency", prefix: "$"), "$12.50"),+ ("short", 1284, .init(style: "short"), "1.28\(nbsp)K"),+ ("decimal places", 3.14159, .init(decimalPlaces: 1), "3.1"),+ ]+ for (name, value, format, expected) in cases {+ let formatted = TrendsParser.formatValue(value, format)+ check("format \(name)", formatted == expected, "got \(formatted.debugDescription), want \(expected.debugDescription)")+ }+ }++ static func checkRangeLabels() {+ let cases: [(String?, String?, String?)] = [+ ("-14d", nil, "Last 14 days"),+ ("-7d", nil, "Last 7 days"),+ ("-30d", nil, "Last 30 days"),+ ("dStart", nil, "Today"),+ ("-1mStart", "-1mEnd", "Last month"),+ ("-3d", nil, "Last 3 days"),+ ("-1w", nil, "Last week"),+ ("2026-10-01", "2026-10-15", "Oct 1 to 15"),+ ("-1mStart", nil, nil),+ ]+ for (from, to, expected) in cases {+ let label = TrendsParser.savedRangeLabel(dateFrom: from, dateTo: to)+ check("range \(from ?? "nil")..\(to ?? "nil")", label == expected, "got \(String(describing: label))")+ }+ let resolved = TrendsParser.ResolvedRange(from: "2026-10-22T00:00:00-04:00", to: "2026-11-04T23:59:59-05:00")+ let unknown = TrendsParser.rangeLabel(source: ["dateRange": ["date_from": "-1mStart"]], resolved: resolved, interval: .day)+ check("range unknown falls back to the resolved window", unknown == "Oct 22 to Nov 4", "got \(String(describing: unknown))")+ }++ static let catalogJSON = """+ {+ "version": 1, "host": "https://us.posthog.com", "projectId": 2, "projectName": "PostHog App", "writtenAt": 1762270000000,+ "pins": [+ { "id": "pin-a", "kind": "insight", "name": "Signups", "subtitle": "Insight", "insightId": 123, "shortId": "abc123", "dashboardId": null, "eligible": true, "number": true, "chart": true, "reason": null },+ { "id": "pin-b", "kind": "dashboard", "name": "Product KPIs", "subtitle": "Product KPIs · Daily active users", "insightId": 456, "shortId": "def456", "dashboardId": 12, "eligible": true, "number": true, "chart": true, "reason": null },+ { "id": "pin-c", "kind": "insight", "name": "Checkout funnel", "subtitle": "Insight", "insightId": 789, "shortId": "ghi789", "dashboardId": null, "eligible": false, "number": false, "chart": false, "reason": "Not a chart over time" },+ { "id": "pin-d", "kind": "insight", "name": "Retention", "subtitle": "Insight", "insightId": null, "shortId": "jkl012", "dashboardId": null, "eligible": true, "number": true, "chart": true, "reason": null }+ ]+ }+ """++ static func checkCatalog() throws {+ let catalog = try require(ChartStore.decodeCatalog(catalogJSON), "catalog decodes")+ check("catalog: picker leaves out ineligible pins, keeps Views order", catalog.pickerPins.map(\.id) == ["pin-a", "pin-b", "pin-d"])+ check("catalog: another version is ignored", ChartStore.decodeCatalog(catalogJSON.replacingOccurrences(of: "\"version\": 1", with: "\"version\": 2")) == nil)+ }++ static let credentials = ChartCredentials(+ version: 1, host: "https://us.posthog.com", projectId: 2, projectName: "PostHog App",+ accessToken: "phx_example", expiresAt: nil, userUuid: "user-1"+ )++ static func checkFetcher(now: Date) {+ let catalog = ChartStore.decodeCatalog(catalogJSON)!+ let insight = catalog.pin(id: "pin-a")!+ let dashboard = catalog.pin(id: "pin-b")!+ let byShortId = catalog.pin(id: "pin-d")!+ check("fetch URL: insight by id", ChartFetcher.url(for: insight, host: "https://us.posthog.com/", projectId: 2)?.absoluteString+ == "https://us.posthog.com/api/projects/2/insights/123/?refresh=force_cache")+ check("fetch URL: dashboard tile", ChartFetcher.url(for: dashboard, host: "https://us.posthog.com", projectId: 2)?.absoluteString+ == "https://us.posthog.com/api/projects/2/insights/456/?refresh=force_cache&from_dashboard=12")+ check("fetch URL: by short id", ChartFetcher.url(for: byShortId, host: "https://us.posthog.com", projectId: 2)?.absoluteString+ == "https://us.posthog.com/api/projects/2/insights/?short_id=jkl012&refresh=force_cache")+ let request = ChartFetcher.request(for: insight, credentials: credentials, appVersion: "1.9.0")+ check("fetch headers", request?.value(forHTTPHeaderField: "Authorization") == "Bearer phx_example"+ && request?.value(forHTTPHeaderField: "Accept") == "application/json"+ && request?.value(forHTTPHeaderField: "User-Agent") == "posthog-mobile-widget/1.9.0 (ios)"+ && request?.timeoutInterval == 20)++ let empty = Data()+ check("status 401 is auth", ChartFetcher.outcome(status: 401, body: empty, pin: insight, now: now) == .failed(.auth))+ check("status 403 is auth", ChartFetcher.outcome(status: 403, body: empty, pin: insight, now: now) == .failed(.auth))+ check("status 404 is not_found", ChartFetcher.outcome(status: 404, body: empty, pin: insight, now: now) == .failed(.notFound))+ check("status 429 is rate_limited", ChartFetcher.outcome(status: 429, body: empty, pin: insight, now: now) == .failed(.rateLimited))+ check("status 503 is rate_limited", ChartFetcher.outcome(status: 503, body: empty, pin: insight, now: now) == .failed(.rateLimited))+ check("unparseable 200 is bad_data", ChartFetcher.outcome(status: 200, body: Data("<html>".utf8), pin: insight, now: now) == .failed(.badData))+ let miss = Data(json(["query": trends(), "result": NSNull(), "last_refresh": NSNull()] as JSONObject).utf8)+ check("cache miss is no_result", ChartFetcher.outcome(status: 200, body: miss, pin: insight, now: now) == .failed(.noResult))+ let limited = Data(json(["query": trends(), "result": NSNull(), "query_status": ["error": true, "error_code": "rate_limited"]] as JSONObject).utf8)+ check("rate-limited 200 is rate_limited", ChartFetcher.outcome(status: 200, body: limited, pin: insight, now: now) == .failed(.rateLimited))+ let failed = Data(json(["query": trends(), "result": [], "query_status": ["error": true]] as JSONObject).utf8)+ check("query error is bad_data", ChartFetcher.outcome(status: 200, body: failed, pin: insight, now: now) == .failed(.badData))+ let list = Data(json(["results": [+ ["short_id": "other", "query": trends(), "result": []],+ ["short_id": "jkl012", "query": trends(), "result": [["label": "A", "data": [4], "days": ["2026-11-03"]]]],+ ]] as JSONObject).utf8)+ if case .snapshot(let snapshot) = ChartFetcher.outcome(status: 200, body: list, pin: byShortId, now: now) {+ check("short id read takes the matching result", snapshot.pinId == "pin-d" && snapshot.series.first?.label == "A")+ } else {+ check("short id read takes the matching result", false)+ }+ let noMatch = Data(json(["results": [["short_id": "other", "query": trends(), "result": []]]] as JSONObject).utf8)+ check("short id read without a match is not_found", ChartFetcher.outcome(status: 200, body: noMatch, pin: byShortId, now: now) == .failed(.notFound))+ let funnel = Data(json(["query": ["kind": "InsightVizNode", "source": ["kind": "FunnelsQuery"]], "result": []] as JSONObject).utf8)+ check("a non-trends result is bad_data", ChartFetcher.outcome(status: 200, body: funnel, pin: insight, now: now) == .failed(.badData))+ }++ static func checkStore(now: Date) throws {+ let suite = "check-chart-widget-\(ProcessInfo.processInfo.processIdentifier)"+ let store = try require(UserDefaults(suiteName: suite), "test suite")+ defer { store.removePersistentDomain(forName: suite) }+ check("app group from the extension id", AppGroup.appId(fromExtensionBundleId: "com.posthog.code.mobile.dev.HedgehogWidget") == "com.posthog.code.mobile.dev"+ && AppGroup.appId(fromExtensionBundleId: "com.posthog.code.mobile") == "com.posthog.code.mobile")+ store.set(catalogJSON, forKey: ChartStore.catalogKey)+ let catalog = try require(ChartStore.catalog(store: store), "stored catalog")+ let pin = try require(catalog.pin(id: "pin-a"), "stored pin")+ let dashboard = try require(catalog.pin(id: "pin-b"), "stored dashboard pin")+ check("store: catalog reads back", ChartStore.catalog(store: store)?.pins.count == 4)+ let snapshot = ChartSample.snapshot(pinId: "pin-a", value: "1,284", delta: 12, deltaText: "12%", values: [1, 2, 3], now: now)+ ChartRefresh.record(.failed(.network), pin: pin, credentials: credentials, at: now, store: store)+ check("store: a failure writes the error", ChartStore.error(pinId: "pin-a", store: store)?.kind == .network)+ check("store: error JSON uses the contract's kind names",+ store.string(forKey: "chart.snapshotError.pin-a")?.contains("\"network\"") == true)+ ChartRefresh.record(.snapshot(snapshot), pin: pin, credentials: credentials, at: now, store: store)+ check("store: a good read writes the snapshot", ChartStore.snapshot(pinId: "pin-a", store: store) == snapshot)+ check("store: a good read clears the error", ChartStore.error(pinId: "pin-a", store: store) == nil)+ ChartRefresh.record(.failed(.rateLimited), pin: pin, credentials: credentials, at: now, store: store)+ check("store: a failure keeps the snapshot", ChartStore.snapshot(pinId: "pin-a", store: store) == snapshot)+ check("store: snapshotError kind", store.string(forKey: "chart.snapshotError.pin-a")?.contains("rate_limited") == true)+ ChartRefresh.record(.failed(.noResult), pin: dashboard, credentials: credentials, at: now, store: store)+ check("store: a cache miss writes no_result", store.string(forKey: "chart.snapshotError.pin-b")?.contains("\"no_result\"") == true)+ ChartStore.save(ChartPinProject(projectId: 2, projectName: "PostHog App"), pinId: "pin-a", store: store)+ let marker = store.string(forKey: "chart.pinProject.pin-a").flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? JSONObject }+ check("store: pin project marker JSON", (marker?["projectId"] as? Int) == 2 && (marker?["projectName"] as? String) == "PostHog App")+ check("store: pin project marker reads back", ChartStore.pinProject(pinId: "pin-a", store: store) == ChartPinProject(projectId: 2, projectName: "PostHog App"))+ let credentialsJSON = #"{"version":1,"host":"https://eu.posthog.com","projectId":7,"projectName":"Shop","accessToken":"pha_example","expiresAt":null,"userUuid":"u"}"#+ check("credentials decode with a null expiry", ChartStore.decodeCredentials(Data(credentialsJSON.utf8))?.isExpired(at: now) == false)++ for (target, changedCatalog) in [+ (pin, catalogJSON.replacingOccurrences(of: "\"insightId\": 123", with: "\"insightId\": 321")),+ (dashboard, catalogJSON.replacingOccurrences(of: "\"dashboardId\": 12", with: "\"dashboardId\": 13")),+ ] {+ let currentSnapshot = ChartSample.snapshot(pinId: target.id, value: "654", delta: 0, deltaText: "No change", values: [654], now: now)+ let oldSnapshot = ChartSample.snapshot(pinId: target.id, value: "123", delta: 0, deltaText: "No change", values: [123], now: now)+ ChartStore.save(currentSnapshot, store: store)+ store.set(changedCatalog, forKey: ChartStore.catalogKey)+ for outcome in [ChartFetchOutcome.failed(.notFound), .snapshot(oldSnapshot)] {+ ChartRefresh.record(outcome, pin: target, credentials: credentials, at: now, store: store)+ check("store: a changed target discards late outcomes", ChartStore.snapshot(pinId: target.id, store: store) == currentSnapshot+ && ChartStore.error(pinId: target.id, store: store) == nil)+ }+ }+ }++ struct ResponseBytes: AsyncSequence, AsyncIteratorProtocol {+ typealias Element = UInt8+ var count: Int++ func makeAsyncIterator() -> Self { self }++ mutating func next() async -> UInt8? {+ guard count > 0 else { return nil }+ count -= 1+ return 65+ }+ }++ static func checkResponseLimits() async {+ for (length, expectedLength, accepted) in [(16, 16, true), (16, -1, true), (17, -1, false), (17, 16, false), (0, 17, false)] {+ do {+ let data = try await ChartFetcher.readBody(ResponseBytes(count: length), expectedLength: Int64(expectedLength), limit: 16)+ check("response limit: \(length) bytes, declared \(expectedLength)", accepted && data == Data(repeating: 65, count: length))+ } catch ChartFetcher.ResponseError.tooLarge {+ check("response limit: \(length) bytes, declared \(expectedLength)", !accepted)+ } catch {+ check("response limit: unexpected error", false, "\(error)")+ }+ }+ }++ actor PendingFetches {+ private var pending: [Int: CheckedContinuation<ChartFetchOutcome, Never>] = [:]+ private var arrivals: [Int: CheckedContinuation<Void, Never>] = [:]++ func fetch(_ pin: ChartPin) async -> ChartFetchOutcome {+ await withCheckedContinuation { continuation in+ pending[pin.insightId!] = continuation+ arrivals.removeValue(forKey: pin.insightId!)?.resume()+ }+ }++ func waitForRequest(_ insightId: Int) async {+ if pending[insightId] != nil { return }+ await withCheckedContinuation { arrivals[insightId] = $0 }+ }++ func complete(_ insightId: Int, with outcome: ChartFetchOutcome) {+ pending.removeValue(forKey: insightId)?.resume(returning: outcome)+ }+ }++ static func checkRefresh(now: Date) async throws {+ let suite = "check-chart-refresh-\(ProcessInfo.processInfo.processIdentifier)"+ let store = try require(UserDefaults(suiteName: suite), "refresh test suite")+ defer { store.removePersistentDomain(forName: suite) }+ store.set(catalogJSON, forKey: ChartStore.catalogKey)+ let pin = try require(ChartStore.catalog(store: store)?.pin(id: "pin-b"), "original dashboard tile")+ let requests = PendingFetches()+ let refresh = ChartRefresh(store: store, fetch: { pin, _, _ in await requests.fetch(pin) })+ let original = Task { await refresh.refresh(pin, credentials: credentials, now: now) }+ await requests.waitForRequest(456)++ store.set(catalogJSON.replacingOccurrences(of: "\"insightId\": 456", with: "\"insightId\": 654"), forKey: ChartStore.catalogKey)+ let replacement = try require(ChartStore.catalog(store: store)?.pin(id: pin.id), "replacement dashboard tile")+ let updated = Task { await refresh.refresh(replacement, credentials: credentials, now: now) }+ await requests.waitForRequest(654)+ let snapshot = ChartSample.snapshot(pinId: pin.id, value: "654", delta: 0, deltaText: "No change", values: [654], now: now)+ await requests.complete(654, with: .snapshot(snapshot))+ await updated.value+ check("refresh: a changed tile starts its own request", ChartStore.snapshot(pinId: pin.id, store: store) == snapshot)++ let oldSnapshot = ChartSample.snapshot(pinId: pin.id, value: "456", delta: 0, deltaText: "No change", values: [456], now: now)+ await requests.complete(456, with: .snapshot(oldSnapshot))+ await original.value+ check("refresh: the old tile cannot overwrite the new result", ChartStore.snapshot(pinId: pin.id, store: store) == snapshot)+ }++ static func checkState(now: Date) throws {+ let catalog = try require(ChartStore.decodeCatalog(catalogJSON), "catalog")+ let links = ChartLinks(scheme: ChartLinks.scheme(forAppId: "com.posthog.code.mobile"), family: .medium)+ let signups = ChartSelection(id: "pin-a", name: "Signups")+ let nowMs = now.timeIntervalSince1970 * 1000+ func state(+ credentials: ChartCredentials? = credentials, catalog: ChartCatalog? = catalog,+ snapshots: [String: ChartSnapshot] = [:], errors: [String: ChartSnapshotError] = [:],+ projects: [String: ChartPinProject] = [:]+ ) -> ChartStoreState {+ ChartStoreState(+ credentials: credentials, catalog: catalog, snapshot: { snapshots[$0] }, error: { errors[$0] }, pinProject: { projects[$0] }+ )+ }+ func detail(_ content: ChartContent) -> String? {+ if case .message(_, let detail) = content.primary.state { return detail }+ return nil+ }+ func message(_ content: ChartContent) -> String? {+ if case .message(let text, _) = content.primary.state { return text }+ return nil+ }++ let signedOut = ChartResolver.content(primary: signups, extras: [], store: state(credentials: nil), links: links, now: now)+ check("state: signed out", message(signedOut) == "Sign in to see your pins" && signedOut.primary.link.absoluteString == "posthog://views")++ let expired = ChartCredentials(version: 1, host: credentials.host, projectId: 2, projectName: nil, accessToken: "x",+ expiresAt: nowMs + 30_000, userUuid: nil)+ check("state: expiring token counts as expired", expired.isExpired(at: now))+ check("state: expired token sends nothing", ChartResolver.pinsToFetch([signups], store: state(credentials: expired), now: now).isEmpty)+ check("state: expired token asks to open the app",+ message(ChartResolver.content(primary: signups, extras: [], store: state(credentials: expired), links: links, now: now)) == "Open PostHog to update")++ let unconfigured = ChartResolver.content(primary: nil, extras: [], store: state(), links: links, now: now)+ check("state: not configured", message(unconfigured) == "Choose a pin")++ let revenue = ChartSelection(id: "pin-x", name: "Revenue")+ let gone = ChartResolver.content(primary: revenue, extras: [], store: state(), links: links, now: now)+ check("state: pin missing from the catalog", message(gone) == "Revenue is no longer pinned")+ let moved = ChartResolver.content(primary: revenue, extras: [],+ store: state(projects: ["pin-x": ChartPinProject(projectId: 7, projectName: "Shop")]), links: links, now: now)+ check("state: a pin from another project says so", message(moved) == "In another project"+ && detail(moved) == "Switch to Shop in PostHog" && moved.primary.title == "Revenue")+ let sameProject = ChartResolver.content(primary: revenue, extras: [],+ store: state(projects: ["pin-x": ChartPinProject(projectId: 2, projectName: "PostHog App")]), links: links, now: now)+ check("state: a pin gone from its own project is no longer pinned", message(sameProject) == "Revenue is no longer pinned")+ let markers = ChartResolver.pinProjects([signups, revenue, ChartSelection(id: "pin-c", name: "C")], catalog: catalog)+ check("pin project markers: only pins the catalog lists", markers.map(\.pinId) == ["pin-a", "pin-c"]+ && markers.allSatisfy { $0.project == ChartPinProject(projectId: 2, projectName: "PostHog App") })++ let notFound = ChartResolver.content(primary: signups, extras: [],+ store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .notFound)]), links: links, now: now)+ check("state: deleted insight", message(notFound) == "Signups was unpinned or deleted. Touch and hold to pick another.")++ let auth = ChartResolver.content(primary: signups, extras: [],+ store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .auth)]), links: links, now: now)+ check("state: rejected token", message(auth) == "Open PostHog to update")++ let ineligible = ChartResolver.content(primary: ChartSelection(id: "pin-c", name: "Checkout funnel"), extras: [], store: state(), links: links, now: now)+ check("state: ineligible shows the reason", message(ineligible) == "Not a chart over time" && ineligible.primary.title == "Checkout funnel")++ let elsewhere = ChartCredentials(version: 1, host: credentials.host, projectId: 9, projectName: "Other", accessToken: "x", expiresAt: nil, userUuid: nil)+ let otherProject = ChartResolver.content(primary: signups, extras: [], store: state(credentials: elsewhere), links: links, now: now)+ if case .message(let text, let detail) = otherProject.primary.state {+ check("state: pin in another project", text == "In another project" && detail == "Switch to PostHog App in PostHog")+ } else {+ check("state: pin in another project", false)+ }+ check("state: another project sends nothing", ChartResolver.pinsToFetch([signups], store: state(credentials: elsewhere), now: now).isEmpty)++ let loading = ChartResolver.content(primary: signups, extras: [], store: state(), links: links, now: now)+ check("state: first read pending", loading.primary.state == .loading && loading.primary.title == "Signups")++ let cached = ChartSample.snapshot(pinId: "pin-a", value: "1,284", delta: 12, deltaText: "12%", values: [1, 2], now: now.addingTimeInterval(-3600))+ let stale = ChartResolver.content(primary: signups, extras: [],+ store: state(snapshots: ["pin-a": cached], errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .network)]),+ links: links, now: now)+ check("state: a failed read keeps the cache", stale.primary.snapshot == cached+ && stale.primary.link.absoluteString == "posthog://views/insight/abc123?from=widget&family=medium")+ check("state: age turns stale after an hour", ChartAge.isStale(dataDate: cached.dataDate, at: now)+ && ChartAge.text(dataDate: cached.dataDate, at: now) == "Updated 1 h ago")+ check("state: age in minutes", ChartAge.text(dataDate: now.addingTimeInterval(-12 * 60), at: now) == "Updated 12 min ago")++ let noCache = ChartResolver.content(primary: signups, extras: [],+ store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .network)]), links: links, now: now)+ check("state: a failed first read says so", message(noCache) == "Couldn't refresh")++ let notComputed = ChartResolver.content(primary: signups, extras: [],+ store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .noResult)]), links: links, now: now)+ check("state: no result asks to open the insight", message(notComputed) == "Open it in PostHog to load this insight"+ && notComputed.primary.title == "Signups"+ && notComputed.primary.link.absoluteString == "posthog://views/insight/abc123?from=widget&family=medium")+ let cachedMiss = ChartResolver.content(primary: signups, extras: [],+ store: state(snapshots: ["pin-a": cached], errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .noResult)]),+ links: links, now: now)+ check("state: no result keeps the cache", cachedMiss.primary.snapshot == cached)+ check("fetch plan: no result reads again", ChartResolver.pinsToFetch(+ [signups], store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs, kind: .noResult)]), now: now).count == 1)++ let dashboard = ChartResolver.content(primary: ChartSelection(id: "pin-b", name: "Product KPIs"), extras: [],+ store: state(snapshots: ["pin-b": cached]), links: links, now: now)+ check("link: dashboard pin", dashboard.primary.link.absoluteString == "posthog://views/dashboard/12?from=widget&family=medium")+ check("link: scheme per variant", ChartLinks.scheme(forAppId: "com.posthog.code.mobile.dev") == "posthog-dev"+ && ChartLinks.scheme(forAppId: "com.posthog.code.mobile.preview") == "posthog-preview")++ let fresh = ChartSample.snapshot(pinId: "pin-a", value: "1", delta: 0, deltaText: "No change", values: [1], now: now.addingTimeInterval(-60))+ let pins = ChartResolver.pinsToFetch(+ [signups, signups, ChartSelection(id: "pin-b", name: "Product KPIs"), ChartSelection(id: "pin-c", name: "Checkout funnel")],+ store: state(), now: now+ )+ check("fetch plan: each pin once, ineligible left out", pins.map(\.id) == ["pin-a", "pin-b"])+ check("fetch plan: a fresh snapshot is shared", ChartResolver.pinsToFetch([signups], store: state(snapshots: ["pin-a": fresh]), now: now).isEmpty)+ let rewritten = try require(ChartStore.decodeCatalog(catalogJSON.replacingOccurrences(of: "1762270000000", with: "\(Int(nowMs))")), "catalog")+ check("fetch plan: a newer catalog reads again", ChartResolver.pinsToFetch([signups], store: state(catalog: rewritten, snapshots: ["pin-a": fresh]), now: now).count == 1)+ check("fetch plan: a recent 429 waits", ChartResolver.pinsToFetch(+ [signups], store: state(errors: ["pin-a": ChartSnapshotError(at: nowMs - 10_000, kind: .rateLimited)]), now: now).isEmpty)++ let (_, extras) = ChartResolver.selections(+ primary: signups,+ extras: [signups, ChartSelection(id: "pin-b", name: "B"), ChartSelection(id: "pin-b", name: "B"), ChartSelection(id: "pin-d", name: "D"), ChartSelection(id: "pin-c", name: "C")],+ family: .large+ )+ check("large: two extra pins, no repeats", extras.map(\.id) == ["pin-b", "pin-d"])+ check("medium: no extra pins", ChartResolver.selections(primary: signups, extras: extras, family: .medium).1.isEmpty)+ }++ static func require<T>(_ value: T?, _ name: String) throws -> T {+ guard let value else {+ check(name, false, "missing")+ throw CheckError.missing(name)+ }+ return value+ }++ enum CheckError: Error {+ case missing(String)+ }+}diff --git a/products/mobile/targets/HedgehogWidget/AppGroup.swift b/products/mobile/targets/HedgehogWidget/AppGroup.swiftnew file mode 100644index 000000000000..8f44de6eba4c--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/AppGroup.swift@@ -0,0 +1,17 @@+import Foundation++enum AppGroup {+ private static let extensionSuffix = ".HedgehogWidget"++ // app.config.ts names the App Group "group." plus the app's bundle id, and this extension's bundle id is the+ // app's id plus ".HedgehogWidget", so each app variant reads its own store.+ static func appId(fromExtensionBundleId widgetId: String) -> String {+ widgetId.hasSuffix(extensionSuffix) ? String(widgetId.dropLast(extensionSuffix.count)) : widgetId+ }++ static let appId: String = appId(+ fromExtensionBundleId: Bundle.main.bundleIdentifier ?? "com.posthog.code.mobile\(extensionSuffix)"+ )++ static let suiteName = "group.\(appId)"+}diff --git a/products/mobile/targets/HedgehogWidget/ChartFetcher.swift b/products/mobile/targets/HedgehogWidget/ChartFetcher.swiftnew file mode 100644index 000000000000..2cd712ad6bbf--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartFetcher.swift@@ -0,0 +1,205 @@+import Foundation++enum ChartFetchOutcome: Equatable, Sendable {+ case snapshot(ChartSnapshot)+ case failed(ChartErrorKind)+}++/// One cache-only insight read with the app's session. The widget never sends `blocking` or `force_blocking`: it only+/// reads what the server already computed, the cheap lane in docs/VIEWS.md "Refresh".+struct ChartFetcher {+ static let timeout: TimeInterval = 20+ static let maxResponseBytes = 1_048_576++ enum ResponseError: Error {+ case tooLarge+ }++ // Ephemeral, so responses read with the user's token never land in a disk cache.+ private static let session: URLSession = {+ let configuration = URLSessionConfiguration.ephemeral+ configuration.timeoutIntervalForRequest = timeout+ configuration.timeoutIntervalForResource = timeout+ configuration.waitsForConnectivity = false+ configuration.urlCache = nil+ return URLSession(configuration: configuration)+ }()++ static var appVersion: String {+ Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"+ }++ static func url(for pin: ChartPin, host: String, projectId: Int) -> URL? {+ let base = host.hasSuffix("/") ? String(host.dropLast()) : host+ if let insightId = pin.insightId {+ var components = URLComponents(string: "\(base)/api/projects/\(projectId)/insights/\(insightId)/")+ var items = [URLQueryItem(name: "refresh", value: "force_cache")]+ if pin.isDashboard, let dashboardId = pin.dashboardId {+ items.append(URLQueryItem(name: "from_dashboard", value: String(dashboardId)))+ }+ components?.queryItems = items+ return components?.url+ }+ guard let shortId = pin.shortId, !shortId.isEmpty else { return nil }+ var components = URLComponents(string: "\(base)/api/projects/\(projectId)/insights/")+ components?.queryItems = [+ URLQueryItem(name: "short_id", value: shortId),+ URLQueryItem(name: "refresh", value: "force_cache"),+ ]+ return components?.url+ }++ static func request(for pin: ChartPin, credentials: ChartCredentials, appVersion: String) -> URLRequest? {+ guard let url = url(for: pin, host: credentials.host, projectId: credentials.projectId) else { return nil }+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)+ request.setValue("Bearer \(credentials.accessToken)", forHTTPHeaderField: "Authorization")+ request.setValue("application/json", forHTTPHeaderField: "Accept")+ request.setValue("posthog-mobile-widget/\(appVersion) (ios)", forHTTPHeaderField: "User-Agent")+ return request+ }++ static func outcome(status: Int, body: Data, pin: ChartPin, now: Date) -> ChartFetchOutcome {+ switch status {+ case 200:+ return parse(body, pin: pin, now: now)+ case 401, 403:+ return .failed(.auth)+ case 404:+ return .failed(.notFound)+ case 429, 503:+ return .failed(.rateLimited)+ case 500...:+ // Other server errors pass like a dropped connection, so the cache stays on screen.+ return .failed(.network)+ default:+ return .failed(.badData)+ }+ }++ static func readBody<Bytes: AsyncSequence>(+ _ bytes: Bytes, expectedLength: Int64, limit: Int = maxResponseBytes+ ) async throws -> Data where Bytes.Element == UInt8 {+ guard expectedLength <= Int64(limit) else { throw ResponseError.tooLarge }+ var data = Data()+ if expectedLength > 0 {+ data.reserveCapacity(Int(expectedLength))+ }+ for try await byte in bytes {+ guard data.count < limit else { throw ResponseError.tooLarge }+ data.append(byte)+ }+ return data+ }++ /// Only a response with a result and no error may change the snapshot (`hasGoodResult` in insightSnapshot.ts). A+ /// rate-limited answer is a 200 with `result: null`.+ private static func parse(_ body: Data, pin: ChartPin, now: Date) -> ChartFetchOutcome {+ guard let json = (try? JSONSerialization.jsonObject(with: body)) as? JSONObject else {+ return .failed(.badData)+ }+ var response = json+ if pin.insightId == nil {+ let results = (json["results"] as? [Any])?.compactMap { $0 as? JSONObject } ?? []+ guard let match = results.first(where: { $0["short_id"] as? String == pin.shortId }) else {+ return .failed(.notFound)+ }+ response = match+ }+ let status = response["query_status"] as? JSONObject+ if status?["error_code"] as? String == "rate_limited" {+ return .failed(.rateLimited)+ }+ if TrendsParser.isTruthy(status?["error"]) {+ return .failed(.badData)+ }+ if response["result"] == nil || response["result"] is NSNull {+ return .failed(.noResult)+ }+ guard let snapshot = try? TrendsParser.snapshot(response: response, pinId: pin.id, now: now) else {+ return .failed(.badData)+ }+ return .snapshot(snapshot)+ }++ func fetch(pin: ChartPin, credentials: ChartCredentials, now: Date) async -> ChartFetchOutcome {+ guard let request = Self.request(for: pin, credentials: credentials, appVersion: Self.appVersion) else {+ return .failed(.badData)+ }+ do {+ let (bytes, response) = try await Self.session.bytes(for: request)+ defer { bytes.task.cancel() }+ guard let http = response as? HTTPURLResponse else { return .failed(.network) }+ guard http.statusCode == 200 else {+ return Self.outcome(status: http.statusCode, body: Data(), pin: pin, now: now)+ }+ let data = try await Self.readBody(bytes, expectedLength: response.expectedContentLength)+ return Self.outcome(status: http.statusCode, body: data, pin: pin, now: now)+ } catch ResponseError.tooLarge {+ return .failed(.badData)+ } catch {+ return .failed(.network)+ }+ }+}++/// Widgets share a request only while their pin points at the same insight and dashboard context.+actor ChartRefresh {+ static let shared = ChartRefresh()++ private struct RequestKey: Hashable {+ let pinId: String+ let url: URL+ }++ private let store: UserDefaults?+ private let fetch: @Sendable (ChartPin, ChartCredentials, Date) async -> ChartFetchOutcome+ private var running: [RequestKey: Task<Void, Never>] = [:]++ init(+ store: UserDefaults? = ChartStore.defaults,+ fetch: @escaping @Sendable (ChartPin, ChartCredentials, Date) async -> ChartFetchOutcome = {+ await ChartFetcher().fetch(pin: $0, credentials: $1, now: $2)+ }+ ) {+ self.store = store+ self.fetch = fetch+ }++ private static func key(for pin: ChartPin, host: String, projectId: Int) -> RequestKey? {+ ChartFetcher.url(for: pin, host: host, projectId: projectId).map { RequestKey(pinId: pin.id, url: $0) }+ }++ func refresh(_ pin: ChartPin, credentials: ChartCredentials, now: Date) async {+ guard let key = Self.key(for: pin, host: credentials.host, projectId: credentials.projectId) else { return }+ if let task = running[key] {+ await task.value+ return+ }+ let task = Task {+ let outcome = await fetch(pin, credentials, now)+ Self.record(outcome, pin: pin, credentials: credentials, at: now, store: store)+ }+ running[key] = task+ await task.value+ running[key] = nil+ }++ static func record(+ _ outcome: ChartFetchOutcome, pin: ChartPin, credentials: ChartCredentials, at now: Date,+ store: UserDefaults? = ChartStore.defaults+ ) {+ guard let catalog = ChartStore.catalog(store: store), catalog.belongs(to: credentials),+ let current = catalog.pin(id: pin.id), current.eligible,+ let originalKey = key(for: pin, host: credentials.host, projectId: credentials.projectId),+ key(for: current, host: catalog.host, projectId: catalog.projectId) == originalKey+ else {+ return+ }+ switch outcome {+ case .snapshot(let snapshot):+ ChartStore.save(snapshot, store: store)+ case .failed(let kind):+ ChartStore.save(ChartSnapshotError(at: (now.timeIntervalSince1970 * 1000).rounded(), kind: kind), pinId: pin.id, store: store)+ }+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartModels.swift b/products/mobile/targets/HedgehogWidget/ChartModels.swiftnew file mode 100644index 000000000000..f7034c595642--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartModels.swift@@ -0,0 +1,134 @@+import Foundation++// The JSON shapes of the chart widget's shared store, as modules/chart-widget/README.md describes them. The app's+// JavaScript writes the catalog and the credentials and the Android widget writes the same snapshot shape, so a change+// here needs the same change on both sides.++struct ChartCredentials: Codable, Equatable, Sendable {+ static let supportedVersion = 1++ let version: Int+ let host: String+ let projectId: Int+ let projectName: String?+ let accessToken: String+ /// Epoch ms. Nil for a personal API key, which never expires.+ let expiresAt: Double?+ let userUuid: String?++ /// A minute of slack, so the token cannot expire between this check and the server reading it.+ func isExpired(at now: Date) -> Bool {+ guard let expiresAt else { return false }+ return now.timeIntervalSince1970 * 1000 > expiresAt - 60_000+ }+}++struct ChartPin: Codable, Equatable, Identifiable, Sendable {+ /// The pin's shortcut id. The widget configuration stores it.+ let id: String+ /// "insight" or "dashboard".+ let kind: String+ let name: String+ let subtitle: String?+ /// Nil until the app has read the insight; the widget then reads by `shortId`.+ let insightId: Int?+ let shortId: String?+ let dashboardId: Int?+ let eligible: Bool+ let number: Bool+ let chart: Bool+ let reason: String?++ var isDashboard: Bool { kind == "dashboard" }+}++struct ChartCatalog: Codable, Equatable, Sendable {+ static let supportedVersion = 1++ let version: Int+ let host: String+ let projectId: Int+ let projectName: String?+ /// Epoch ms.+ let writtenAt: Double+ /// In Views order.+ let pins: [ChartPin]++ var pickerPins: [ChartPin] { pins.filter(\.eligible) }++ func pin(id: String) -> ChartPin? {+ pins.first { $0.id == id }+ }++ /// The token reads one project on one host; a catalog of another project needs the app to switch first.+ func belongs(to credentials: ChartCredentials) -> Bool {+ projectId == credentials.projectId && Self.normalized(host) == Self.normalized(credentials.host)+ }++ private static func normalized(_ host: String) -> String {+ let lowered = host.lowercased()+ return lowered.hasSuffix("/") ? String(lowered.dropLast()) : lowered+ }+}++enum ChartKind: String, Codable, Sendable {+ case line, bar+}++struct ChartPoint: Codable, Equatable, Sendable {+ /// The server's bucket label, such as "2026-10-22".+ let at: String+ /// Nil for a bucket without a number, because JSON has no NaN.+ let value: Double?+}++struct ChartSeries: Codable, Equatable, Sendable {+ let label: String+ let points: [ChartPoint]+ let previous: Bool+}++struct ChartSnapshot: Codable, Equatable, Sendable {+ static let supportedVersion = 1++ let version: Int+ let pinId: String+ /// Epoch ms of the read that wrote this snapshot.+ let fetchedAt: Double+ let lastRefreshAt: String?+ let rangeLabel: String?+ /// The trends interval: "hour", "day", "week" or "month".+ let intervalLabel: String+ /// Nil when the insight has no single number, such as two series.+ let valueText: String?+ /// The signed change that sets the pill's direction: percent, or points for a percentage insight.+ let deltaPercent: Double?+ let deltaText: String?+ let deltaBasis: String?+ /// Up to five current series, then the previous-period series of those. Up to 60 points each.+ let series: [ChartSeries]+ let chartKind: ChartKind+}++enum ChartErrorKind: String, Codable, Sendable {+ case network+ case auth+ case notFound = "not_found"+ case rateLimited = "rate_limited"+ case badData = "bad_data"+ /// A 200 without a result: the server has not computed the insight, and the widget never asks it to.+ case noResult = "no_result"+}++struct ChartSnapshotError: Codable, Equatable, Sendable {+ /// Epoch ms.+ let at: Double+ let kind: ChartErrorKind+}++/// The project a pin last appeared in (`chart.pinProject.<pinId>`). After a project switch the new catalog no longer+/// lists the pin, and this tells "in another project" apart from "unpinned".+struct ChartPinProject: Codable, Equatable, Sendable {+ let projectId: Int+ let projectName: String?+}diff --git a/products/mobile/targets/HedgehogWidget/ChartState.swift b/products/mobile/targets/HedgehogWidget/ChartState.swiftnew file mode 100644index 000000000000..3f293cdf8d84--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartState.swift@@ -0,0 +1,342 @@+import Foundation++// What each chart widget shows, decided from the store without WidgetKit, so scripts/check_chart_widget.swift can run it.++enum ChartFamily: String {+ case small, medium, large+}++struct ChartSelection: Equatable {+ let id: String+ let name: String+}++struct ChartSlot: Equatable {+ enum State: Equatable {+ case ready(ChartSnapshot)+ case loading+ case message(String, detail: String?)+ }++ /// The pin's name, when it is known and the message does not already say it.+ let title: String?+ let state: State+ let link: URL++ var snapshot: ChartSnapshot? {+ if case .ready(let snapshot) = state {+ return snapshot+ }+ return nil+ }+}++struct ChartContent: Equatable {+ let primary: ChartSlot+ let extras: [ChartSlot]++ /// The oldest data on screen, so the one age label is true for every number (`statusLine` in freshness.ts).+ var oldestData: Date? {+ ([primary] + extras).compactMap { $0.snapshot?.dataDate }.min()+ }+}++/// Deep links into the app's Views routes (docs/VIEWS.md "Routes").+struct ChartLinks {+ let scheme: String+ let family: ChartFamily++ /// `scheme` per app id in src/lib/appVariants.json: the store app id plus the variant's `idSuffix`.+ private static let schemes: [(suffix: String, scheme: String)] = [+ (".dev", "posthog-dev"),+ (".preview", "posthog-preview"),+ ]++ static func scheme(forAppId appId: String) -> String {+ schemes.first { appId.hasSuffix($0.suffix) }?.scheme ?? "posthog"+ }++ var root: URL {+ URL(string: "\(scheme)://views")!+ }++ func pin(_ pin: ChartPin) -> URL {+ let query = "from=widget&family=\(family.rawValue)"+ if pin.isDashboard, let dashboardId = pin.dashboardId {+ return URL(string: "\(scheme)://views/dashboard/\(dashboardId)?\(query)") ?? root+ }+ if let shortId = pin.shortId?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), !shortId.isEmpty {+ return URL(string: "\(scheme)://views/insight/\(shortId)?\(query)") ?? root+ }+ return root+ }+}++struct ChartStoreState {+ let credentials: ChartCredentials?+ let catalog: ChartCatalog?+ let snapshot: (String) -> ChartSnapshot?+ let error: (String) -> ChartSnapshotError?+ let pinProject: (String) -> ChartPinProject?+}++enum ChartResolver {+ /// A pin read in the last 5 minutes is not read again, so widgets that show the same pin share one request. The+ /// same floor as an automatic read in Views (docs/VIEWS.md "Refresh").+ static let shareWindow: TimeInterval = 5 * 60+ static let rateLimitPause: TimeInterval = 60++ static let signedOut = ChartSlot.State.message("Sign in to see your pins", detail: "Open PostHog to sign in")+ static let reauthenticate = ChartSlot.State.message("Open PostHog to update", detail: nil)+ static let notConfigured = ChartSlot.State.message("Choose a pin", detail: "Touch and hold to pick a pin from your Views tab")+ static let noResult = ChartSlot.State.message("Open it in PostHog to load this insight", detail: nil)++ static func selections(primary: ChartSelection?, extras: [ChartSelection], family: ChartFamily) -> (ChartSelection?, [ChartSelection]) {+ guard family == .large else { return (primary, []) }+ var seen = Set(primary.map { [$0.id] } ?? [])+ var unique: [ChartSelection] = []+ for extra in extras where !seen.contains(extra.id) {+ seen.insert(extra.id)+ unique.append(extra)+ }+ return (primary, Array(unique.prefix(2)))+ }++ static func needsFetch(snapshot: ChartSnapshot?, error: ChartSnapshotError?, catalog: ChartCatalog, now: Date) -> Bool {+ let nowMs = now.timeIntervalSince1970 * 1000+ if let error {+ return !(error.kind == .rateLimited && nowMs - error.at < rateLimitPause * 1000)+ }+ guard let snapshot else { return true }+ // A catalog written after the read can point the pin at another tile.+ return nowMs - snapshot.fetchedAt >= shareWindow * 1000 || snapshot.fetchedAt < catalog.writtenAt+ }++ static func pinProjects(_ selections: [ChartSelection], catalog: ChartCatalog?) -> [(pinId: String, project: ChartPinProject)] {+ guard let catalog else { return [] }+ let project = ChartPinProject(projectId: catalog.projectId, projectName: catalog.projectName)+ return selections.filter { catalog.pin(id: $0.id) != nil }.map { ($0.id, project) }+ }++ static func pinsToFetch(_ selections: [ChartSelection], store: ChartStoreState, now: Date) -> [ChartPin] {+ guard let credentials = store.credentials, !credentials.isExpired(at: now),+ let catalog = store.catalog, catalog.belongs(to: credentials)+ else {+ return []+ }+ var seen = Set<String>()+ var pins: [ChartPin] = []+ for selection in selections where !seen.contains(selection.id) {+ seen.insert(selection.id)+ guard let pin = catalog.pin(id: selection.id), pin.eligible, pin.insightId != nil || pin.shortId != nil,+ needsFetch(snapshot: store.snapshot(pin.id), error: store.error(pin.id), catalog: catalog, now: now)+ else {+ continue+ }+ pins.append(pin)+ }+ return pins+ }++ static func content(+ primary: ChartSelection?, extras: [ChartSelection], store: ChartStoreState, links: ChartLinks, now: Date+ ) -> ChartContent {+ guard let credentials = store.credentials else {+ return ChartContent(primary: ChartSlot(title: nil, state: signedOut, link: links.root), extras: [])+ }+ if credentials.isExpired(at: now) {+ return ChartContent(primary: ChartSlot(title: primary?.name, state: reauthenticate, link: links.root), extras: [])+ }+ return ChartContent(+ primary: slot(primary, credentials: credentials, store: store, links: links),+ extras: extras.map { slot($0, credentials: credentials, store: store, links: links) }+ )+ }++ static func slot(+ _ selection: ChartSelection?, credentials: ChartCredentials, store: ChartStoreState, links: ChartLinks+ ) -> ChartSlot {+ guard let selection else {+ return ChartSlot(title: nil, state: notConfigured, link: links.root)+ }+ // The app writes the catalog after its first pin list read.+ guard let catalog = store.catalog else {+ return ChartSlot(title: selection.name, state: .loading, link: links.root)+ }+ guard let pin = catalog.pin(id: selection.id) else {+ if let project = store.pinProject(selection.id), project.projectId != credentials.projectId {+ return otherProject(title: selection.name, projectName: project.projectName, links: links)+ }+ return ChartSlot(title: nil, state: .message("\(selection.name) is no longer pinned", detail: nil), link: links.root)+ }+ guard catalog.belongs(to: credentials) else {+ return otherProject(title: pin.name, projectName: catalog.projectName, links: links)+ }+ guard pin.eligible else {+ return ChartSlot(+ title: pin.name, state: .message(pin.reason ?? "Not supported on the widget yet", detail: nil), link: links.root+ )+ }+ let error = store.error(pin.id)+ switch error?.kind {+ case .auth:+ return ChartSlot(title: pin.name, state: reauthenticate, link: links.root)+ case .notFound:+ return ChartSlot(+ title: nil,+ state: .message("\(pin.name) was unpinned or deleted. Touch and hold to pick another.", detail: nil),+ link: links.root+ )+ default:+ break+ }+ if let snapshot = store.snapshot(pin.id) {+ return ChartSlot(title: pin.name, state: .ready(snapshot), link: links.pin(pin))+ }+ if let error {+ // Opening the insight in the app computes it; the widget then reads the result.+ return ChartSlot(title: pin.name, state: failure(error.kind), link: error.kind == .noResult ? links.pin(pin) : links.root)+ }+ return ChartSlot(title: pin.name, state: .loading, link: links.root)+ }++ private static func otherProject(title: String, projectName: String?, links: ChartLinks) -> ChartSlot {+ ChartSlot(+ title: title,+ state: .message("In another project", detail: "Switch to \(projectName ?? "that project") in PostHog"),+ link: links.root+ )+ }++ static func failure(_ kind: ChartErrorKind) -> ChartSlot.State {+ switch kind {+ case .badData:+ return .message("Can't show this insight here", detail: nil)+ case .auth:+ return reauthenticate+ case .notFound:+ return .message("Not found", detail: nil)+ case .network, .rateLimited:+ return .message("Couldn't refresh", detail: "Trying again soon")+ case .noResult:+ return noResult+ }+ }+}++extension ChartSnapshot {+ var dataDate: Date {+ if let lastRefreshAt, let computed = ChartDates.parse(lastRefreshAt) {+ return computed+ }+ return Date(timeIntervalSince1970: fetchedAt / 1000)+ }++ var interval: TrendsParser.Interval {+ TrendsParser.Interval.of(intervalLabel)+ }++ var currentSeries: [ChartSeries] { series.filter { !$0.previous } }++ var hasPoints: Bool {+ currentSeries.contains { series in series.points.contains { $0.value != nil } }+ }++ var pillText: String? {+ guard let deltaText else { return nil }+ guard let deltaPercent, deltaPercent != 0 else { return deltaText }+ return "\(deltaPercent > 0 ? "▲" : "▼") \(deltaText)"+ }++ func trimmed(to limit: Int) -> [ChartSeries] {+ series.map { ChartSeries(label: $0.label, points: Array($0.points.suffix(limit)), previous: $0.previous) }+ }++ func axisLabels(limit: Int) -> (String, String)? {+ guard let points = currentSeries.first?.points.suffix(limit), let first = points.first, let last = points.last,+ let start = ChartDates.bucketStart(first.at), let end = ChartDates.bucketStart(last.at)+ else {+ return nil+ }+ return (ChartDates.axisLabel(start, interval: interval), ChartDates.axisLabel(end, interval: interval))+ }+}++enum ChartAge {+ static let staleAfter: TimeInterval = 60 * 60++ /// `statusLine` in src/features/views/freshness.ts.+ static func text(dataDate: Date, at now: Date) -> String {+ let age = max(0, now.timeIntervalSince(dataDate))+ if age < 60 {+ return "Updated just now"+ }+ let minutes = max(1, Int(age / 60))+ if minutes < 60 {+ return "Updated \(minutes) min ago"+ }+ let hours = minutes / 60+ if hours < 24 {+ return "Updated \(hours) h ago"+ }+ let days = hours / 24+ return days == 1 ? "Updated 1 day ago" : "Updated \(days) days ago"+ }++ static func isStale(dataDate: Date, at now: Date) -> Bool {+ now.timeIntervalSince(dataDate) > staleAfter+ }+}++/// The gallery's preview: made-up numbers, never a user's.+enum ChartSample {+ static func snapshot(+ pinId: String, value: String, delta: Double, deltaText: String, values: [Double], now: Date+ ) -> ChartSnapshot {+ let calendar = Calendar(identifier: .gregorian)+ let days = values.indices.map { index in+ ChartDates.dayLabel(calendar.date(byAdding: .day, value: index - values.count + 1, to: now) ?? now)+ }+ let previous = values.map { ($0 * 0.88).rounded() }+ let computed = now.addingTimeInterval(-12 * 60)+ return ChartSnapshot(+ version: ChartSnapshot.supportedVersion,+ pinId: pinId,+ fetchedAt: (now.timeIntervalSince1970 * 1000).rounded(),+ lastRefreshAt: ISO8601DateFormatter().string(from: computed),+ rangeLabel: "Last 14 days",+ intervalLabel: "day",+ valueText: value,+ deltaPercent: delta,+ deltaText: deltaText,+ deltaBasis: "vs previous period",+ series: [+ ChartSeries(label: "Sample", points: zip(days, values).map { ChartPoint(at: $0, value: $1) }, previous: false),+ ChartSeries(label: "Previous period", points: zip(days, previous).map { ChartPoint(at: $0, value: $1) }, previous: true),+ ],+ chartKind: .line+ )+ }++ static func content(family: ChartFamily, now: Date) -> ChartContent {+ let links = ChartLinks(scheme: "posthog", family: family)+ let signups = snapshot(+ pinId: "sample-signups", value: "1,284", delta: 12, deltaText: "12%",+ values: [72, 80, 77, 85, 91, 88, 79, 94, 98, 90, 101, 97, 108, 124], now: now+ )+ let primary = ChartSlot(title: "Signups", state: .ready(signups), link: links.root)+ guard family == .large else { return ChartContent(primary: primary, extras: []) }+ let active = snapshot(+ pinId: "sample-active", value: "342", delta: 4.1, deltaText: "4.1%",+ values: [310, 322, 318, 330, 326, 335, 329, 338, 331, 340, 336, 344, 339, 342], now: now+ )+ let pageviews = snapshot(+ pinId: "sample-pageviews", value: "18,902", delta: -3.2, deltaText: "3.2%",+ values: [19800, 19650, 19900, 19500, 19620, 19400, 19300, 19450, 19200, 19100, 19250, 19000, 18950, 18902], now: now+ )+ return ChartContent(primary: primary, extras: [+ ChartSlot(title: "Daily active users", state: .ready(active), link: links.root),+ ChartSlot(title: "Pageviews", state: .ready(pageviews), link: links.root),+ ])+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartStore.swift b/products/mobile/targets/HedgehogWidget/ChartStore.swiftnew file mode 100644index 000000000000..71b1b066bd83--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartStore.swift@@ -0,0 +1,102 @@+import Foundation+import Security++/// The chart widget's side of the store it shares with the app (modules/chart-widget/ios/ChartWidgetModule.swift).+/// Foundation and Security only, so scripts/check_chart_widget.swift can compile it.+enum ChartStore {+ static let catalogKey = "chart.catalog"+ static let keychainService = "com.posthog.code.mobile.chart-widget"+ static let keychainAccount = "credentials"++ static func snapshotKey(_ pinId: String) -> String { "chart.snapshot.\(pinId)" }+ static func snapshotErrorKey(_ pinId: String) -> String { "chart.snapshotError.\(pinId)" }+ static func pinProjectKey(_ pinId: String) -> String { "chart.pinProject.\(pinId)" }++ static var defaults: UserDefaults? { UserDefaults(suiteName: AppGroup.suiteName) }++ static func decodeCatalog(_ json: String) -> ChartCatalog? {+ guard let catalog = try? JSONDecoder().decode(ChartCatalog.self, from: Data(json.utf8)),+ catalog.version == ChartCatalog.supportedVersion+ else {+ return nil+ }+ return catalog+ }++ static func catalog(store: UserDefaults? = ChartStore.defaults) -> ChartCatalog? {+ store?.string(forKey: catalogKey).flatMap(decodeCatalog)+ }++ static func snapshot(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartSnapshot? {+ guard let json = store?.string(forKey: snapshotKey(pinId)),+ let snapshot = try? JSONDecoder().decode(ChartSnapshot.self, from: Data(json.utf8)),+ snapshot.version == ChartSnapshot.supportedVersion+ else {+ return nil+ }+ return snapshot+ }++ static func save(_ snapshot: ChartSnapshot, store: UserDefaults? = ChartStore.defaults) {+ guard let data = try? JSONEncoder().encode(snapshot), let json = String(data: data, encoding: .utf8) else {+ return+ }+ store?.set(json, forKey: snapshotKey(snapshot.pinId))+ store?.removeObject(forKey: snapshotErrorKey(snapshot.pinId))+ }++ static func error(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartSnapshotError? {+ guard let json = store?.string(forKey: snapshotErrorKey(pinId)) else { return nil }+ return try? JSONDecoder().decode(ChartSnapshotError.self, from: Data(json.utf8))+ }++ static func save(_ error: ChartSnapshotError, pinId: String, store: UserDefaults? = ChartStore.defaults) {+ guard let data = try? JSONEncoder().encode(error), let json = String(data: data, encoding: .utf8) else {+ return+ }+ store?.set(json, forKey: snapshotErrorKey(pinId))+ }++ static func pinProject(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartPinProject? {+ guard let json = store?.string(forKey: pinProjectKey(pinId)) else { return nil }+ return try? JSONDecoder().decode(ChartPinProject.self, from: Data(json.utf8))+ }++ /// Writes only a changed marker, because every timeline call resolves its pins again.+ static func save(_ project: ChartPinProject, pinId: String, store: UserDefaults? = ChartStore.defaults) {+ guard pinProject(pinId: pinId, store: store) != project,+ let data = try? JSONEncoder().encode(project), let json = String(data: data, encoding: .utf8)+ else {+ return+ }+ store?.set(json, forKey: pinProjectKey(pinId))+ }++ static func decodeCredentials(_ data: Data) -> ChartCredentials? {+ guard let credentials = try? JSONDecoder().decode(ChartCredentials.self, from: data),+ credentials.version == ChartCredentials.supportedVersion,+ !credentials.accessToken.isEmpty+ else {+ return nil+ }+ return credentials+ }++ /// The app writes the item with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, so a refresh while the phone is+ /// locked still reads it. An App Group id is also a keychain access group.+ static func credentials(accessGroup: String = AppGroup.suiteName) -> ChartCredentials? {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: keychainService,+ kSecAttrAccount as String: keychainAccount,+ kSecAttrAccessGroup as String: accessGroup,+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]+ var item: CFTypeRef?+ guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let data = item as? Data else {+ return nil+ }+ return decodeCredentials(data)+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swift b/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swiftnew file mode 100644index 000000000000..6fbc75a0c2b8--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swift@@ -0,0 +1,78 @@+import Foundation+import WidgetKit++struct ChartEntry: TimelineEntry {+ let date: Date+ let content: ChartContent+}++struct ChartTimelineProvider: AppIntentTimelineProvider {+ /// The second entry only moves the age label on; it reads nothing.+ private static let ageStep: TimeInterval = 15 * 60+ private static let reloadAfter: TimeInterval = 30 * 60++ func placeholder(in context: Context) -> ChartEntry {+ let now = Date()+ return ChartEntry(date: now, content: ChartSample.content(family: Self.family(context), now: now))+ }++ func snapshot(for configuration: ChartWidgetIntent, in context: Context) async -> ChartEntry {+ let now = Date()+ if context.isPreview {+ return ChartEntry(date: now, content: ChartSample.content(family: Self.family(context), now: now))+ }+ return ChartEntry(date: now, content: Self.content(configuration, family: Self.family(context), store: Self.storeState(), now: now))+ }++ func timeline(for configuration: ChartWidgetIntent, in context: Context) async -> Timeline<ChartEntry> {+ let now = Date()+ let family = Self.family(context)+ let (primary, extras) = Self.selections(configuration, family: family)+ let before = Self.storeState()+ for marker in ChartResolver.pinProjects([primary].compactMap { $0 } + extras, catalog: before.catalog) {+ ChartStore.save(marker.project, pinId: marker.pinId)+ }+ if let credentials = before.credentials {+ let pins = ChartResolver.pinsToFetch([primary].compactMap { $0 } + extras, store: before, now: now)+ await withTaskGroup(of: Void.self) { group in+ for pin in pins {+ group.addTask { await ChartRefresh.shared.refresh(pin, credentials: credentials, now: now) }+ }+ }+ }+ let content = Self.content(configuration, family: family, store: Self.storeState(), now: now)+ let entries = [now, now.addingTimeInterval(Self.ageStep)].map { ChartEntry(date: $0, content: content) }+ return Timeline(entries: entries, policy: .after(now.addingTimeInterval(Self.reloadAfter)))+ }++ private static func family(_ context: Context) -> ChartFamily {+ switch context.family {+ case .systemSmall: .small+ case .systemLarge, .systemExtraLarge: .large+ default: .medium+ }+ }++ private static func selections(_ configuration: ChartWidgetIntent, family: ChartFamily) -> (ChartSelection?, [ChartSelection]) {+ let primary = configuration.pin.map { ChartSelection(id: $0.id, name: $0.name) }+ let extras = (configuration.extraPins ?? []).map { ChartSelection(id: $0.id, name: $0.name) }+ return ChartResolver.selections(primary: primary, extras: extras, family: family)+ }++ private static func storeState() -> ChartStoreState {+ let defaults = ChartStore.defaults+ return ChartStoreState(+ credentials: ChartStore.credentials(),+ catalog: ChartStore.catalog(store: defaults),+ snapshot: { ChartStore.snapshot(pinId: $0, store: defaults) },+ error: { ChartStore.error(pinId: $0, store: defaults) },+ pinProject: { ChartStore.pinProject(pinId: $0, store: defaults) }+ )+ }++ private static func content(_ configuration: ChartWidgetIntent, family: ChartFamily, store: ChartStoreState, now: Date) -> ChartContent {+ let (primary, extras) = selections(configuration, family: family)+ let links = ChartLinks(scheme: ChartLinks.scheme(forAppId: AppGroup.appId), family: family)+ return ChartResolver.content(primary: primary, extras: extras, store: store, links: links, now: now)+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartViews.swift b/products/mobile/targets/HedgehogWidget/ChartViews.swiftnew file mode 100644index 000000000000..981f66a545ac--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartViews.swift@@ -0,0 +1,599 @@+import SwiftUI+import WidgetKit++/// Values from src/ui/theme.ts, src/ui/tokens.ts and src/ui/chart/palette.ts, so the widget matches the Views tab.+struct ChartColors {+ let surface: Color+ let ink: Color+ let secondary: Color+ let tertiary: Color+ let hairline: Color+ let barNeutral: Color+ let green: Color+ let red: Color+ let orange: Color+ let previous: Color+ let series: [Color]++ func seriesColor(_ index: Int) -> Color {+ series[index % series.count]+ }++ static func of(_ scheme: ColorScheme) -> ChartColors {+ scheme == .dark ? dark : light+ }++ static let light = ChartColors(+ surface: Color(hex: 0xFFFFFF), ink: Color(hex: 0x1F1F1C), secondary: Color(hex: 0x6B6B65),+ tertiary: Color(hex: 0x8A8A84), hairline: Color(hex: 0xE4E4E0), barNeutral: Color(hex: 0xD6D6D1),+ green: Color(hex: 0x1A7F37), red: Color(hex: 0xCF222E), orange: Color(hex: 0xF54E00), previous: Color(hex: 0xA3A39D),+ series: [0x1D4AFF, 0x621DA6, 0x42827E, 0xCE0E74, 0xF14F58].map { Color(hex: $0) }+ )++ static let dark = ChartColors(+ surface: Color(hex: 0x23262E), ink: Color(hex: 0xF4F4F2), secondary: Color(hex: 0xB4B5BA),+ tertiary: Color(hex: 0x8C8E95), hairline: Color(hex: 0x2E3139), barNeutral: Color(hex: 0x5E6068),+ green: Color(hex: 0x3FB950), red: Color(hex: 0xF85149), orange: Color(hex: 0xFF6B35), previous: Color(hex: 0x6F727A),+ series: [0x6B8AFF, 0x7F26D9, 0x3E7A76, 0xBF0D6C, 0xF0474F].map { Color(hex: $0) }+ )+}++private extension Color {+ init(hex: UInt32) {+ self.init(+ .sRGB,+ red: Double((hex >> 16) & 0xFF) / 255,+ green: Double((hex >> 8) & 0xFF) / 255,+ blue: Double(hex & 0xFF) / 255,+ opacity: 1+ )+ }+}++struct ChartSurface: View {+ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ ChartColors.of(colorScheme).surface+ }+}++private enum PointWindow {+ static let compact = 14+ static let large = TrendsParser.pointLimit+}++struct ChartWidgetView: View {+ let entry: ChartEntry++ @Environment(\.widgetFamily) private var family+ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ let colors = ChartColors.of(colorScheme)+ Group {+ switch family {+ case .systemSmall:+ SmallChartLayout(slot: entry.content.primary, now: entry.date, colors: colors)+ case .systemLarge, .systemExtraLarge:+ LargeChartLayout(content: entry.content, now: entry.date, colors: colors)+ default:+ MediumChartLayout(content: entry.content, now: entry.date, colors: colors)+ }+ }+ .widgetURL(entry.content.primary.link)+ }+}++private struct SmallChartLayout: View {+ let slot: ChartSlot+ let now: Date+ let colors: ChartColors++ var body: some View {+ if let snapshot = slot.snapshot {+ VStack(alignment: .leading, spacing: 2) {+ PinTitle(text: slot.title, colors: colors)+ if let value = snapshot.valueText {+ ValueText(text: value, size: 26, colors: colors)+ HStack(spacing: 4) {+ DeltaPill(snapshot: snapshot, colors: colors)+ RangeText(text: snapshot.rangeLabel, colors: colors)+ }+ } else {+ RangeText(text: snapshot.rangeLabel, colors: colors)+ }+ PlotArea(snapshot: snapshot, window: PointWindow.compact, kind: .line, style: .sparkline, colors: colors)+ .padding(.top, 4)+ AgeLabel(dataDate: snapshot.dataDate, now: now, colors: colors)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ } else {+ StateView(slot: slot, colors: colors)+ }+ }+}++private struct MediumChartLayout: View {+ let content: ChartContent+ let now: Date+ let colors: ChartColors++ var body: some View {+ if let snapshot = content.primary.snapshot {+ ChartPanel(+ title: content.primary.title, snapshot: snapshot, window: PointWindow.compact, axisLabels: false,+ dataDate: content.oldestData, now: now, colors: colors+ )+ } else {+ StateView(slot: content.primary, colors: colors)+ }+ }+}++private struct LargeChartLayout: View {+ let content: ChartContent+ let now: Date+ let colors: ChartColors++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ if let snapshot = content.primary.snapshot {+ ChartPanel(+ title: content.primary.title, snapshot: snapshot, window: PointWindow.large, axisLabels: true,+ dataDate: content.oldestData, now: now, colors: colors+ )+ } else {+ StateView(slot: content.primary, colors: colors)+ }+ if !content.extras.isEmpty {+ HStack(spacing: 8) {+ ForEach(Array(content.extras.enumerated()), id: \.offset) { _, slot in+ Link(destination: slot.link) {+ NumberTile(slot: slot, colors: colors)+ }+ }+ }+ .frame(height: 104)+ if content.primary.snapshot == nil, let dataDate = content.oldestData {+ HStack {+ Spacer(minLength: 0)+ AgeLabel(dataDate: dataDate, now: now, colors: colors)+ }+ }+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ }+}++private struct ChartPanel: View {+ let title: String?+ let snapshot: ChartSnapshot+ let window: Int+ let axisLabels: Bool+ let dataDate: Date?+ let now: Date+ let colors: ChartColors++ var body: some View {+ VStack(alignment: .leading, spacing: 4) {+ HStack(spacing: 5) {+ Image(systemName: snapshot.chartKind == .bar ? "chart.bar.fill" : "chart.xyaxis.line")+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(colors.secondary)+ PinTitle(text: title, colors: colors)+ }+ if let value = snapshot.valueText {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ ValueText(text: value, size: 26, colors: colors)+ .layoutPriority(1)+ DeltaPill(snapshot: snapshot, colors: colors)+ if snapshot.pillText != nil, let basis = snapshot.deltaBasis {+ Text(basis)+ .font(.system(size: 10.5))+ .foregroundStyle(colors.secondary)+ .lineLimit(1)+ }+ }+ }+ PlotArea(snapshot: snapshot, window: window, kind: snapshot.chartKind, style: .chart, colors: colors)+ .padding(.top, 2)+ if axisLabels, let ends = snapshot.axisLabels(limit: window) {+ HStack {+ Text(ends.0)+ Spacer(minLength: 8)+ Text(ends.1)+ }+ .font(.system(size: 10.5))+ .foregroundStyle(colors.tertiary)+ .lineLimit(1)+ }+ HStack(spacing: 8) {+ RangeText(text: snapshot.rangeLabel, colors: colors)+ Spacer(minLength: 0)+ if let dataDate {+ AgeLabel(dataDate: dataDate, now: now, colors: colors)+ }+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ }+}++private struct NumberTile: View {+ let slot: ChartSlot+ let colors: ChartColors++ var body: some View {+ VStack(alignment: .leading, spacing: 2) {+ PinTitle(text: slot.title, colors: colors)+ switch slot.state {+ case .ready(let snapshot):+ RangeText(text: snapshot.rangeLabel, colors: colors)+ HStack(alignment: .firstTextBaseline, spacing: 4) {+ ValueText(text: snapshot.valueText ?? "", size: 20, colors: colors)+ DeltaPill(snapshot: snapshot, colors: colors)+ }+ PlotArea(snapshot: snapshot, window: PointWindow.compact, kind: .line, style: .sparkline, colors: colors)+ case .loading:+ Text("Loading…")+ .font(.system(size: 12))+ .foregroundStyle(colors.secondary)+ PlaceholderSparkline(colors: colors)+ case .message(let text, let detail):+ Text(text)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(colors.secondary)+ .lineLimit(3)+ if let detail {+ Text(detail)+ .font(.system(size: 10.5))+ .foregroundStyle(colors.secondary)+ .lineLimit(2)+ }+ Spacer(minLength: 0)+ }+ }+ .padding(10)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).stroke(colors.hairline, lineWidth: 1))+ }+}++private struct StateView: View {+ let slot: ChartSlot+ let colors: ChartColors++ var body: some View {+ VStack(spacing: 4) {+ if let title = slot.title {+ Text(title)+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(colors.ink)+ .lineLimit(1)+ }+ switch slot.state {+ case .message(let text, let detail):+ Text(text)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(colors.secondary)+ if let detail {+ Text(detail)+ .font(.system(size: 12))+ .foregroundStyle(colors.secondary)+ }+ case .loading:+ Text("Loading…")+ .font(.system(size: 12))+ .foregroundStyle(colors.secondary)+ PlaceholderSparkline(colors: colors)+ .frame(maxWidth: 120, maxHeight: 28)+ .padding(.top, 4)+ case .ready:+ EmptyView()+ }+ }+ .multilineTextAlignment(.center)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+}++private struct PinTitle: View {+ let text: String?+ let colors: ChartColors++ var body: some View {+ Text(text ?? "")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(colors.ink)+ .lineLimit(1)+ }+}++private struct ValueText: View {+ let text: String+ let size: CGFloat+ let colors: ChartColors++ var body: some View {+ Text(text)+ .font(.system(size: size, weight: .bold))+ .monospacedDigit()+ .foregroundStyle(colors.ink)+ .lineLimit(1)+ .minimumScaleFactor(0.5)+ }+}++private struct RangeText: View {+ let text: String?+ let colors: ChartColors++ var body: some View {+ if let text {+ Text(text)+ .font(.system(size: 10.5))+ .foregroundStyle(colors.secondary)+ .lineLimit(1)+ }+ }+}++private struct AgeLabel: View {+ let dataDate: Date+ let now: Date+ let colors: ChartColors++ var body: some View {+ Text(ChartAge.text(dataDate: dataDate, at: now))+ .font(.system(size: 10.5))+ .foregroundStyle(ChartAge.isStale(dataDate: dataDate, at: now) ? colors.orange : colors.tertiary)+ .lineLimit(1)+ }+}++private struct DeltaPill: View {+ let snapshot: ChartSnapshot+ let colors: ChartColors++ var body: some View {+ if let text = snapshot.pillText {+ let direction = snapshot.deltaPercent ?? 0+ let tint = direction > 0 ? colors.green : direction < 0 ? colors.red : colors.secondary+ Text(text)+ .font(.system(size: 10.5, weight: .semibold))+ .monospacedDigit()+ .foregroundStyle(tint)+ .lineLimit(1)+ .fixedSize()+ .padding(.horizontal, 5)+ .padding(.vertical, 1.5)+ .background(tint.opacity(0.12), in: Capsule())+ }+ }+}++private enum PlotStyle {+ /// Floats above the floor, so a flat-ish series reads as a line (src/ui/chart/Sparkline.tsx).+ case sparkline+ /// Axis scaling with three grid lines (`yAxisTicks` in src/ui/chart/chartMath.ts).+ case chart+}++private struct PlotArea: View {+ let snapshot: ChartSnapshot+ let window: Int+ let kind: ChartKind+ let style: PlotStyle+ let colors: ChartColors++ var body: some View {+ if snapshot.hasPoints {+ Plot(series: snapshot.trimmed(to: window), kind: kind, style: style, colors: colors)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .accessibilityHidden(true)+ } else {+ Text("No data for this range")+ .font(.system(size: 10.5))+ .foregroundStyle(colors.tertiary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }+}++private struct PlaceholderSparkline: View {+ let colors: ChartColors++ private static let wave: [ChartSeries] = [+ ChartSeries(+ label: "",+ points: [0.5, 0.62, 0.55, 0.7, 0.64, 0.78, 0.7, 0.84, 0.76, 0.9].enumerated().map {+ ChartPoint(at: String($0.offset), value: $0.element)+ },+ previous: false+ ),+ ]++ var body: some View {+ Plot(series: Self.wave, kind: .line, style: .sparkline, colors: colors, tint: colors.hairline, fillsArea: false)+ .accessibilityHidden(true)+ }+}++private struct Plot: View {+ let series: [ChartSeries]+ let kind: ChartKind+ let style: PlotStyle+ let colors: ChartColors+ var tint: Color? = nil+ var fillsArea = true++ private var current: [ChartSeries] { series.filter { !$0.previous } }+ private var previous: [ChartSeries] { kind == .line && style == .chart ? series.filter(\.previous) : [] }++ var body: some View {+ GeometryReader { proxy in+ let scale = PlotScale(series: current + previous, kind: kind, style: style, size: proxy.size)+ ZStack {+ if style == .chart {+ scale.gridPath().stroke(colors.hairline, lineWidth: 1)+ }+ if kind == .bar && style == .chart {+ bars(scale)+ } else {+ lines(scale)+ }+ }+ }+ }++ @ViewBuilder+ private func lines(_ scale: PlotScale) -> some View {+ if fillsArea, current.count == 1, let only = current.first {+ scale.areaPath(only.points).fill(+ LinearGradient(+ colors: [colors.seriesColor(0).opacity(0.18), colors.seriesColor(0).opacity(0.02)],+ startPoint: .top, endPoint: .bottom+ )+ )+ }+ ForEach(Array(previous.enumerated()), id: \.offset) { _, line in+ scale.linePath(line.points)+ .stroke(colors.previous, style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round, dash: [3, 3]))+ }+ ForEach(Array(current.enumerated()), id: \.offset) { index, line in+ scale.linePath(line.points)+ .stroke(tint ?? colors.seriesColor(index), style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))+ }+ }++ @ViewBuilder+ private func bars(_ scale: PlotScale) -> some View {+ if current.count == 1, let only = current.first {+ let last = only.points.count - 1+ scale.barsPath(only.points, series: 0, of: 1) { $0 != last }.fill(colors.barNeutral)+ scale.barsPath(only.points, series: 0, of: 1) { $0 == last }.fill(colors.ink)+ } else {+ ForEach(Array(current.enumerated()), id: \.offset) { index, bar in+ scale.barsPath(bar.points, series: index, of: current.count) { _ in true }.fill(colors.seriesColor(index))+ }+ }+ }+}++private struct PlotScale {+ let size: CGSize+ let count: Int+ let low: Double+ let high: Double+ /// Room above and below, so a 2pt stroke at the extremes is not clipped.+ let inset: CGFloat = 2++ init(series: [ChartSeries], kind: ChartKind, style: PlotStyle, size: CGSize) {+ self.size = size+ count = series.first { !$0.previous }?.points.count ?? 0+ let values = series.flatMap { $0.points.compactMap(\.value) }+ (low, high) = Self.domain(values, kind: kind, style: style)+ }++ private static func domain(_ values: [Double], kind: ChartKind, style: PlotStyle) -> (Double, Double) {+ guard let minimum = values.min(), let maximum = values.max() else { return (0, 1) }+ let span = maximum - minimum+ var low: Double+ var high: Double+ switch (style, kind) {+ case (.sparkline, _):+ low = minimum >= 0 ? max(0, minimum - span * 0.6) : minimum - span * 0.6+ high = maximum + span * 0.1+ case (.chart, .bar):+ low = min(0, minimum)+ high = max(0, maximum)+ case (.chart, .line):+ let pad = span > 0 ? span * 0.05 : (abs(maximum) * 0.1 == 0 ? 1 : abs(maximum) * 0.1)+ low = minimum - pad+ high = maximum + pad+ if minimum >= 0 && low < 0 {+ low = 0+ }+ }+ if high <= low {+ // A flat series sits in the middle.+ low -= 1+ high += 1+ }+ return (low, high)+ }++ func x(_ index: Int) -> CGFloat {+ count <= 1 ? size.width / 2 : CGFloat(index) / CGFloat(count - 1) * size.width+ }++ func y(_ value: Double) -> CGFloat {+ let fraction = (value - low) / (high - low)+ return inset + (1 - CGFloat(fraction)) * max(0, size.height - inset * 2)+ }++ func gridPath() -> Path {+ var path = Path()+ for fraction in [0.0, 0.5, 1.0] {+ let y = inset + CGFloat(fraction) * max(0, size.height - inset * 2)+ path.move(to: CGPoint(x: 0, y: y))+ path.addLine(to: CGPoint(x: size.width, y: y))+ }+ return path+ }++ func linePath(_ points: [ChartPoint]) -> Path {+ var path = Path()+ var pen = false+ for (index, point) in points.enumerated() {+ guard let value = point.value else {+ pen = false+ continue+ }+ let location = CGPoint(x: x(index), y: y(value))+ if pen {+ path.addLine(to: location)+ } else {+ path.move(to: location)+ }+ pen = true+ }+ return path+ }++ func areaPath(_ points: [ChartPoint]) -> Path {+ let drawn = points.enumerated().compactMap { index, point in point.value.map { CGPoint(x: x(index), y: y($0)) } }+ guard let first = drawn.first, let last = drawn.last, drawn.count > 1 else { return Path() }+ var path = Path()+ path.move(to: first)+ drawn.dropFirst().forEach { path.addLine(to: $0) }+ path.addLine(to: CGPoint(x: last.x, y: size.height))+ path.addLine(to: CGPoint(x: first.x, y: size.height))+ path.closeSubpath()+ return path+ }++ func barsPath(_ points: [ChartPoint], series: Int, of seriesCount: Int, including: (Int) -> Bool) -> Path {+ guard count > 0 else { return Path() }+ let slot = size.width / CGFloat(count)+ let group = slot * 0.72+ let width = group / CGFloat(max(1, seriesCount))+ let gap = seriesCount > 1 ? min(1, width * 0.2) : 0+ let baseline = y(min(max(0, low), high))+ var path = Path()+ for (index, point) in points.enumerated() where including(index) {+ guard let value = point.value else { continue }+ let top = y(value)+ let rect = CGRect(+ x: slot * CGFloat(index) + (slot - group) / 2 + width * CGFloat(series),+ y: min(top, baseline),+ width: max(0.5, width - gap),+ height: max(0.5, abs(baseline - top))+ )+ path.addRoundedRect(in: rect, cornerSize: CGSize(width: min(2, rect.width / 2), height: min(2, rect.height / 2)))+ }+ return path+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartWidget.swift b/products/mobile/targets/HedgehogWidget/ChartWidget.swiftnew file mode 100644index 000000000000..483d293ae8e4--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartWidget.swift@@ -0,0 +1,18 @@+import SwiftUI+import WidgetKit++struct ChartWidget: Widget {+ let kind = "ChartWidget"++ var body: some WidgetConfiguration {+ AppIntentConfiguration(kind: kind, intent: ChartWidgetIntent.self, provider: ChartTimelineProvider()) { entry in+ ChartWidgetView(entry: entry)+ .containerBackground(for: .widget) {+ ChartSurface()+ }+ }+ .configurationDisplayName("Chart")+ .description("A pinned insight from your Views tab, with its latest value.")+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swift b/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swiftnew file mode 100644index 000000000000..94ebff374c3f--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swift@@ -0,0 +1,83 @@+import AppIntents+import WidgetKit++/// A pin from the catalog the app writes (`chart.catalog`). The configuration stores its id.+struct PinEntity: AppEntity {+ static var typeDisplayRepresentation: TypeDisplayRepresentation { "Pin" }+ static var defaultQuery: PinQuery { PinQuery() }++ let id: String+ let name: String+ let subtitle: String?++ init(id: String, name: String, subtitle: String?) {+ self.id = id+ self.name = name+ self.subtitle = subtitle+ }++ init(pin: ChartPin) {+ self.init(id: pin.id, name: pin.name, subtitle: pin.subtitle)+ }++ var displayRepresentation: DisplayRepresentation {+ guard let subtitle, !subtitle.isEmpty else {+ return DisplayRepresentation(title: "\(name)")+ }+ return DisplayRepresentation(title: "\(name)", subtitle: "\(subtitle)")+ }+}++struct PinQuery: EntityStringQuery {+ private var pickerPins: [PinEntity] {+ (ChartStore.catalog()?.pickerPins ?? []).map(PinEntity.init(pin:))+ }++ /// A stored id that left the catalog still resolves, so the widget can say the pin is gone instead of+ /// asking to choose one.+ func entities(for identifiers: [PinEntity.ID]) async throws -> [PinEntity] {+ let catalog = ChartStore.catalog()+ return identifiers.map { id in+ catalog?.pin(id: id).map(PinEntity.init(pin:)) ?? PinEntity(id: id, name: "This pin", subtitle: nil)+ }+ }++ func entities(matching string: String) async throws -> [PinEntity] {+ pickerPins.filter {+ $0.name.localizedCaseInsensitiveContains(string) || ($0.subtitle?.localizedCaseInsensitiveContains(string) ?? false)+ }+ }++ func suggestedEntities() async throws -> [PinEntity] {+ pickerPins+ }++ func defaultResult() async -> PinEntity? {+ pickerPins.first+ }+}++struct ChartWidgetIntent: WidgetConfigurationIntent {+ static var title: LocalizedStringResource { "Chart" }+ static var description: IntentDescription { "Choose a pin from your Views tab." }++ @Parameter(title: "Pin")+ var pin: PinEntity?++ @Parameter(title: "More pins", description: "Shown on the large widget")+ var extraPins: [PinEntity]?++ // Only the large widget draws the extra pins, so the other sizes do not ask for them.+ static var parameterSummary: some ParameterSummary {+ When(widgetFamily: .equalTo, .systemLarge) {+ Summary {+ \.$pin+ \.$extraPins+ }+ } otherwise: {+ Summary {+ \.$pin+ }+ }+ }+}diff --git a/products/mobile/targets/HedgehogWidget/Choreography.swift b/products/mobile/targets/HedgehogWidget/Choreography.swiftindex 45b39621c010..ab8251bec10b 100644--- a/products/mobile/targets/HedgehogWidget/Choreography.swift+++ b/products/mobile/targets/HedgehogWidget/Choreography.swift@@ -117,14 +117,7 @@ struct Choreography: Codable {}enum SharedStore {- // app.config.ts names the App Group "group." plus the app's bundle id, and this extension's bundle id is the- // app's id plus ".HedgehogWidget", so each app variant reads its own store.- static let suiteName: String = {- let extensionSuffix = ".HedgehogWidget"- let widgetId = Bundle.main.bundleIdentifier ?? "com.posthog.code.mobile\(extensionSuffix)"- let appId = widgetId.hasSuffix(extensionSuffix) ? String(widgetId.dropLast(extensionSuffix.count)) : widgetId- return "group.\(appId)"- }()+ static let suiteName = AppGroup.suiteNamestatic let choreographyKey = "choreography"static var defaults: UserDefaults? { UserDefaults(suiteName: suiteName) }diff --git a/products/mobile/targets/HedgehogWidget/HedgehogWidgetBundle.swift b/products/mobile/targets/HedgehogWidget/HedgehogWidgetBundle.swiftindex acebbb1d6b0d..a1a60f78832c 100644--- a/products/mobile/targets/HedgehogWidget/HedgehogWidgetBundle.swift+++ b/products/mobile/targets/HedgehogWidget/HedgehogWidgetBundle.swift@@ -5,5 +5,6 @@ import WidgetKitstruct HedgehogWidgetBundle: WidgetBundle {var body: some Widget {HedgehogWidget()+ ChartWidget()}}diff --git a/products/mobile/targets/HedgehogWidget/TrendsParser.swift b/products/mobile/targets/HedgehogWidget/TrendsParser.swiftnew file mode 100644index 000000000000..0bf411a6330c--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/TrendsParser.swift@@ -0,0 +1,747 @@+import Foundation++// Mirrors the app's trends adapter, so a pin shows the same number on the widget as in Views:+// - src/model/adapters/insightSnapshot.ts: trendsEntries, seriesViews, pointsOf, compareOf, capabilitiesOf, numberParts,+// inProgressFrom;+// - src/model/adapters/insightFormatting.ts: insightValueFormat, formatInsightValue;+// - src/features/views/snapshotChart.ts: snapshotChartSeries, deltaBasisText, resolvedRangeText, pinRangeLabel;+// - src/features/views/rangePresets.ts: RANGE_PRESETS, rangeLabel, formatRangeSpan.+// A change to one of those needs the same change here and in the Android widget.++typealias JSONObject = [String: Any]++enum TrendsParser {+ enum Failure: Error, Equatable {+ case notJSON, notTrends, noResult+ }++ static let pointLimit = 60+ static let seriesLimit = 5++ enum Interval: String {+ case hour, day, week, month++ static func of(_ value: Any?) -> Interval {+ (value as? String).flatMap(Interval.init(rawValue:)) ?? .day+ }++ var length: TimeInterval {+ switch self {+ case .hour: 3600+ case .day: 86400+ case .week: 7 * 86400+ case .month: 31 * 86400+ }+ }+ }++ struct Point {+ let at: String+ /// NaN for a bucket without a number.+ let value: Double+ }++ enum Compare {+ case current, previous+ }++ indirect enum Breakdown: Equatable {+ case none+ case text(String)+ case number(Double)+ case list([Breakdown])+ }++ struct SeriesView {+ let label: String+ let points: [Point]+ let compare: Compare?+ let seriesIndex: Double+ let breakdown: Breakdown+ }++ struct ValueFormat: Equatable {+ var style: String? = nil+ var prefix = ""+ var suffix = ""+ var decimalPlaces: Int? = nil+ var minDecimalPlaces: Int? = nil+ }++ enum DeltaBasis {+ case compare, previousBucket+ }++ enum DeltaUnit {+ case percent, points+ }++ struct Delta {+ let previous: Double+ let change: Double+ let percent: Double?+ let unit: DeltaUnit+ let basis: DeltaBasis+ let previousAt: String?+ }++ struct NumberParts {+ let value: Double+ let valueAt: String?+ let delta: Delta?+ }++ struct ResolvedRange {+ let from: String+ let to: String+ }++ static func snapshot(data: Data, pinId: String, now: Date) throws -> ChartSnapshot {+ guard let response = (try? JSONSerialization.jsonObject(with: data)) as? JSONObject else {+ throw Failure.notJSON+ }+ return try snapshot(response: response, pinId: pinId, now: now)+ }++ /// The snapshot of one good insight response: a `result` and no `query_status.error`, which the caller checks.+ static func snapshot(response: JSONObject, pinId: String, now: Date) throws -> ChartSnapshot {+ let query = response["query"]+ guard let source = sourceOf(query), source["kind"] as? String == "TrendsQuery" else {+ throw Failure.notTrends+ }+ guard let result = response["result"] as? [Any] else {+ throw Failure.noResult+ }+ let entries = result.compactMap { $0 as? JSONObject }+ let views = seriesViews(entries)+ let interval = Interval.of(source["interval"])+ let format = valueFormat(source: source)+ let resolved = resolvedRange(response)+ let firstCurrent = views.first { $0.compare != .previous }+ let inProgress = firstCurrent.flatMap { inProgressFrom($0.points, resolved: resolved, interval: interval, now: now) }+ let number = hasNumber(query: query, source: source, entries: entries)+ ? numberParts(source: source, entries: entries, format: format, inProgressAt: inProgress)+ : nil+ let delta = number?.delta.flatMap { deltaFields($0, interval: interval) }+ return ChartSnapshot(+ version: ChartSnapshot.supportedVersion,+ pinId: pinId,+ fetchedAt: (now.timeIntervalSince1970 * 1000).rounded(),+ lastRefreshAt: response["last_refresh"] as? String,+ rangeLabel: rangeLabel(source: source, resolved: resolved, interval: interval),+ intervalLabel: interval.rawValue,+ valueText: number.map { formatValue($0.value, format) },+ deltaPercent: delta?.percent,+ deltaText: delta?.text,+ deltaBasis: delta?.basis,+ series: chartSeries(views),+ chartKind: chartKind(query: query)+ )+ }++ static func sourceOf(_ query: Any?) -> JSONObject? {+ let node = query as? JSONObject+ return (node?["source"] as? JSONObject) ?? node+ }++ static func displayOf(_ query: Any?) -> String? {+ let display = (sourceOf(query)?["trendsFilter"] as? JSONObject)?["display"] ?? (query as? JSONObject)?["display"]+ return display as? String+ }++ private static let barDisplays: Set<String> = ["ActionsBar", "ActionsStackedBar", "ActionsUnstackedBar"]++ static func chartKind(query: Any?) -> ChartKind {+ displayOf(query).map(barDisplays.contains) == true ? .bar : .line+ }++ static func seriesNodes(_ source: JSONObject) -> [JSONObject] {+ (source["series"] as? [Any])?.compactMap { $0 as? JSONObject } ?? []+ }++ static func hasBreakdown(_ source: JSONObject) -> Bool {+ let filter = source["breakdownFilter"] as? JSONObject+ return isTruthy(filter?["breakdown"]) || (filter?["breakdowns"] as? [Any])?.isEmpty == false+ }++ /// `capabilitiesOf(...).number`: a big number, or one series or one result without a breakdown. With several series+ /// the first one would stand for the whole insight.+ static func hasNumber(query: Any?, source: JSONObject, entries: [JSONObject]) -> Bool {+ if displayOf(query) == "BoldNumber" {+ return true+ }+ let current = entries.filter { compareOf($0) != .previous }+ return !hasBreakdown(source) && (seriesNodes(source).count == 1 || current.count == 1)+ }++ // Distinct-user math counts a person once per bucket, so only these maths add up over a window.+ private static let summableMath: Set<String> = ["total", "sum", "first_time_for_user", "first_matching_event_for_user"]++ static func isSummable(_ source: JSONObject) -> Bool {+ let math = seriesNodes(source).first?["math"]+ if math == nil || math is NSNull {+ return true+ }+ return (math as? String).map(summableMath.contains) ?? false+ }++ static func resolvedRange(_ response: JSONObject) -> ResolvedRange? {+ let range = response["resolved_date_range"] as? JSONObject+ guard let from = range?["date_from"] as? String, let to = range?["date_to"] as? String,+ !from.isEmpty, !to.isEmpty+ else {+ return nil+ }+ return ResolvedRange(from: from, to: to)+ }++ static func compareOf(_ entry: JSONObject) -> Compare? {+ switch entry["compare_label"] as? String {+ case "previous": .previous+ case "current": .current+ default: nil+ }+ }++ static func seriesIndexOf(_ entry: JSONObject, fallback: Double) -> Double {+ finite((entry["action"] as? JSONObject)?["order"]) ?? fallback+ }++ static func breakdownOf(_ entry: JSONObject) -> Breakdown {+ let value = entry["breakdown_value"]+ if let parts = value as? [Any] {+ var list: [Breakdown] = []+ for part in parts {+ if part is NSNull {+ list.append(.none)+ } else if let text = part as? String {+ list.append(.text(text))+ } else if let number = finite(part) {+ list.append(.number(number))+ } else {+ return .none+ }+ }+ return .list(list)+ }+ if let text = value as? String {+ return .text(text)+ }+ return finite(value).map(Breakdown.number) ?? .none+ }++ static func pointsOf(_ entry: JSONObject?) -> [Point] {+ guard let entry, let days = entry["days"] as? [Any], let data = entry["data"] as? [Any] else {+ return []+ }+ let labels = days.compactMap { $0 as? String }+ let length = min(labels.count, data.count)+ return (0..<length).map { Point(at: labels[$0], value: finite(data[$0]) ?? .nan) }+ }++ static func seriesViews(_ entries: [JSONObject]) -> [SeriesView] {+ entries.enumerated().map { index, entry in+ let seriesIndex = seriesIndexOf(entry, fallback: Double(index))+ let label = (entry["label"] as? String).map(displaySeriesLabel) ?? "Series \(Int(seriesIndex) + 1)"+ return SeriesView(+ label: label,+ points: pointsOf(entry),+ compare: compareOf(entry),+ seriesIndex: seriesIndex,+ breakdown: breakdownOf(entry)+ )+ }+ }++ private static let breakdownOther = "$$_posthog_breakdown_other_$$"+ private static let breakdownNull = "$$_posthog_breakdown_null_$$"++ static func displaySeriesLabel(_ label: String) -> String {+ label.replacingOccurrences(of: breakdownOther, with: "Other").replacingOccurrences(of: breakdownNull, with: "None")+ }++ static func breakdownLabel(_ value: Breakdown) -> String? {+ switch value {+ case .none:+ return nil+ case .text(let text):+ return text == breakdownOther ? "Other" : text == breakdownNull ? "None" : text+ case .number(let number):+ return jsNumberString(number)+ case .list(let parts):+ let labels = parts.compactMap(breakdownLabel)+ return labels.isEmpty ? nil : labels.joined(separator: ", ")+ }+ }++ static func seriesLabel(_ series: SeriesView) -> String {+ guard let breakdown = breakdownLabel(series.breakdown), !breakdown.isEmpty, !series.label.contains(breakdown) else {+ return series.label+ }+ return "\(series.label) · \(breakdown)"+ }++ static func inProgressFrom(_ points: [Point], resolved: ResolvedRange?, interval: Interval, now: Date) -> String? {+ guard let last = points.last else { return nil }+ if let resolved {+ guard let end = ChartDates.parse(resolved.to) else { return nil }+ return end > now ? last.at : nil+ }+ guard let start = ChartDates.bucketStart(last.at) else { return nil }+ return start.addingTimeInterval(interval.length) > now ? last.at : nil+ }++ static func makeDelta(+ value: Double, previous: Double, basis: DeltaBasis, previousAt: String?, format: ValueFormat+ ) -> Delta {+ let change = value - previous+ let points = format.style == "percentage" || format.style == "percentage_scaled"+ return Delta(+ previous: previous,+ change: format.style == "percentage_scaled" ? change * 100 : change,+ percent: previous == 0 ? nil : change / abs(previous) * 100,+ unit: points ? .points : .percent,+ basis: basis,+ previousAt: previousAt+ )+ }++ private static func sumFinite(_ points: [Point]) -> Double? {+ let values = points.map(\.value).filter(\.isFinite)+ return values.isEmpty ? nil : values.reduce(0, +)+ }++ /// The big number and its delta, so that both always describe the same thing:+ /// - a server aggregate (`aggregated_value`) is the value; the previous period's aggregate gives the delta;+ /// - with a compare series and summable math, the window totals;+ /// - otherwise the last complete bucket, against the same bucket of the previous period, or else the bucket before it.+ static func numberParts(+ source: JSONObject, entries: [JSONObject], format: ValueFormat, inProgressAt: String?+ ) -> NumberParts? {+ guard let current = entries.first(where: { compareOf($0) != .previous }) else { return nil }+ let currentIndex = seriesIndexOf(current, fallback: 0)+ let currentBreakdown = breakdownOf(current)+ let previousEntry = entries.first {+ compareOf($0) == .previous && seriesIndexOf($0, fallback: 0) == currentIndex && breakdownOf($0) == currentBreakdown+ }+ if let aggregate = finite(current["aggregated_value"]) {+ let previousAggregate = finite(previousEntry?["aggregated_value"])+ return NumberParts(+ value: aggregate,+ valueAt: nil,+ delta: previousAggregate.map {+ makeDelta(value: aggregate, previous: $0, basis: .compare, previousAt: nil, format: format)+ }+ )+ }+ let points = pointsOf(current)+ let previousPoints = pointsOf(previousEntry)+ if previousEntry != nil && isSummable(source) {+ guard let total = sumFinite(points) else { return nil }+ return NumberParts(+ value: total,+ valueAt: nil,+ delta: sumFinite(previousPoints).map {+ makeDelta(value: total, previous: $0, basis: .compare, previousAt: nil, format: format)+ }+ )+ }+ let complete = inProgressAt != nil && points.last?.at == inProgressAt ? Array(points.dropLast()) : points+ guard let index = complete.lastIndex(where: { $0.value.isFinite }) else { return nil }+ let point = complete[index]+ let against: Point?+ if previousEntry != nil {+ against = previousPoints.indices.contains(index) ? previousPoints[index] : nil+ } else {+ against = index > 0 ? complete[index - 1] : nil+ }+ let delta = against.flatMap { against in+ against.value.isFinite+ ? makeDelta(+ value: point.value, previous: against.value, basis: previousEntry != nil ? .compare : .previousBucket,+ previousAt: against.at, format: format+ )+ : nil+ }+ return NumberParts(value: point.value, valueAt: point.at, delta: delta)+ }++ struct DeltaFields {+ let percent: Double+ let text: String+ let basis: String+ }++ static func deltaFields(_ delta: Delta, interval: Interval) -> DeltaFields? {+ let basis = deltaBasisText(delta, interval: interval)+ if delta.change == 0 {+ return DeltaFields(percent: 0, text: "No change", basis: basis)+ }+ if delta.unit == .points {+ guard delta.change.isFinite else { return nil }+ return DeltaFields(percent: delta.change, text: String(format: "%.1f pts", abs(delta.change)), basis: basis)+ }+ guard let percent = delta.percent, percent.isFinite else { return nil }+ let size = abs(percent)+ return DeltaFields(percent: percent, text: "\(number(size, maxDigits: size >= 10 ? 0 : 1))%", basis: basis)+ }++ static func deltaBasisText(_ delta: Delta, interval: Interval) -> String {+ guard delta.basis == .previousBucket, let previousAt = delta.previousAt,+ let date = ChartDates.bucketStart(previousAt)+ else {+ return "vs previous period"+ }+ return "vs \(ChartDates.axisLabel(date, interval: interval))"+ }++ static func chartSeries(_ views: [SeriesView]) -> [ChartSeries] {+ let current = Array(views.filter { $0.compare != .previous }.prefix(seriesLimit))+ guard let reference = current.first?.points, !reference.isEmpty else { return [] }+ func aligned(_ points: [Point]) -> [ChartPoint] {+ let padded = reference.indices.map { index in+ let point = points.indices.contains(index) ? points[index] : nil+ let value = point?.value+ return ChartPoint(at: point?.at ?? reference[index].at, value: value.flatMap { $0.isFinite ? $0 : nil })+ }+ return Array(padded.suffix(pointLimit))+ }+ var result = current.map { ChartSeries(label: seriesLabel($0), points: aligned($0.points), previous: false) }+ for view in views where view.compare == .previous {+ guard let partner = current.first(where: {+ $0.seriesIndex == view.seriesIndex && $0.breakdown == view.breakdown+ }) else { continue }+ let label = current.count == 1 ? "Previous period" : "\(seriesLabel(partner)), previous period"+ result.append(ChartSeries(label: label, points: aligned(view.points), previous: true))+ }+ return result+ }++ private struct Preset {+ let label: String+ let from: String+ let to: String?+ }++ private static let presets: [Preset] = [+ Preset(label: "Today", from: "dStart", to: nil),+ Preset(label: "Yesterday", from: "-1dStart", to: "-1dEnd"),+ Preset(label: "Last 24 hours", from: "-24h", to: nil),+ Preset(label: "Last 7 days", from: "-7d", to: nil),+ Preset(label: "Last 30 days", from: "-30d", to: nil),+ Preset(label: "Last 90 days", from: "-90d", to: nil),+ Preset(label: "This week", from: "wStart", to: nil),+ Preset(label: "This month", from: "mStart", to: nil),+ Preset(label: "Last month", from: "-1mStart", to: "-1mEnd"),+ Preset(label: "This year", from: "yStart", to: nil),+ Preset(label: "All time", from: "all", to: nil),+ Preset(label: "Last hour", from: "-1h", to: nil),+ Preset(label: "Last 48 hours", from: "-48h", to: nil),+ Preset(label: "Last 14 days", from: "-14d", to: nil),+ Preset(label: "Last 180 days", from: "-180d", to: nil),+ Preset(label: "Last week", from: "-1wStart", to: "-1wEnd"),+ ]++ private static let relativePattern = try! NSRegularExpression(pattern: #"^-(\d+)([hdwmy])$"#)+ private static let relativeNouns = ["h": "hour", "d": "day", "w": "week", "m": "month", "y": "year"]++ static func rangeLabel(source: JSONObject, resolved: ResolvedRange?, interval: Interval) -> String? {+ let range = (source["dateRange"] as? JSONObject) ?? ((source["filters"] as? JSONObject)?["dateRange"] as? JSONObject)+ let dateFrom = range?["date_from"] as? String+ let dateTo = range?["date_to"] as? String+ return savedRangeLabel(dateFrom: dateFrom, dateTo: dateTo) ?? resolved.map { resolvedRangeText($0, interval: interval) }+ }++ static func savedRangeLabel(dateFrom: String?, dateTo: String?) -> String? {+ guard let dateFrom, !dateFrom.isEmpty else { return nil }+ if let preset = presets.first(where: { $0.from == dateFrom && $0.to == dateTo }) {+ return preset.label+ }+ if dateTo == nil, let groups = ChartDates.groups(relativePattern, dateFrom),+ let amount = groups[1].flatMap({ Int($0) }), let noun = groups[2].flatMap({ relativeNouns[$0] })+ {+ return amount == 1 ? "Last \(noun)" : "Last \(amount) \(noun)s"+ }+ if ChartDates.wallTime(dateFrom) != nil {+ return ChartDates.span(dateFrom, dateTo ?? dateFrom)+ }+ return nil+ }++ static func resolvedRangeText(_ range: ResolvedRange, interval: Interval) -> String {+ if interval == .hour {+ return ChartDates.span(range.from, range.to)+ }+ return ChartDates.span(String(range.from.prefix(10)), String(range.to.prefix(10)))+ }++ private static func precision(_ value: Any?) -> Int? {+ guard let number = finite(value), number == number.rounded(), number >= 0, number <= 100 else { return nil }+ return Int(number)+ }++ static func valueFormat(source: JSONObject) -> ValueFormat {+ let filter = source["trendsFilter"] as? JSONObject+ return ValueFormat(+ style: filter?["aggregationAxisFormat"] as? String,+ prefix: filter?["aggregationAxisPrefix"] as? String ?? "",+ suffix: filter?["aggregationAxisPostfix"] as? String ?? "",+ decimalPlaces: precision(filter?["decimalPlaces"]),+ minDecimalPlaces: precision(filter?["minDecimalPlaces"])+ )+ }++ static func formatValue(_ value: Double, _ format: ValueFormat) -> String {+ let style = format.style+ let scaled = style == "percentage_scaled" ? value * 100 : value+ let significant = format.decimalPlaces ?? significantDecimals(scaled, minimum: format.minDecimalPlaces ?? 2)+ var formatted = number(scaled, maxDigits: significant, minDigits: format.minDecimalPlaces ?? 0)+ switch style {+ case "percentage", "percentage_scaled":+ formatted = "\(number(scaled, maxDigits: significant))%"+ case "currency":+ formatted = "$\(number(value, maxDigits: 2, minDigits: 2))"+ case "short":+ formatted = shortNumber(value)+ case "duration":+ formatted = duration(value * 1000)+ case "duration_ms":+ formatted = duration(value)+ case "duration_ns":+ if abs(value) < 1000 {+ formatted = "\(number(value, maxDigits: 2))ns"+ } else if abs(value) < 1_000_000 {+ formatted = "\(number(value / 1000, maxDigits: 2))µs"+ } else {+ formatted = duration(value / 1_000_000)+ }+ default:+ break+ }+ let prefix = style == "currency" && !format.prefix.isEmpty && formatted.hasPrefix(format.prefix) ? "" : format.prefix+ return "\(prefix)\(formatted)\(format.suffix)"+ }++ /// `toLocaleString('en-US')`: grouped thousands, halves rounded away from zero.+ static func number(_ value: Double, maxDigits: Int, minDigits: Int = 0) -> String {+ let formatter = NumberFormatter()+ formatter.locale = Locale(identifier: "en_US")+ formatter.numberStyle = .decimal+ formatter.usesGroupingSeparator = true+ formatter.roundingMode = .halfUp+ formatter.minimumFractionDigits = minDigits+ formatter.maximumFractionDigits = max(maxDigits, minDigits)+ return formatter.string(from: NSNumber(value: value)) ?? jsNumberString(value)+ }++ static func significantDecimals(_ value: Double, minimum: Int = 2) -> Int {+ guard value.isFinite, value != 0 else { return minimum }+ return min(max(minimum, 1 - Int(floor(log10(abs(value))))), 10)+ }++ static func shortNumber(_ value: Double) -> String {+ let magnitudes = ["", "K", "M", "B", "T", "P", "E", "Z", "Y"]+ var rounded = Double(String(format: "%.3g", value)) ?? value+ var magnitude = 0+ while abs(rounded) >= 1000 && magnitude < magnitudes.count - 1 {+ magnitude += 1+ rounded /= 1000+ }+ return magnitude > 0 ? "\(jsNumberString(rounded))\u{00a0}\(magnitudes[magnitude])" : jsNumberString(rounded)+ }++ static func duration(_ milliseconds: Double) -> String {+ let absolute = abs(milliseconds)+ guard absolute.isFinite else { return jsNumberString(milliseconds) }+ if absolute == 0 {+ return "0s"+ }+ if absolute < 60_000 {+ let value = absolute < 1000 ? milliseconds : milliseconds / 1000+ let decimals = min(max(0, 2 - Int(floor(log10(abs(value))))), 4)+ return "\(number(value, maxDigits: decimals))\(absolute < 1000 ? "ms" : "s")"+ }+ guard let seconds = Int(exactly: floor(absolute / 1000)) else {+ return "\(String(format: "%.6g", milliseconds / 1000))s"+ }+ let days = seconds / 86400+ let hours = (seconds % 86400) / 3600+ let minutes = (seconds % 3600) / 60+ let parts: [(Int, String)] = days > 0 ? [(days, "d"), (hours, "h")] : [(hours, "h"), (minutes, "m"), (seconds % 60, "s")]+ let text = parts.filter { $0.0 != 0 }.map { "\($0.0)\($0.1)" }.joined(separator: "\u{00a0}")+ return "\(milliseconds < 0 ? "-" : "")\(text)"+ }++ /// A JSON number that is not a boolean, as the adapters' `finite` reads it.+ static func finite(_ value: Any?) -> Double? {+ guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }+ let double = number.doubleValue+ return double.isFinite ? double : nil+ }++ /// JavaScript's `Boolean(value)` for a JSON value.+ static func isTruthy(_ value: Any?) -> Bool {+ switch value {+ case nil, is NSNull:+ return false+ case let number as NSNumber:+ if CFGetTypeID(number) == CFBooleanGetTypeID() {+ return number.boolValue+ }+ return number.doubleValue != 0 && !number.doubleValue.isNaN+ case let text as String:+ return !text.isEmpty+ default:+ return true+ }+ }++ /// `String(number)` in JavaScript, for whole numbers and short decimals.+ static func jsNumberString(_ value: Double) -> String {+ if value.isFinite && value == value.rounded() && abs(value) < 1e15 {+ return String(Int64(value))+ }+ return "\(value)"+ }+}++/// Dates as the app reads and writes them: src/lib/dates.ts (parseBucketStart, formatMonthDay),+/// src/ui/chart/chartMath.ts (formatAxisDate) and src/features/views/rangePresets.ts (formatRangeSpan).+enum ChartDates {+ private static let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]+ private static let utc = TimeZone(identifier: "UTC")!++ private static let isoPattern = try! NSRegularExpression(+ pattern: #"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?(Z|[+-]\d{2}(?::?\d{2})?)?$"#+ )+ private static let bucketPattern = try! NSRegularExpression(+ pattern: #"^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$"#+ )+ private static let dayOnlyPattern = try! NSRegularExpression(pattern: #"^(\d{4})-(\d{2})-(\d{2})$"#)+ private static let dateTimePattern = try! NSRegularExpression(pattern: #"^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})"#)++ static func groups(_ regex: NSRegularExpression, _ text: String) -> [String?]? {+ guard let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }+ return (0..<match.numberOfRanges).map { index in+ Range(match.range(at: index), in: text).map { String(text[$0]) }+ }+ }++ private static func calendar(_ zone: TimeZone) -> Calendar {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = zone+ return calendar+ }++ private static func date(_ groups: [String?], zone: TimeZone) -> Date? {+ var components = DateComponents()+ components.year = groups[1].flatMap { Int($0) }+ components.month = groups[2].flatMap { Int($0) }+ components.day = groups[3].flatMap { Int($0) }+ components.hour = groups.count > 4 ? groups[4].flatMap { Int($0) } ?? 0 : 0+ components.minute = groups.count > 5 ? groups[5].flatMap { Int($0) } ?? 0 : 0+ components.second = groups.count > 6 ? groups[6].flatMap { Int($0) } ?? 0 : 0+ if groups.count > 7, let fraction = groups[7] {+ components.nanosecond = Int(String((fraction + "000000000").prefix(9)))+ }+ return calendar(zone).date(from: components)+ }++ private static func zone(offset: String) -> TimeZone? {+ if offset == "Z" {+ return utc+ }+ let digits = offset.dropFirst().filter(\.isNumber)+ guard let hours = Int(digits.prefix(2)) else { return nil }+ let minutes = Int(digits.dropFirst(2).prefix(2)) ?? 0+ let seconds = (hours * 3600 + minutes * 60) * (offset.hasPrefix("-") ? -1 : 1)+ return TimeZone(secondsFromGMT: seconds)+ }++ /// `Date.parse` for the server's ISO strings: a bare date is UTC midnight, a date and time without an offset is+ /// local time.+ static func parse(_ text: String) -> Date? {+ guard let groups = groups(isoPattern, text) else { return nil }+ let zone: TimeZone+ if let offset = groups[8] {+ guard let parsed = Self.zone(offset: offset) else { return nil }+ zone = parsed+ } else {+ zone = groups[4] == nil ? utc : .current+ }+ return date(groups, zone: zone)+ }++ /// `parseBucketStart`: a bucket label without an offset is wall-clock time, so it parses as local time.+ static func bucketStart(_ text: String) -> Date? {+ if let groups = groups(bucketPattern, text) {+ return date(groups, zone: .current)+ }+ return parse(text)+ }++ /// `formatAxisDate`: "14:00" for hours, "Oct 12" for days and weeks, "Oct 2026" for months.+ static func axisLabel(_ date: Date, interval: TrendsParser.Interval) -> String {+ let parts = calendar(.current).dateComponents([.year, .month, .day, .hour, .minute], from: date)+ let month = months[((parts.month ?? 1) - 1 + 12) % 12]+ switch interval {+ case .hour:+ return String(format: "%02d:%02d", parts.hour ?? 0, parts.minute ?? 0)+ case .day, .week:+ return "\(month) \(parts.day ?? 1)"+ case .month:+ return "\(month) \(parts.year ?? 0)"+ }+ }++ static func dayLabel(_ date: Date) -> String {+ let parts = calendar(.current).dateComponents([.year, .month, .day], from: date)+ return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 1, parts.day ?? 1)+ }++ struct WallTime {+ let year: Int+ let month: Int+ let day: Int+ let time: String?+ }++ /// The date and time as written, which for the server's resolved ranges is the project timezone.+ static func wallTime(_ value: String) -> WallTime? {+ if let day = groups(dayOnlyPattern, value) {+ return WallTime(year: Int(day[1] ?? "") ?? 0, month: Int(day[2] ?? "") ?? 0, day: Int(day[3] ?? "") ?? 0, time: nil)+ }+ if let dateTime = groups(dateTimePattern, value) {+ return WallTime(+ year: Int(dateTime[1] ?? "") ?? 0, month: Int(dateTime[2] ?? "") ?? 0, day: Int(dateTime[3] ?? "") ?? 0,+ time: "\(dateTime[4] ?? "00"):\(dateTime[5] ?? "00")"+ )+ }+ return nil+ }++ private static func monthDay(_ time: WallTime) -> String {+ "\(months.indices.contains(time.month - 1) ? months[time.month - 1] : "") \(time.day)"+ }++ /// `formatRangeSpan` with " to " between the ends: "Oct 13", "Oct 6 to 12", "Sep 29 to Oct 6",+ /// "Dec 29, 2025 to Jan 4, 2026", and times for windows of hours.+ static func span(_ from: String, _ to: String, separator: String = " to ") -> String {+ guard let a = wallTime(from), let b = wallTime(to) else {+ return "\(from)\(separator)\(to)"+ }+ if a.time != nil || b.time != nil {+ return "\(monthDay(a)) \(a.time ?? "00:00")\(separator)\(monthDay(b)) \(b.time ?? "00:00")"+ }+ if a.year != b.year {+ return "\(monthDay(a)), \(a.year)\(separator)\(monthDay(b)), \(b.year)"+ }+ if a.month == b.month && a.day == b.day {+ return monthDay(a)+ }+ if a.month == b.month {+ return "\(monthDay(a))\(separator)\(b.day)"+ }+ return "\(monthDay(a))\(separator)\(monthDay(b))"+ }+}