@colixsystems/widget-sdk 0.341.0 → 0.342.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,7 +46,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
46
46
  | **CORE** | `useGeolocation(options)` (optional: options) | `{ latitude, longitude, accuracy, loading, error, getCurrentPosition, backgroundSupported, backgroundWatching, startBackgroundWatch, stopBackgroundWatch }` | `ctx.device.geolocation` — no scope. Capture is IMPERATIVE: call `getCurrentPosition()` from a user gesture (a tap), never on mount. Resolves to `{ latitude, longitude, accuracy }`; rejects with `GeolocationError` (`.code` in `PERMISSION_DENIED \| UNAVAILABLE \| TIMEOUT \| UNSUPPORTED \| INTERNAL`). Identical on web (`navigator.geolocation`) and the Expo export (`expo-location`). **Background watch** — `startBackgroundWatch({ enableHighAccuracy, distanceIntervalMeters, timeIntervalMs })` keeps positions arriving while the app is backgrounded; `stopBackgroundWatch()` releases it. NATIVE-ONLY and opt-in per app: gate the control on `backgroundSupported` (false on web, and in an export whose workspace did not opt in). The watch outlives the widget's mount, and its positions land in the same `latitude`/`longitude`/`accuracy` slots. |
47
47
  | **CORE** | `useSpeechToText(options)` (optional: options) | `{ transcript, partial, listening, supported, error, start, stop, abort, reset }` | `ctx.device.speech` — no scope. Dictation with the device's **on-device** recogniser: no audio is uploaded and no AI credit is spent. Capture is IMPERATIVE: call `start()` from a user gesture (a tap), never on mount. `transcript` accumulates finalised speech, `partial` holds the uncommitted guess (needs `options.interimResults`); `stop()` keeps it, `abort()` discards it. Rejects with `SpeechToTextError` (`.code` in `PERMISSION_DENIED \| NO_SPEECH \| LANGUAGE_UNSUPPORTED \| NETWORK \| ABORTED \| UNSUPPORTED \| INTERNAL`). **Gate your mic button on `supported`** — Firefox ships no `SpeechRecognition`. Identical on web (`SpeechRecognition`) and the Expo export (`expo-speech-recognition`). |
48
48
  | **CORE** | `useCamera(options)` (optional: options) | `{ asset, loading, error, supported, capture, pick, reset }` | `ctx.device.camera` — no scope. Take a photo (`capture()`) or choose one (`pick()`). Capture is IMPERATIVE: call from a user gesture (a tap), never on mount. Both resolve a normalised `{ uri, name, mimeType, width, height, size, file }`, or **`null` when the user dismisses the picker** — dismissal is not an error, so no `try/catch` is needed on the happy path. Rejects with `CameraError` (`.code` in `PERMISSION_DENIED \| UNSUPPORTED \| INTERNAL`). `asset.file` is already the right upload part for the host, so `fd.append("file", asset.file)` → `ctx.assets.upload(fd)` is ONE code path on both. **Gate your camera button on `supported`.** Identical on web (a live `getUserMedia` preview, phones included; a file input only where getUserMedia is absent) and the Expo export (`expo-image-picker`). |
49
- | **CORE** | `useI18n()` | `{ t, locale, languages, canSetLocale, setLocale }` | `ctx.i18n` — no scope. `t(key)` resolves the widget-namespaced key (`widget.<id>.<key>`, declared in `manifest.translations`) first, then a **predefined shared key** (`shared.<key>`) when `key` is one of the standard strings (`submit`, `cancel`, `save`, `loading`, …), then the raw key. Use a shared key for an identical default string so it translates once and any per-instance `widget.<id>.<key>` override still wins. `languages` lists the app's active languages (`[{ code, name, is_base }]`); `setLocale(code)` switches the whole app live — saved to a signed-in user's account, kept on the device for a visitor, `null` for the app default. Rejects with `.code` `INVALID_LOCALE` \| `UNSUPPORTED`; `canSetLocale` is false where the host cannot switch (the Builder canvas). |
49
+ | **CORE** | `useI18n()` | `{ t, locale, languages, canSetLocale, setLocale, formatDate }` | `ctx.i18n` — no scope. `t(key)` resolves the widget-namespaced key (`widget.<id>.<key>`, declared in `manifest.translations`) first, then a **predefined shared key** (`shared.<key>`) when `key` is one of the standard strings (`submit`, `cancel`, `save`, `loading`, …), then the raw key. Use a shared key for an identical default string so it translates once and any per-instance `widget.<id>.<key>` override still wins. `languages` lists the app's active languages (`[{ code, name, is_base }]`); `setLocale(code)` switches the whole app live — saved to a signed-in user's account, kept on the device for a visitor, `null` for the app default. Rejects with `.code` `INVALID_LOCALE` \| `UNSUPPORTED`; `canSetLocale` is false where the host cannot switch (the Builder canvas). Show every date with `formatDate(value)`: the app's language with the month named (`Jan 3, 2027`, `3 jan. 2027`), `{ time: true }` adds the time, and a null, empty or unreadable value gives `—` instead of throwing. Without `time`, a value at exactly midnight UTC is read as a calendar date. Never a numeric pattern such as `dd/MM/yyyy`. |
50
50
  | **CORE** | `useAppearance()` | `{ mode, preference, canSwitch, setPreference }` | `ctx.appearance` — no scope. `mode` is the palette showing (`light` \| `dark`), `preference` what the app follows (`light` \| `dark` \| `system`). `setPreference(p)` switches the whole app live — saved to a signed-in user's account, kept on the device for a visitor, `null` for the app default. Rejects with `.code` `UNSUPPORTED` \| `INVALID_APPEARANCE`; `canSwitch` is false where the app does not let users switch and on the Builder canvas. |
51
51
  | **CORE** | `useTranslate()` | `{ translate, translating, error, language, available }` | `ctx.i18n.translate` — no scope. Machine-translates **user-generated content** (record text, file names, API payloads) into the app user's language; `useI18n().t()` is still the answer for your own copy. `translate(str)` → `Promise<string>`, `translate(str[])` → `Promise<string[]>` in ONE request. Target defaults to the app user's language. Cached per session, per pod, and durably per workspace, so repeat text is free. Limits: 50 segments / 5 000 chars each / 20 000 total. Rejects with `TranslateError`; `available` is false where the host cannot translate. |
52
52
  | **CORE** | `useLinkPreview(url)` | `{ preview, loading, error, available }` — `preview` is `{ url, title, description, site_name, image_url } \| null` | `ctx.linkPreviews.get` — no scope. A link's title, description, site name and image, fetched by the platform (the device never contacts the linked site). A page with nothing to show resolves with null fields, not an error — render the plain link. A non-http(s) `url` makes no request. Memoized for up to an hour across widgets; concurrent calls for one URL share a request. `error` is a `LinkPreviewError` (`VALIDATION` \| `AUTH_REQUIRED` \| `RATE_LIMITED` \| `NETWORK` \| `INTERNAL`). `available` is false on a host with no link-preview client |
@@ -91,7 +91,16 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
91
 
92
92
  ## Status
93
93
 
94
- `v0.341.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+ `v0.342.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
95
+
96
+ ### What's new in 0.342.0 (contract 1.279.0)
97
+
98
+ **`useI18n().formatDate` shows a date in the app's language.** `formatDate(value)` names the month, as the Studio and `<DateTimePicker>` do: `Jan 3, 2027` in an English app, `3 jan. 2027` in a Swedish one. `formatDate(value, { time: true })` adds the time of a date-and-time value; a bare `YYYY-MM-DD` never shows one. It takes an ISO string, a `Date` or a timestamp, keeps a DATE column's `YYYY-MM-DDT00:00:00.000Z` on its calendar day, and returns `—` for a null, empty or unreadable value instead of throwing, so it is also the guard every shown date needs. Without `time`, a value at exactly midnight UTC is read as a calendar date (how a DATE column arrives), so a date-and-time stored at that instant shows its UTC day. It shows the date in the app's language on the web and in the exported app alike (through each platform's own date formatting, so spacing can differ slightly). It formats dates only: a time on its own (a `14:30` text) gives `—`. Use it instead of a fixed pattern such as `dd/MM/yyyy`: `03/01/2027` is 3 January in one country and 1 March in another.
99
+
100
+ ```js
101
+ const { t, formatDate } = useI18n();
102
+ <Text>{t("access_ends", "Access ends on")} {formatDate(member.accessEnds)}</Text>
103
+ ```
95
104
 
96
105
  ### What's new in 0.341.0 (contract 1.278.0)
97
106
 
package/dist/contract.cjs CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  const { COMPONENT_PROPS, COMPONENT_PROPS_ERROR_PREFIX, componentPropsError, tabItemKey } = require("./component-props.cjs");
6
6
  const { COMPONENT_TEXTS, fillSdkText, textInLanguage } = require("./sdk-texts.cjs");
7
+ const { formatDateForDisplay } = require("./date-label.cjs");
7
8
 
8
9
  // The widget SDK contract: the ONE source the linter, the AI agents, the
9
10
  // compiler and both hosts read. `contract.cjs` is GENERATED from `contract.js`
@@ -928,6 +929,11 @@ const HOOKS = [
928
929
  "setLocale(null) returns to the app's default language. setLocale resolves once the choice is saved and rejects with " +
929
930
  "an Error whose .code is INVALID_LOCALE (the code is not one of languages) or UNSUPPORTED (this host cannot switch, " +
930
931
  "e.g. the Builder canvas) — always catch it. canSetLocale is false on such a host: render the choices disabled then, never a dead button. " +
932
+ "formatDate(value, { time }?) shows a date in the app's language with its month named, as the Studio and <DateTimePicker> do " +
933
+ "(\"Jan 3, 2027\" in English, \"3 jan. 2027\" in Swedish); { time: true } adds the time of a date-and-time value. Without time, a value at " +
934
+ "exactly midnight UTC is read as a calendar date (how a DATE column arrives), so an instant stored then shows its UTC day. It takes an ISO string, " +
935
+ "a Date or a timestamp, and returns \"—\" for a null, empty or unreadable value instead of throwing, so it is the one way to show a date: " +
936
+ "never a fixed numeric pattern such as dd/MM/yyyy, which reads as a different day in another country. " +
931
937
  "Identical on web (Player) and the Expo export.",
932
938
  returnShape: {
933
939
  t: "(key: string, fallback?: string) => string",
@@ -935,6 +941,7 @@ const HOOKS = [
935
941
  languages: "Array<{ code: string, name: string, is_base: boolean }>",
936
942
  canSetLocale: "boolean",
937
943
  setLocale: "(code: string | null) => Promise<void> // rejects with Error .code INVALID_LOCALE | UNSUPPORTED",
944
+ formatDate: "(value: string | Date | number | null, options?: { time?: boolean }) => string // \"—\" when empty or unreadable",
938
945
  },
939
946
  requiredContextSlice: ["i18n.t", "i18n.locale"],
940
947
  scopes: null,
@@ -5382,8 +5389,8 @@ const CHARGE_CURRENCY = "SEK";
5382
5389
  // which reads this table.
5383
5390
  //
5384
5391
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5385
- // react-native-web do not agree on its output (the same reason widgets format
5386
- // dates with `date-fns` rather than `toLocaleDateString`), and this string ends
5392
+ // react-native-web do not agree on its output (dates differ only in spacing, so
5393
+ // `useI18n().formatDate` uses Intl; a price must match exactly), and this string ends
5387
5394
  // up on a price the buyer compares against the amount they are charged. An
5388
5395
  // explicit table renders byte-identically on both hosts.
5389
5396
  //
@@ -7135,7 +7142,9 @@ const CONTRACT = deepFreeze({
7135
7142
  // `appOperations` it calls; a `connectorRef` property may name one with
7136
7143
  // `template`. Checked by `appstudio-widget lint --manifest`. The template
7137
7144
  // contract is shared with the action SDK (`./connector-template`).
7138
- version: "1.278.0",
7145
+ // 1.279.0: additive (sc-18049) — useI18n() returns formatDate(value, { time }?),
7146
+ // a date in the app's language with its month named; "—" when empty.
7147
+ version: "1.279.0",
7139
7148
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7140
7149
  hooks: HOOKS,
7141
7150
  primitives: PRIMITIVES,
@@ -7744,4 +7753,5 @@ module.exports = {
7744
7753
  SDK_TEXTS,
7745
7754
  sdkText,
7746
7755
  fillSdkText,
7756
+ formatDateForDisplay,
7747
7757
  };
package/dist/contract.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // `useTheme().elevation` — so a widget shadow and a container shadow match.
11
11
  import { COMPONENT_PROPS, COMPONENT_PROPS_ERROR_PREFIX, componentPropsError, tabItemKey } from "./component-props.js";
12
12
  import { COMPONENT_TEXTS, fillSdkText, textInLanguage } from "./sdk-texts.js";
13
+ import { formatDateForDisplay } from "./date-label.js";
13
14
 
14
15
  const ELEVATION = Object.freeze({
15
16
  none: Object.freeze({}),
@@ -923,6 +924,11 @@ const HOOKS = [
923
924
  "setLocale(null) returns to the app's default language. setLocale resolves once the choice is saved and rejects with " +
924
925
  "an Error whose .code is INVALID_LOCALE (the code is not one of languages) or UNSUPPORTED (this host cannot switch, " +
925
926
  "e.g. the Builder canvas) — always catch it. canSetLocale is false on such a host: render the choices disabled then, never a dead button. " +
927
+ "formatDate(value, { time }?) shows a date in the app's language with its month named, as the Studio and <DateTimePicker> do " +
928
+ "(\"Jan 3, 2027\" in English, \"3 jan. 2027\" in Swedish); { time: true } adds the time of a date-and-time value. Without time, a value at " +
929
+ "exactly midnight UTC is read as a calendar date (how a DATE column arrives), so an instant stored then shows its UTC day. It takes an ISO string, " +
930
+ "a Date or a timestamp, and returns \"—\" for a null, empty or unreadable value instead of throwing, so it is the one way to show a date: " +
931
+ "never a fixed numeric pattern such as dd/MM/yyyy, which reads as a different day in another country. " +
926
932
  "Identical on web (Player) and the Expo export.",
927
933
  returnShape: {
928
934
  t: "(key: string, fallback?: string) => string",
@@ -930,6 +936,7 @@ const HOOKS = [
930
936
  languages: "Array<{ code: string, name: string, is_base: boolean }>",
931
937
  canSetLocale: "boolean",
932
938
  setLocale: "(code: string | null) => Promise<void> // rejects with Error .code INVALID_LOCALE | UNSUPPORTED",
939
+ formatDate: "(value: string | Date | number | null, options?: { time?: boolean }) => string // \"—\" when empty or unreadable",
933
940
  },
934
941
  requiredContextSlice: ["i18n.t", "i18n.locale"],
935
942
  scopes: null,
@@ -5377,8 +5384,8 @@ const CHARGE_CURRENCY = "SEK";
5377
5384
  // which reads this table.
5378
5385
  //
5379
5386
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5380
- // react-native-web do not agree on its output (the same reason widgets format
5381
- // dates with `date-fns` rather than `toLocaleDateString`), and this string ends
5387
+ // react-native-web do not agree on its output (dates differ only in spacing, so
5388
+ // `useI18n().formatDate` uses Intl; a price must match exactly), and this string ends
5382
5389
  // up on a price the buyer compares against the amount they are charged. An
5383
5390
  // explicit table renders byte-identically on both hosts.
5384
5391
  //
@@ -7130,7 +7137,9 @@ const CONTRACT = deepFreeze({
7130
7137
  // `appOperations` it calls; a `connectorRef` property may name one with
7131
7138
  // `template`. Checked by `appstudio-widget lint --manifest`. The template
7132
7139
  // contract is shared with the action SDK (`./connector-template`).
7133
- version: "1.278.0",
7140
+ // 1.279.0: additive (sc-18049) — useI18n() returns formatDate(value, { time }?),
7141
+ // a date in the app's language with its month named; "—" when empty.
7142
+ version: "1.279.0",
7134
7143
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7135
7144
  hooks: HOOKS,
7136
7145
  primitives: PRIMITIVES,
@@ -7739,4 +7748,5 @@ export {
7739
7748
  SDK_TEXTS,
7740
7749
  sdkText,
7741
7750
  fillSdkText,
7751
+ formatDateForDisplay,
7742
7752
  };
@@ -0,0 +1,164 @@
1
+ // GENERATED from date-label.js by scripts/generate-cjs.js — DO NOT EDIT.
2
+ // Change date-label.js, then run `npm run generate:cjs` in packages/widget-sdk.
3
+ "use strict";
4
+
5
+ // The value-to-text half of the date contract, shared by `<DateTimePicker>`'s
6
+ // field label and `useI18n().formatDate`. No imports, so the CommonJS copy the
7
+ // backend loads through contract.cjs stays standalone.
8
+
9
+ const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})/;
10
+ const TIME_ONLY = /^(\d{2}):(\d{2})/;
11
+
12
+ function formatToIso(date, mode) {
13
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
14
+ if (mode === "date") {
15
+ // Calendar dates are timezone-free: May 28 in Stockholm stays May 28 in NYC.
16
+ const y = String(date.getFullYear()).padStart(4, "0");
17
+ const m = String(date.getMonth() + 1).padStart(2, "0");
18
+ const d = String(date.getDate()).padStart(2, "0");
19
+ return `${y}-${m}-${d}`;
20
+ }
21
+ if (mode === "time") {
22
+ const h = String(date.getHours()).padStart(2, "0");
23
+ const mm = String(date.getMinutes()).padStart(2, "0");
24
+ return `${h}:${mm}`;
25
+ }
26
+ // datetime — full UTC ISO so the wire format round-trips through a DATE column.
27
+ return date.toISOString();
28
+ }
29
+
30
+ function normaliseMode(mode) {
31
+ return mode === "time" || mode === "datetime" ? mode : "date";
32
+ }
33
+
34
+ /**
35
+ * A stored value as the local wall-clock parts the picker edits, or null when
36
+ * it is empty or unreadable. `month` is 0-based, as `Date` counts it.
37
+ *
38
+ * @returns {{year: number, month: number, day: number, hours: number, minutes: number} | null}
39
+ */
40
+ function valueToParts(value, mode) {
41
+ if (value == null || value === "") return null;
42
+ const text = String(value);
43
+ const effectiveMode = normaliseMode(mode);
44
+ if (effectiveMode === "time") {
45
+ const match = TIME_ONLY.exec(text);
46
+ if (!match) return null;
47
+ const hours = Number(match[1]);
48
+ const minutes = Number(match[2]);
49
+ if (hours > 23 || minutes > 59) return null;
50
+ return { year: null, month: null, day: null, hours, minutes };
51
+ }
52
+ // A date column holds a calendar date, never an instant: read its head as is.
53
+ const dateOnly = DATE_ONLY.exec(text);
54
+ if (effectiveMode === "date" || (dateOnly && text.length === 10)) {
55
+ if (!dateOnly) return null;
56
+ return checkedParts(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]), 0, 0);
57
+ }
58
+ const d = new Date(text);
59
+ if (Number.isNaN(d.getTime())) return null;
60
+ return {
61
+ year: d.getFullYear(),
62
+ month: d.getMonth(),
63
+ day: d.getDate(),
64
+ hours: d.getHours(),
65
+ minutes: d.getMinutes(),
66
+ };
67
+ }
68
+
69
+ function checkedParts(year, month, day, hours, minutes) {
70
+ const d = new Date(year, month, day, hours, minutes);
71
+ if (d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day) return null;
72
+ return { year, month, day, hours, minutes };
73
+ }
74
+
75
+ function partsToDate(parts) {
76
+ return new Date(parts.year, parts.month, parts.day, parts.hours || 0, parts.minutes || 0);
77
+ }
78
+
79
+ function nowParts(now = new Date()) {
80
+ return {
81
+ year: now.getFullYear(),
82
+ month: now.getMonth(),
83
+ day: now.getDate(),
84
+ hours: now.getHours(),
85
+ minutes: now.getMinutes(),
86
+ };
87
+ }
88
+
89
+ // Built once per locale and options: construction is slow on Hermes. Each
90
+ // formats the wall-clock time in UTC, so a cached one never keeps a stale zone.
91
+ const FORMATTERS = new Map();
92
+
93
+ // Hermes ships a partial Intl; any refusal falls back to the ISO shape.
94
+ function intlFormat(locale, options, date) {
95
+ const key = `${locale || ""}|${JSON.stringify(options)}`;
96
+ try {
97
+ let formatter = FORMATTERS.get(key);
98
+ if (!formatter) {
99
+ formatter = new Intl.DateTimeFormat(locale || undefined, { ...options, timeZone: "UTC" });
100
+ FORMATTERS.set(key, formatter);
101
+ }
102
+ const wallClock = new Date(0);
103
+ wallClock.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
104
+ wallClock.setUTCHours(date.getHours(), date.getMinutes(), 0, 0);
105
+ return formatter.format(wallClock);
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ const DATE_LABEL = { year: "numeric", month: "short", day: "numeric" };
112
+ const TIME_LABEL = { hour: "2-digit", minute: "2-digit" };
113
+
114
+ function partsLabel(parts, mode, locale) {
115
+ if (mode === "time") {
116
+ const date = new Date(2000, 0, 1, parts.hours, parts.minutes);
117
+ return intlFormat(locale, TIME_LABEL, date) || formatToIso(date, "time");
118
+ }
119
+ const date = partsToDate(parts);
120
+ if (mode === "date") {
121
+ return intlFormat(locale, DATE_LABEL, date) || formatToIso(date, "date");
122
+ }
123
+ return (
124
+ intlFormat(locale, { ...DATE_LABEL, ...TIME_LABEL }, date) ||
125
+ `${formatToIso(date, "date")} ${formatToIso(date, "time")}`
126
+ );
127
+ }
128
+
129
+ const NO_DATE = "—";
130
+
131
+ // A DATE column answers as UTC midnight, so without `time` that is a calendar date.
132
+ const UTC_MIDNIGHT = /^\d{4}-\d{2}-\d{2}T00:00(:00(\.0+)?)?Z$/;
133
+
134
+ /**
135
+ * `useI18n().formatDate`: a value in the app's language with its month named
136
+ * (`Jan 3, 2027`, `3 jan. 2027`), plus the time when `options.time` is set. A
137
+ * bare `YYYY-MM-DD` never shows a time. Without `time`, an instant at exactly
138
+ * midnight UTC shows its UTC day. Empty or unreadable input gives `NO_DATE`;
139
+ * it never throws.
140
+ */
141
+ function formatDateForDisplay(value, locale, options) {
142
+ const withTime = Boolean(options && options.time);
143
+ if (value instanceof Date || typeof value === "number") {
144
+ const instant = new Date(value);
145
+ if (Number.isNaN(instant.getTime())) return NO_DATE;
146
+ return partsLabel(nowParts(instant), withTime ? "datetime" : "date", locale);
147
+ }
148
+ if (typeof value !== "string" || !value) return NO_DATE;
149
+ const calendarDate =
150
+ value.length === 10 || (!withTime && UTC_MIDNIGHT.test(value)) ? value.slice(0, 10) : null;
151
+ const parts = valueToParts(calendarDate || value, "datetime");
152
+ if (!parts) return NO_DATE;
153
+ return partsLabel(parts, withTime && !calendarDate ? "datetime" : "date", locale);
154
+ }
155
+ module.exports = {
156
+ formatToIso,
157
+ normaliseMode,
158
+ valueToParts,
159
+ partsToDate,
160
+ nowParts,
161
+ partsLabel,
162
+ NO_DATE,
163
+ formatDateForDisplay,
164
+ };
@@ -0,0 +1,150 @@
1
+ // The value-to-text half of the date contract, shared by `<DateTimePicker>`'s
2
+ // field label and `useI18n().formatDate`. No imports, so the CommonJS copy the
3
+ // backend loads through contract.cjs stays standalone.
4
+
5
+ const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})/;
6
+ const TIME_ONLY = /^(\d{2}):(\d{2})/;
7
+
8
+ export function formatToIso(date, mode) {
9
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
10
+ if (mode === "date") {
11
+ // Calendar dates are timezone-free: May 28 in Stockholm stays May 28 in NYC.
12
+ const y = String(date.getFullYear()).padStart(4, "0");
13
+ const m = String(date.getMonth() + 1).padStart(2, "0");
14
+ const d = String(date.getDate()).padStart(2, "0");
15
+ return `${y}-${m}-${d}`;
16
+ }
17
+ if (mode === "time") {
18
+ const h = String(date.getHours()).padStart(2, "0");
19
+ const mm = String(date.getMinutes()).padStart(2, "0");
20
+ return `${h}:${mm}`;
21
+ }
22
+ // datetime — full UTC ISO so the wire format round-trips through a DATE column.
23
+ return date.toISOString();
24
+ }
25
+
26
+ export function normaliseMode(mode) {
27
+ return mode === "time" || mode === "datetime" ? mode : "date";
28
+ }
29
+
30
+ /**
31
+ * A stored value as the local wall-clock parts the picker edits, or null when
32
+ * it is empty or unreadable. `month` is 0-based, as `Date` counts it.
33
+ *
34
+ * @returns {{year: number, month: number, day: number, hours: number, minutes: number} | null}
35
+ */
36
+ export function valueToParts(value, mode) {
37
+ if (value == null || value === "") return null;
38
+ const text = String(value);
39
+ const effectiveMode = normaliseMode(mode);
40
+ if (effectiveMode === "time") {
41
+ const match = TIME_ONLY.exec(text);
42
+ if (!match) return null;
43
+ const hours = Number(match[1]);
44
+ const minutes = Number(match[2]);
45
+ if (hours > 23 || minutes > 59) return null;
46
+ return { year: null, month: null, day: null, hours, minutes };
47
+ }
48
+ // A date column holds a calendar date, never an instant: read its head as is.
49
+ const dateOnly = DATE_ONLY.exec(text);
50
+ if (effectiveMode === "date" || (dateOnly && text.length === 10)) {
51
+ if (!dateOnly) return null;
52
+ return checkedParts(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]), 0, 0);
53
+ }
54
+ const d = new Date(text);
55
+ if (Number.isNaN(d.getTime())) return null;
56
+ return {
57
+ year: d.getFullYear(),
58
+ month: d.getMonth(),
59
+ day: d.getDate(),
60
+ hours: d.getHours(),
61
+ minutes: d.getMinutes(),
62
+ };
63
+ }
64
+
65
+ function checkedParts(year, month, day, hours, minutes) {
66
+ const d = new Date(year, month, day, hours, minutes);
67
+ if (d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day) return null;
68
+ return { year, month, day, hours, minutes };
69
+ }
70
+
71
+ export function partsToDate(parts) {
72
+ return new Date(parts.year, parts.month, parts.day, parts.hours || 0, parts.minutes || 0);
73
+ }
74
+
75
+ export function nowParts(now = new Date()) {
76
+ return {
77
+ year: now.getFullYear(),
78
+ month: now.getMonth(),
79
+ day: now.getDate(),
80
+ hours: now.getHours(),
81
+ minutes: now.getMinutes(),
82
+ };
83
+ }
84
+
85
+ // Built once per locale and options: construction is slow on Hermes. Each
86
+ // formats the wall-clock time in UTC, so a cached one never keeps a stale zone.
87
+ const FORMATTERS = new Map();
88
+
89
+ // Hermes ships a partial Intl; any refusal falls back to the ISO shape.
90
+ function intlFormat(locale, options, date) {
91
+ const key = `${locale || ""}|${JSON.stringify(options)}`;
92
+ try {
93
+ let formatter = FORMATTERS.get(key);
94
+ if (!formatter) {
95
+ formatter = new Intl.DateTimeFormat(locale || undefined, { ...options, timeZone: "UTC" });
96
+ FORMATTERS.set(key, formatter);
97
+ }
98
+ const wallClock = new Date(0);
99
+ wallClock.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
100
+ wallClock.setUTCHours(date.getHours(), date.getMinutes(), 0, 0);
101
+ return formatter.format(wallClock);
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ const DATE_LABEL = { year: "numeric", month: "short", day: "numeric" };
108
+ const TIME_LABEL = { hour: "2-digit", minute: "2-digit" };
109
+
110
+ export function partsLabel(parts, mode, locale) {
111
+ if (mode === "time") {
112
+ const date = new Date(2000, 0, 1, parts.hours, parts.minutes);
113
+ return intlFormat(locale, TIME_LABEL, date) || formatToIso(date, "time");
114
+ }
115
+ const date = partsToDate(parts);
116
+ if (mode === "date") {
117
+ return intlFormat(locale, DATE_LABEL, date) || formatToIso(date, "date");
118
+ }
119
+ return (
120
+ intlFormat(locale, { ...DATE_LABEL, ...TIME_LABEL }, date) ||
121
+ `${formatToIso(date, "date")} ${formatToIso(date, "time")}`
122
+ );
123
+ }
124
+
125
+ export const NO_DATE = "—";
126
+
127
+ // A DATE column answers as UTC midnight, so without `time` that is a calendar date.
128
+ const UTC_MIDNIGHT = /^\d{4}-\d{2}-\d{2}T00:00(:00(\.0+)?)?Z$/;
129
+
130
+ /**
131
+ * `useI18n().formatDate`: a value in the app's language with its month named
132
+ * (`Jan 3, 2027`, `3 jan. 2027`), plus the time when `options.time` is set. A
133
+ * bare `YYYY-MM-DD` never shows a time. Without `time`, an instant at exactly
134
+ * midnight UTC shows its UTC day. Empty or unreadable input gives `NO_DATE`;
135
+ * it never throws.
136
+ */
137
+ export function formatDateForDisplay(value, locale, options) {
138
+ const withTime = Boolean(options && options.time);
139
+ if (value instanceof Date || typeof value === "number") {
140
+ const instant = new Date(value);
141
+ if (Number.isNaN(instant.getTime())) return NO_DATE;
142
+ return partsLabel(nowParts(instant), withTime ? "datetime" : "date", locale);
143
+ }
144
+ if (typeof value !== "string" || !value) return NO_DATE;
145
+ const calendarDate =
146
+ value.length === 10 || (!withTime && UTC_MIDNIGHT.test(value)) ? value.slice(0, 10) : null;
147
+ const parts = valueToParts(calendarDate || value, "datetime");
148
+ if (!parts) return NO_DATE;
149
+ return partsLabel(parts, withTime && !calendarDate ? "datetime" : "date", locale);
150
+ }
@@ -4,9 +4,16 @@
4
4
  // without a renderer. No React, no RN here — just Date math and Intl.
5
5
 
6
6
  import { sdkText } from "./contract.js";
7
+ import {
8
+ formatToIso,
9
+ normaliseMode,
10
+ valueToParts,
11
+ partsToDate,
12
+ nowParts,
13
+ partsLabel,
14
+ } from "./date-label.js";
7
15
 
8
- const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})/;
9
- const TIME_ONLY = /^(\d{2}):(\d{2})/;
16
+ export { formatToIso, normaliseMode, valueToParts, partsToDate, nowParts };
10
17
 
11
18
  // A stored DATETIME instant → `<input type="datetime-local">`'s
12
19
  // `YYYY-MM-DDTHH:mm` on the viewer's local clock. A bare calendar date is
@@ -27,73 +34,6 @@ export function dateTimeLocalInputToIso(raw) {
27
34
  return d.toISOString();
28
35
  }
29
36
 
30
- export function formatToIso(date, mode) {
31
- if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
32
- if (mode === "date") {
33
- // Calendar dates are timezone-free: May 28 in Stockholm stays May 28 in NYC.
34
- const y = String(date.getFullYear()).padStart(4, "0");
35
- const m = String(date.getMonth() + 1).padStart(2, "0");
36
- const d = String(date.getDate()).padStart(2, "0");
37
- return `${y}-${m}-${d}`;
38
- }
39
- if (mode === "time") {
40
- const h = String(date.getHours()).padStart(2, "0");
41
- const mm = String(date.getMinutes()).padStart(2, "0");
42
- return `${h}:${mm}`;
43
- }
44
- // datetime — full UTC ISO so the wire format round-trips through a DATE column.
45
- return date.toISOString();
46
- }
47
-
48
- export function normaliseMode(mode) {
49
- return mode === "time" || mode === "datetime" ? mode : "date";
50
- }
51
-
52
- /**
53
- * A stored value as the local wall-clock parts the picker edits, or null when
54
- * it is empty or unreadable. `month` is 0-based, as `Date` counts it.
55
- *
56
- * @returns {{year: number, month: number, day: number, hours: number, minutes: number} | null}
57
- */
58
- export function valueToParts(value, mode) {
59
- if (value == null || value === "") return null;
60
- const text = String(value);
61
- const effectiveMode = normaliseMode(mode);
62
- if (effectiveMode === "time") {
63
- const match = TIME_ONLY.exec(text);
64
- if (!match) return null;
65
- const hours = Number(match[1]);
66
- const minutes = Number(match[2]);
67
- if (hours > 23 || minutes > 59) return null;
68
- return { year: null, month: null, day: null, hours, minutes };
69
- }
70
- // A date column holds a calendar date, never an instant: read its head as is.
71
- const dateOnly = DATE_ONLY.exec(text);
72
- if (effectiveMode === "date" || (dateOnly && text.length === 10)) {
73
- if (!dateOnly) return null;
74
- return checkedParts(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]), 0, 0);
75
- }
76
- const d = new Date(text);
77
- if (Number.isNaN(d.getTime())) return null;
78
- return {
79
- year: d.getFullYear(),
80
- month: d.getMonth(),
81
- day: d.getDate(),
82
- hours: d.getHours(),
83
- minutes: d.getMinutes(),
84
- };
85
- }
86
-
87
- function checkedParts(year, month, day, hours, minutes) {
88
- const d = new Date(year, month, day, hours, minutes);
89
- if (d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day) return null;
90
- return { year, month, day, hours, minutes };
91
- }
92
-
93
- export function partsToDate(parts) {
94
- return new Date(parts.year, parts.month, parts.day, parts.hours || 0, parts.minutes || 0);
95
- }
96
-
97
37
  /** The ISO string the picker emits for local parts, in its mode's wire shape. */
98
38
  export function partsToIso(parts, mode) {
99
39
  const effectiveMode = normaliseMode(mode);
@@ -104,28 +44,6 @@ export function partsToIso(parts, mode) {
104
44
  return formatToIso(partsToDate(parts), effectiveMode) || "";
105
45
  }
106
46
 
107
- export function nowParts(now = new Date()) {
108
- return {
109
- year: now.getFullYear(),
110
- month: now.getMonth(),
111
- day: now.getDate(),
112
- hours: now.getHours(),
113
- minutes: now.getMinutes(),
114
- };
115
- }
116
-
117
- // Hermes ships a partial Intl; any refusal falls back to the ISO shape.
118
- function intlFormat(locale, options, date) {
119
- try {
120
- return new Intl.DateTimeFormat(locale || undefined, options).format(date);
121
- } catch {
122
- return null;
123
- }
124
- }
125
-
126
- const DATE_LABEL = { year: "numeric", month: "short", day: "numeric" };
127
- const TIME_LABEL = { hour: "2-digit", minute: "2-digit" };
128
-
129
47
  /**
130
48
  * The text on the picker's field: the value in the viewer's language
131
49
  * (`28 maj 2026`, `May 28, 2026, 2:30 PM`), or a mode-specific placeholder
@@ -140,16 +58,5 @@ export function formatDisplayLabel(value, mode, locale) {
140
58
  }
141
59
  const parts = valueToParts(value, effectiveMode);
142
60
  if (!parts) return String(value);
143
- if (effectiveMode === "time") {
144
- const date = new Date(2000, 0, 1, parts.hours, parts.minutes);
145
- return intlFormat(locale, TIME_LABEL, date) || formatToIso(date, "time");
146
- }
147
- const date = partsToDate(parts);
148
- if (effectiveMode === "date") {
149
- return intlFormat(locale, DATE_LABEL, date) || formatToIso(date, "date");
150
- }
151
- return (
152
- intlFormat(locale, { ...DATE_LABEL, ...TIME_LABEL }, date) ||
153
- `${formatToIso(date, "date")} ${formatToIso(date, "time")}`
154
- );
61
+ return partsLabel(parts, effectiveMode, locale);
155
62
  }
package/dist/hooks.js CHANGED
@@ -60,6 +60,8 @@ import {
60
60
  COMPONENT_PROPS,
61
61
  COMPONENT_PROPS_ERROR_PREFIX,
62
62
  componentPropsError,
63
+ // sc-18049 — the picker's own label formatter, so dates read alike everywhere.
64
+ formatDateForDisplay,
63
65
  } from "./contract.js";
64
66
 
65
67
  /** @internal — host-injected context value of shape WidgetContext (see index.d.ts). */
@@ -1060,7 +1062,7 @@ function localeError(code, message) {
1060
1062
  }
1061
1063
 
1062
1064
  /**
1063
- * Returns { t, locale, languages, canSetLocale, setLocale }. `t(key,
1065
+ * Returns { t, locale, languages, canSetLocale, setLocale, formatDate }. `t(key,
1064
1066
  * fallback)` resolves `{{t:key}}` against the host's translation table and
1065
1067
  * falls back to `fallback ?? key` when the key is missing. The host's i18n.t
1066
1068
  * may or may not honour the two-arg form; we degrade gracefully either way.
@@ -1146,7 +1148,11 @@ export function useI18n() {
1146
1148
  },
1147
1149
  [hostT, widgetId],
1148
1150
  );
1149
- return { t, locale, languages, canSetLocale: hostSetLocale !== null, setLocale };
1151
+ const formatDate = useCallback(
1152
+ (value, options) => formatDateForDisplay(value, locale, options),
1153
+ [locale],
1154
+ );
1155
+ return { t, locale, languages, canSetLocale: hostSetLocale !== null, setLocale, formatDate };
1150
1156
  }
1151
1157
 
1152
1158
  function appearanceError(code, message) {
package/dist/index.d.ts CHANGED
@@ -2514,6 +2514,13 @@ export interface AppLanguage {
2514
2514
  * visitor's stays on the device, and `null` returns to the app's default.
2515
2515
  * Rejects with an Error whose `.code` is `INVALID_LOCALE` or `UNSUPPORTED`
2516
2516
  * (`canSetLocale` is false on a host that cannot switch).
2517
+ *
2518
+ * `formatDate(value, { time }?)` shows a date in the app's language with its
2519
+ * month named (`Jan 3, 2027`, `3 jan. 2027`); `{ time: true }` adds the time of
2520
+ * a date-and-time value. Without `time`, a value at exactly midnight UTC is
2521
+ * read as a calendar date (a DATE column's form), so an instant stored then
2522
+ * shows its UTC day. A null, empty or unreadable value gives `"—"`; it never
2523
+ * throws.
2517
2524
  */
2518
2525
  export function useI18n(): {
2519
2526
  locale: string;
@@ -2521,6 +2528,7 @@ export function useI18n(): {
2521
2528
  languages: AppLanguage[];
2522
2529
  canSetLocale: boolean;
2523
2530
  setLocale(code: string | null): Promise<void>;
2531
+ formatDate(value: string | Date | number | null | undefined, options?: { time?: boolean }): string;
2524
2532
  };
2525
2533
 
2526
2534
  /** What an app follows: a fixed palette, or the device's setting. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.341.0",
3
+ "version": "0.342.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -68,7 +68,8 @@
68
68
  "src/dev-shims.js",
69
69
  "src/contract.js",
70
70
  "src/component-props.js",
71
- "src/sdk-texts.js"
71
+ "src/sdk-texts.js",
72
+ "src/date-label.js"
72
73
  ],
73
74
  "scripts": {
74
75
  "build": "node scripts/build.js",
package/src/contract.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // `useTheme().elevation` — so a widget shadow and a container shadow match.
11
11
  import { COMPONENT_PROPS, COMPONENT_PROPS_ERROR_PREFIX, componentPropsError, tabItemKey } from "./component-props.js";
12
12
  import { COMPONENT_TEXTS, fillSdkText, textInLanguage } from "./sdk-texts.js";
13
+ import { formatDateForDisplay } from "./date-label.js";
13
14
 
14
15
  const ELEVATION = Object.freeze({
15
16
  none: Object.freeze({}),
@@ -923,6 +924,11 @@ const HOOKS = [
923
924
  "setLocale(null) returns to the app's default language. setLocale resolves once the choice is saved and rejects with " +
924
925
  "an Error whose .code is INVALID_LOCALE (the code is not one of languages) or UNSUPPORTED (this host cannot switch, " +
925
926
  "e.g. the Builder canvas) — always catch it. canSetLocale is false on such a host: render the choices disabled then, never a dead button. " +
927
+ "formatDate(value, { time }?) shows a date in the app's language with its month named, as the Studio and <DateTimePicker> do " +
928
+ "(\"Jan 3, 2027\" in English, \"3 jan. 2027\" in Swedish); { time: true } adds the time of a date-and-time value. Without time, a value at " +
929
+ "exactly midnight UTC is read as a calendar date (how a DATE column arrives), so an instant stored then shows its UTC day. It takes an ISO string, " +
930
+ "a Date or a timestamp, and returns \"—\" for a null, empty or unreadable value instead of throwing, so it is the one way to show a date: " +
931
+ "never a fixed numeric pattern such as dd/MM/yyyy, which reads as a different day in another country. " +
926
932
  "Identical on web (Player) and the Expo export.",
927
933
  returnShape: {
928
934
  t: "(key: string, fallback?: string) => string",
@@ -930,6 +936,7 @@ const HOOKS = [
930
936
  languages: "Array<{ code: string, name: string, is_base: boolean }>",
931
937
  canSetLocale: "boolean",
932
938
  setLocale: "(code: string | null) => Promise<void> // rejects with Error .code INVALID_LOCALE | UNSUPPORTED",
939
+ formatDate: "(value: string | Date | number | null, options?: { time?: boolean }) => string // \"—\" when empty or unreadable",
933
940
  },
934
941
  requiredContextSlice: ["i18n.t", "i18n.locale"],
935
942
  scopes: null,
@@ -5377,8 +5384,8 @@ const CHARGE_CURRENCY = "SEK";
5377
5384
  // which reads this table.
5378
5385
  //
5379
5386
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5380
- // react-native-web do not agree on its output (the same reason widgets format
5381
- // dates with `date-fns` rather than `toLocaleDateString`), and this string ends
5387
+ // react-native-web do not agree on its output (dates differ only in spacing, so
5388
+ // `useI18n().formatDate` uses Intl; a price must match exactly), and this string ends
5382
5389
  // up on a price the buyer compares against the amount they are charged. An
5383
5390
  // explicit table renders byte-identically on both hosts.
5384
5391
  //
@@ -7130,7 +7137,9 @@ const CONTRACT = deepFreeze({
7130
7137
  // `appOperations` it calls; a `connectorRef` property may name one with
7131
7138
  // `template`. Checked by `appstudio-widget lint --manifest`. The template
7132
7139
  // contract is shared with the action SDK (`./connector-template`).
7133
- version: "1.278.0",
7140
+ // 1.279.0: additive (sc-18049) — useI18n() returns formatDate(value, { time }?),
7141
+ // a date in the app's language with its month named; "—" when empty.
7142
+ version: "1.279.0",
7134
7143
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7135
7144
  hooks: HOOKS,
7136
7145
  primitives: PRIMITIVES,
@@ -7739,4 +7748,5 @@ export {
7739
7748
  SDK_TEXTS,
7740
7749
  sdkText,
7741
7750
  fillSdkText,
7751
+ formatDateForDisplay,
7742
7752
  };
@@ -0,0 +1,150 @@
1
+ // The value-to-text half of the date contract, shared by `<DateTimePicker>`'s
2
+ // field label and `useI18n().formatDate`. No imports, so the CommonJS copy the
3
+ // backend loads through contract.cjs stays standalone.
4
+
5
+ const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})/;
6
+ const TIME_ONLY = /^(\d{2}):(\d{2})/;
7
+
8
+ export function formatToIso(date, mode) {
9
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
10
+ if (mode === "date") {
11
+ // Calendar dates are timezone-free: May 28 in Stockholm stays May 28 in NYC.
12
+ const y = String(date.getFullYear()).padStart(4, "0");
13
+ const m = String(date.getMonth() + 1).padStart(2, "0");
14
+ const d = String(date.getDate()).padStart(2, "0");
15
+ return `${y}-${m}-${d}`;
16
+ }
17
+ if (mode === "time") {
18
+ const h = String(date.getHours()).padStart(2, "0");
19
+ const mm = String(date.getMinutes()).padStart(2, "0");
20
+ return `${h}:${mm}`;
21
+ }
22
+ // datetime — full UTC ISO so the wire format round-trips through a DATE column.
23
+ return date.toISOString();
24
+ }
25
+
26
+ export function normaliseMode(mode) {
27
+ return mode === "time" || mode === "datetime" ? mode : "date";
28
+ }
29
+
30
+ /**
31
+ * A stored value as the local wall-clock parts the picker edits, or null when
32
+ * it is empty or unreadable. `month` is 0-based, as `Date` counts it.
33
+ *
34
+ * @returns {{year: number, month: number, day: number, hours: number, minutes: number} | null}
35
+ */
36
+ export function valueToParts(value, mode) {
37
+ if (value == null || value === "") return null;
38
+ const text = String(value);
39
+ const effectiveMode = normaliseMode(mode);
40
+ if (effectiveMode === "time") {
41
+ const match = TIME_ONLY.exec(text);
42
+ if (!match) return null;
43
+ const hours = Number(match[1]);
44
+ const minutes = Number(match[2]);
45
+ if (hours > 23 || minutes > 59) return null;
46
+ return { year: null, month: null, day: null, hours, minutes };
47
+ }
48
+ // A date column holds a calendar date, never an instant: read its head as is.
49
+ const dateOnly = DATE_ONLY.exec(text);
50
+ if (effectiveMode === "date" || (dateOnly && text.length === 10)) {
51
+ if (!dateOnly) return null;
52
+ return checkedParts(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]), 0, 0);
53
+ }
54
+ const d = new Date(text);
55
+ if (Number.isNaN(d.getTime())) return null;
56
+ return {
57
+ year: d.getFullYear(),
58
+ month: d.getMonth(),
59
+ day: d.getDate(),
60
+ hours: d.getHours(),
61
+ minutes: d.getMinutes(),
62
+ };
63
+ }
64
+
65
+ function checkedParts(year, month, day, hours, minutes) {
66
+ const d = new Date(year, month, day, hours, minutes);
67
+ if (d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day) return null;
68
+ return { year, month, day, hours, minutes };
69
+ }
70
+
71
+ export function partsToDate(parts) {
72
+ return new Date(parts.year, parts.month, parts.day, parts.hours || 0, parts.minutes || 0);
73
+ }
74
+
75
+ export function nowParts(now = new Date()) {
76
+ return {
77
+ year: now.getFullYear(),
78
+ month: now.getMonth(),
79
+ day: now.getDate(),
80
+ hours: now.getHours(),
81
+ minutes: now.getMinutes(),
82
+ };
83
+ }
84
+
85
+ // Built once per locale and options: construction is slow on Hermes. Each
86
+ // formats the wall-clock time in UTC, so a cached one never keeps a stale zone.
87
+ const FORMATTERS = new Map();
88
+
89
+ // Hermes ships a partial Intl; any refusal falls back to the ISO shape.
90
+ function intlFormat(locale, options, date) {
91
+ const key = `${locale || ""}|${JSON.stringify(options)}`;
92
+ try {
93
+ let formatter = FORMATTERS.get(key);
94
+ if (!formatter) {
95
+ formatter = new Intl.DateTimeFormat(locale || undefined, { ...options, timeZone: "UTC" });
96
+ FORMATTERS.set(key, formatter);
97
+ }
98
+ const wallClock = new Date(0);
99
+ wallClock.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
100
+ wallClock.setUTCHours(date.getHours(), date.getMinutes(), 0, 0);
101
+ return formatter.format(wallClock);
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ const DATE_LABEL = { year: "numeric", month: "short", day: "numeric" };
108
+ const TIME_LABEL = { hour: "2-digit", minute: "2-digit" };
109
+
110
+ export function partsLabel(parts, mode, locale) {
111
+ if (mode === "time") {
112
+ const date = new Date(2000, 0, 1, parts.hours, parts.minutes);
113
+ return intlFormat(locale, TIME_LABEL, date) || formatToIso(date, "time");
114
+ }
115
+ const date = partsToDate(parts);
116
+ if (mode === "date") {
117
+ return intlFormat(locale, DATE_LABEL, date) || formatToIso(date, "date");
118
+ }
119
+ return (
120
+ intlFormat(locale, { ...DATE_LABEL, ...TIME_LABEL }, date) ||
121
+ `${formatToIso(date, "date")} ${formatToIso(date, "time")}`
122
+ );
123
+ }
124
+
125
+ export const NO_DATE = "—";
126
+
127
+ // A DATE column answers as UTC midnight, so without `time` that is a calendar date.
128
+ const UTC_MIDNIGHT = /^\d{4}-\d{2}-\d{2}T00:00(:00(\.0+)?)?Z$/;
129
+
130
+ /**
131
+ * `useI18n().formatDate`: a value in the app's language with its month named
132
+ * (`Jan 3, 2027`, `3 jan. 2027`), plus the time when `options.time` is set. A
133
+ * bare `YYYY-MM-DD` never shows a time. Without `time`, an instant at exactly
134
+ * midnight UTC shows its UTC day. Empty or unreadable input gives `NO_DATE`;
135
+ * it never throws.
136
+ */
137
+ export function formatDateForDisplay(value, locale, options) {
138
+ const withTime = Boolean(options && options.time);
139
+ if (value instanceof Date || typeof value === "number") {
140
+ const instant = new Date(value);
141
+ if (Number.isNaN(instant.getTime())) return NO_DATE;
142
+ return partsLabel(nowParts(instant), withTime ? "datetime" : "date", locale);
143
+ }
144
+ if (typeof value !== "string" || !value) return NO_DATE;
145
+ const calendarDate =
146
+ value.length === 10 || (!withTime && UTC_MIDNIGHT.test(value)) ? value.slice(0, 10) : null;
147
+ const parts = valueToParts(calendarDate || value, "datetime");
148
+ if (!parts) return NO_DATE;
149
+ return partsLabel(parts, withTime && !calendarDate ? "datetime" : "date", locale);
150
+ }