@colixsystems/widget-sdk 0.340.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/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,
@@ -4375,6 +4382,13 @@ const MANIFEST_SCHEMA = {
4375
4382
  "Optional (REQ-L10N-WIDGET). Translation strings the widget ships. Shape { <key>: { en: string, <locale>?: string, ... } } — `en` is REQUIRED per key. At install the host merges these into the tenant's localization dictionary under a per-widget namespace (`widget.<manifest.id>.<key>`); `useI18n().t(\"<key>\")` resolves the namespaced key automatically, so authors never type the prefix. Non-destructive: an existing admin-edited value is never overwritten, and a language the tenant has not added is never created (values for absent locales are dropped; the widget's `en` seeds the tenant's base language so every key renders). Keys persist across uninstalls; admins prune them from the Translations admin (bulk delete by `widget.<id>.` prefix). Limits: ≤500 keys; each key matches /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/; each value ≤1 KB; the namespaced key must fit the dictionary key cap (128 chars).",
4376
4383
  default: {},
4377
4384
  },
4385
+ connectorTemplates: {
4386
+ type: "array",
4387
+ required: false,
4388
+ description:
4389
+ "Optional. The REST connectors the widget calls, created in the installing workspace at install so the installer only adds the credential. Each entry is { key, name, baseUrl, authType?, authConfig?, defaultHeaders?, description?, appOperations }, the same contract an Action's connectorTemplates follow, plus `appOperations` (required): the operations the widget calls with `useConnector(connectorId).call(\"<operation>\", { params, query, body })`, each { key, method, path, query?, body? }. The connector is created callable from the app with exactly those operations. A manifest never carries a credential (a token, password, API key value or client secret): publishing one is refused, and the installer enters it on the connector. Declare `connectors.call:*` in requestedScopes, and give the widget a `connectorRef` property with `template: \"<key>\"` so placing it binds the property to the connector its install created. A reinstall or an upgrade keeps the installer's credential and creates no second connector. An upgrade that adds or changes an operation, asks its token for more, or moves the connector to another host is not applied to an installed connector, so keep the operations an earlier version listed working. At most 4 templates.",
4390
+ default: [],
4391
+ },
4378
4392
  };
4379
4393
 
4380
4394
  const WIDGET_CONTEXT_SHAPE = {
@@ -5375,8 +5389,8 @@ const CHARGE_CURRENCY = "SEK";
5375
5389
  // which reads this table.
5376
5390
  //
5377
5391
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5378
- // react-native-web do not agree on its output (the same reason widgets format
5379
- // 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
5380
5394
  // up on a price the buyer compares against the amount they are charged. An
5381
5395
  // explicit table renders byte-identically on both hosts.
5382
5396
  //
@@ -7123,7 +7137,14 @@ const CONTRACT = deepFreeze({
7123
7137
  // script's own run, inside a 1 s cap on the whole press, so a press can
7124
7138
  // wait up to about 1 s before ACTION_TIMEOUT. A press that never started
7125
7139
  // its script rejects RATE_LIMITED (429, Retry-After: 1): nothing ran.
7126
- version: "1.277.0",
7140
+ // 1.278.0: additive (sc-17829) — manifest `connectorTemplates`: the REST
7141
+ // connectors a widget ships, provisioned at install with the
7142
+ // `appOperations` it calls; a `connectorRef` property may name one with
7143
+ // `template`. Checked by `appstudio-widget lint --manifest`. The template
7144
+ // contract is shared with the action SDK (`./connector-template`).
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",
7127
7148
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7128
7149
  hooks: HOOKS,
7129
7150
  primitives: PRIMITIVES,
@@ -7732,4 +7753,5 @@ module.exports = {
7732
7753
  SDK_TEXTS,
7733
7754
  sdkText,
7734
7755
  fillSdkText,
7756
+ formatDateForDisplay,
7735
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,
@@ -4370,6 +4377,13 @@ const MANIFEST_SCHEMA = {
4370
4377
  "Optional (REQ-L10N-WIDGET). Translation strings the widget ships. Shape { <key>: { en: string, <locale>?: string, ... } } — `en` is REQUIRED per key. At install the host merges these into the tenant's localization dictionary under a per-widget namespace (`widget.<manifest.id>.<key>`); `useI18n().t(\"<key>\")` resolves the namespaced key automatically, so authors never type the prefix. Non-destructive: an existing admin-edited value is never overwritten, and a language the tenant has not added is never created (values for absent locales are dropped; the widget's `en` seeds the tenant's base language so every key renders). Keys persist across uninstalls; admins prune them from the Translations admin (bulk delete by `widget.<id>.` prefix). Limits: ≤500 keys; each key matches /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/; each value ≤1 KB; the namespaced key must fit the dictionary key cap (128 chars).",
4371
4378
  default: {},
4372
4379
  },
4380
+ connectorTemplates: {
4381
+ type: "array",
4382
+ required: false,
4383
+ description:
4384
+ "Optional. The REST connectors the widget calls, created in the installing workspace at install so the installer only adds the credential. Each entry is { key, name, baseUrl, authType?, authConfig?, defaultHeaders?, description?, appOperations }, the same contract an Action's connectorTemplates follow, plus `appOperations` (required): the operations the widget calls with `useConnector(connectorId).call(\"<operation>\", { params, query, body })`, each { key, method, path, query?, body? }. The connector is created callable from the app with exactly those operations. A manifest never carries a credential (a token, password, API key value or client secret): publishing one is refused, and the installer enters it on the connector. Declare `connectors.call:*` in requestedScopes, and give the widget a `connectorRef` property with `template: \"<key>\"` so placing it binds the property to the connector its install created. A reinstall or an upgrade keeps the installer's credential and creates no second connector. An upgrade that adds or changes an operation, asks its token for more, or moves the connector to another host is not applied to an installed connector, so keep the operations an earlier version listed working. At most 4 templates.",
4385
+ default: [],
4386
+ },
4373
4387
  };
4374
4388
 
4375
4389
  const WIDGET_CONTEXT_SHAPE = {
@@ -5370,8 +5384,8 @@ const CHARGE_CURRENCY = "SEK";
5370
5384
  // which reads this table.
5371
5385
  //
5372
5386
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5373
- // react-native-web do not agree on its output (the same reason widgets format
5374
- // 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
5375
5389
  // up on a price the buyer compares against the amount they are charged. An
5376
5390
  // explicit table renders byte-identically on both hosts.
5377
5391
  //
@@ -7118,7 +7132,14 @@ const CONTRACT = deepFreeze({
7118
7132
  // script's own run, inside a 1 s cap on the whole press, so a press can
7119
7133
  // wait up to about 1 s before ACTION_TIMEOUT. A press that never started
7120
7134
  // its script rejects RATE_LIMITED (429, Retry-After: 1): nothing ran.
7121
- version: "1.277.0",
7135
+ // 1.278.0: additive (sc-17829) — manifest `connectorTemplates`: the REST
7136
+ // connectors a widget ships, provisioned at install with the
7137
+ // `appOperations` it calls; a `connectorRef` property may name one with
7138
+ // `template`. Checked by `appstudio-widget lint --manifest`. The template
7139
+ // contract is shared with the action SDK (`./connector-template`).
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",
7122
7143
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7123
7144
  hooks: HOOKS,
7124
7145
  primitives: PRIMITIVES,
@@ -7727,4 +7748,5 @@ export {
7727
7748
  SDK_TEXTS,
7728
7749
  sdkText,
7729
7750
  fillSdkText,
7751
+ formatDateForDisplay,
7730
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) {