@wix/himalaya-cli 0.1446.0 → 0.1448.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.
Files changed (98) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/state/src/index.d.ts +2 -1
  2. package/dist/cli.mjs +38 -27
  3. package/dist/preview-assets.generated.bin +0 -0
  4. package/guides/designing-himi-screens.md +7 -5
  5. package/guides/push-cli-onboarding.md +31 -0
  6. package/guides/recipe-dynamic-list.md +9 -0
  7. package/guides/sdk-reference.json +1 -1
  8. package/guides/wix-api-usage.md +17 -0
  9. package/guides/wix-sdk-overview.md +1 -0
  10. package/package.json +2 -2
  11. package/templates/beauty-salon/tier5-src/_shared/collection-query.ts +43 -9
  12. package/templates/beauty-salon/tier5-src/_shared/collection-service.ts +15 -3
  13. package/templates/beauty-salon/tier5-src/_shared/iap-presentation.ts +3 -1
  14. package/templates/beauty-salon-owner/dev/index.ts +3 -14
  15. package/templates/beauty-salon-owner/tier5-src/_shared/collection-query.ts +43 -9
  16. package/templates/beauty-salon-owner/tier5-src/_shared/collection-service.ts +15 -3
  17. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  18. package/templates/beauty-salon-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  19. package/templates/branded-lite/tier5-src/_shared/collection-query.ts +43 -9
  20. package/templates/branded-lite/tier5-src/_shared/collection-service.ts +15 -3
  21. package/templates/branded-lite/tier5-src/_shared/iap-presentation.ts +3 -1
  22. package/templates/community-club/tier5-src/_shared/collection-query.ts +43 -9
  23. package/templates/community-club/tier5-src/_shared/collection-service.ts +15 -3
  24. package/templates/community-club/tier5-src/_shared/iap-presentation.ts +3 -1
  25. package/templates/community-club-owner/dev/index.ts +3 -14
  26. package/templates/community-club-owner/tier5-src/_shared/collection-query.ts +43 -9
  27. package/templates/community-club-owner/tier5-src/_shared/collection-service.ts +15 -3
  28. package/templates/community-club-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  29. package/templates/community-club-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  30. package/templates/events-meetups/tier5-src/_shared/collection-query.ts +43 -9
  31. package/templates/events-meetups/tier5-src/_shared/collection-service.ts +15 -3
  32. package/templates/events-meetups/tier5-src/_shared/iap-presentation.ts +3 -1
  33. package/templates/events-meetups-owner/dev/index.ts +3 -14
  34. package/templates/events-meetups-owner/tier5-src/_shared/collection-query.ts +43 -9
  35. package/templates/events-meetups-owner/tier5-src/_shared/collection-service.ts +15 -3
  36. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  37. package/templates/events-meetups-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  38. package/templates/gym-fitness/tier5-src/_shared/collection-query.ts +43 -9
  39. package/templates/gym-fitness/tier5-src/_shared/collection-service.ts +15 -3
  40. package/templates/gym-fitness/tier5-src/_shared/iap-presentation.ts +3 -1
  41. package/templates/gym-fitness-owner/dev/index.ts +3 -14
  42. package/templates/gym-fitness-owner/tier5-src/_shared/collection-query.ts +43 -9
  43. package/templates/gym-fitness-owner/tier5-src/_shared/collection-service.ts +15 -3
  44. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  45. package/templates/gym-fitness-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  46. package/templates/nonprofit-cause/tier5-src/_shared/collection-query.ts +43 -9
  47. package/templates/nonprofit-cause/tier5-src/_shared/collection-service.ts +15 -3
  48. package/templates/nonprofit-cause/tier5-src/_shared/iap-presentation.ts +3 -1
  49. package/templates/nonprofit-cause-owner/dev/index.ts +3 -14
  50. package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-query.ts +43 -9
  51. package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-service.ts +15 -3
  52. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  53. package/templates/nonprofit-cause-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  54. package/templates/owner-lite/dev/index.ts +3 -14
  55. package/templates/owner-lite/tier5-src/_shared/collection-query.ts +43 -9
  56. package/templates/owner-lite/tier5-src/_shared/collection-service.ts +15 -3
  57. package/templates/owner-lite/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  58. package/templates/owner-lite/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  59. package/templates/podcast-creator/tier5-src/_shared/collection-query.ts +43 -9
  60. package/templates/podcast-creator/tier5-src/_shared/collection-service.ts +15 -3
  61. package/templates/podcast-creator/tier5-src/_shared/iap-presentation.ts +3 -1
  62. package/templates/podcast-creator-owner/dev/index.ts +3 -14
  63. package/templates/podcast-creator-owner/tier5-src/_shared/collection-query.ts +43 -9
  64. package/templates/podcast-creator-owner/tier5-src/_shared/collection-service.ts +15 -3
  65. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  66. package/templates/podcast-creator-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  67. package/templates/portfolio-creative/tier5-src/_shared/collection-query.ts +43 -9
  68. package/templates/portfolio-creative/tier5-src/_shared/collection-service.ts +15 -3
  69. package/templates/portfolio-creative/tier5-src/_shared/iap-presentation.ts +3 -1
  70. package/templates/portfolio-creative-owner/dev/index.ts +3 -14
  71. package/templates/portfolio-creative-owner/tier5-src/_shared/collection-query.ts +43 -9
  72. package/templates/portfolio-creative-owner/tier5-src/_shared/collection-service.ts +15 -3
  73. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  74. package/templates/portfolio-creative-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  75. package/templates/restaurant/tier5-src/_shared/collection-query.ts +43 -9
  76. package/templates/restaurant/tier5-src/_shared/collection-service.ts +15 -3
  77. package/templates/restaurant/tier5-src/_shared/iap-presentation.ts +3 -1
  78. package/templates/restaurant-owner/dev/index.ts +3 -14
  79. package/templates/restaurant-owner/tier5-src/_shared/collection-query.ts +43 -9
  80. package/templates/restaurant-owner/tier5-src/_shared/collection-service.ts +15 -3
  81. package/templates/restaurant-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  82. package/templates/restaurant-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  83. package/templates/retail-store/tier5-src/_shared/collection-query.ts +43 -9
  84. package/templates/retail-store/tier5-src/_shared/collection-service.ts +15 -3
  85. package/templates/retail-store/tier5-src/_shared/iap-presentation.ts +3 -1
  86. package/templates/retail-store-owner/dev/index.ts +3 -14
  87. package/templates/retail-store-owner/tier5-src/_shared/collection-query.ts +43 -9
  88. package/templates/retail-store-owner/tier5-src/_shared/collection-service.ts +15 -3
  89. package/templates/retail-store-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  90. package/templates/retail-store-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
  91. package/templates/yoga-studio/tier5-src/_shared/collection-query.ts +43 -9
  92. package/templates/yoga-studio/tier5-src/_shared/collection-service.ts +15 -3
  93. package/templates/yoga-studio/tier5-src/_shared/iap-presentation.ts +3 -1
  94. package/templates/yoga-studio-owner/dev/index.ts +3 -14
  95. package/templates/yoga-studio-owner/tier5-src/_shared/collection-query.ts +43 -9
  96. package/templates/yoga-studio-owner/tier5-src/_shared/collection-service.ts +15 -3
  97. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-manage/index.ts +17 -12
  98. package/templates/yoga-studio-owner/tier5-src/himi-owner-lite-manage/logic.ts +18 -5
@@ -110,13 +110,26 @@ export function countText(metric: Metric, label: string): string {
110
110
  return `${count}${metric.hasMore ? "+" : ""} ${label}`;
111
111
  }
112
112
 
113
- /** Apply independently loaded metrics. A failed source stays visibly unknown;
114
- * it never becomes a misleading zero. */
115
- export function withMetrics(areas: ManageArea[], metrics: Record<string, Metric | undefined>, unavailable: Set<string>): ManageArea[] {
113
+ /** Why a summary could not load: the area's app is not on the site, the owner may not read it, or the read failed.
114
+ * From the LEADING status only, as Today reads it (`isSectionUnavailable`): a transient
115
+ * `HTTP 503: {"message":"upstream returned 404"}` is a failure, not a missing app. */
116
+ export type MetricFailure = "notSetUp" | "noAccess" | "failed";
117
+
118
+ export function metricFailure(error: unknown): MetricFailure {
119
+ const text = String((error as Error)?.message ?? error);
120
+ if (/^HTTP (?:404|428)\b/.test(text) || /^HTTP \d{3} \[FAILED_PRECONDITION\]/.test(text)) return "notSetUp";
121
+ if (/^HTTP 403\b/.test(text) || /^HTTP \d{3} \[PERMISSION_DENIED\]/.test(text)) return "noAccess";
122
+ return "failed";
123
+ }
124
+
125
+ /** Apply independently loaded metrics. A failed source stays visibly unknown, saying why on its own row
126
+ * ([failures]: metric key → that row's status); it never becomes a misleading zero. */
127
+ export function withMetrics(areas: ManageArea[], metrics: Record<string, Metric | undefined>, failures: Map<string, string>): ManageArea[] {
116
128
  return areas.map(area => {
117
129
  const metric = metrics[area.metricKey];
118
- if (!metric || unavailable.has(area.metricKey)) {
119
- return { ...area, metricText: "—", statusText: "Couldn’t load summary", unavailable: true };
130
+ const failure = failures.get(area.metricKey);
131
+ if (!metric || failure !== undefined) {
132
+ return { ...area, metricText: "—", statusText: failure ?? "", unavailable: true };
120
133
  }
121
134
  return {
122
135
  ...area,
@@ -20,6 +20,13 @@ export interface CollectionQueryState<Row> extends CollectionPage<Row> {
20
20
  pageError: boolean;
21
21
  complete: boolean;
22
22
  error: string;
23
+ /** The rows are the source's `cached` page, shown while the live read is still out. */
24
+ provisional?: boolean;
25
+ }
26
+ /** What a collection showed, as `shownPage` hands it out and `seed` takes it back on a restored boot. */
27
+ export interface CollectionShownPage<Row> {
28
+ state: CollectionQueryState<Row>;
29
+ loadedPages: number;
23
30
  }
24
31
  export interface CollectionQuerySource<Row> {
25
32
  fetch(criteria: CollectionQuery, cursor: string): Promise<CollectionPage<Row>>;
@@ -50,13 +57,19 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
50
57
  let state: CollectionQueryState<Row> = { criteria: normalize({}), items: [], nextCursor: '', status: 'idle', loadingMore: false, pageError: false, complete: false, error: '' };
51
58
  /** The query a revalidation is running under: its snapshots are held back until it is done. */
52
59
  let revalidating = -1;
53
- /** What the screen shows: the last published state, restored when a revalidation fails. */
54
- let shown: { state: CollectionQueryState<Row>; loadedPages: number } | undefined;
60
+ /** The last page the screen showed whole (rows ready, nothing paging, failing or standing in): what a revalidation
61
+ * keeps on screen and restores when it fails, and what a restored boot shows. A next page loading or failing after
62
+ * it leaves those rows on screen, so it is still this. */
63
+ let lastShown: { state: CollectionQueryState<Row>; loadedPages: number } | undefined;
64
+ const sameCriteria = (a: CollectionQuery, b: CollectionQuery) => JSON.stringify(a) === JSON.stringify(b);
55
65
  let clearedByError = false;
56
66
  const snapshot = (): CollectionQueryState<Row> => ({ ...state, criteria: copyQuery(state.criteria), items: [...state.items] });
57
67
  const emit = () => {
58
68
  if (disposed || revalidating === generation) return;
59
- shown = { state: snapshot(), loadedPages };
69
+ // A settled answer replaces it, an empty one included: rows the live query proved gone are never kept.
70
+ if (state.status === 'ready' && !state.pageError && !state.loadingMore && !state.provisional) {
71
+ lastShown = state.items.length > 0 ? { state: snapshot(), loadedPages } : undefined;
72
+ }
60
73
  publish(snapshot());
61
74
  };
62
75
  const merge = (old: Row[], page: Row[]): Row[] => {
@@ -77,14 +90,14 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
77
90
  const criteria = copyQuery(state.criteria);
78
91
  if (!append) loadedPages = 0;
79
92
  state = { ...state, status: append ? 'ready' : 'loading', loadingMore: append, pageError: false, error: '',
80
- ...(append ? {} : { items: [], nextCursor: '', total: undefined, metadata: undefined, complete: false }) };
93
+ ...(append ? {} : { items: [], nextCursor: '', total: undefined, metadata: undefined, complete: false, provisional: false }) };
81
94
  emit();
82
95
  try {
83
96
  if (!append && source.cached) {
84
97
  const cached = await source.cached(criteria).catch(() => undefined);
85
98
  if (disposed || generation !== revision) return;
86
99
  if (cached?.items.length) {
87
- state = { ...state, items: merge([], cached.items), metadata: cached.metadata, status: 'ready', complete: false };
100
+ state = { ...state, items: merge([], cached.items), metadata: cached.metadata, status: 'ready', complete: false, provisional: true };
88
101
  emit();
89
102
  }
90
103
  }
@@ -94,17 +107,18 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
94
107
  state = { ...state, items: merge(append ? state.items : [], page.items), nextCursor: page.nextCursor,
95
108
  total: typeof page.total === 'number' && Number.isFinite(page.total) && page.total >= 0 ? page.total : (append ? state.total : undefined),
96
109
  metadata: page.metadata ?? (append ? state.metadata : undefined),
97
- status: 'ready', loadingMore: false, pageError: false, complete: page.complete ?? !page.nextCursor };
110
+ status: 'ready', loadingMore: false, pageError: false, complete: page.complete ?? !page.nextCursor, provisional: false };
98
111
  loadedPages++;
99
112
  } catch (error) {
100
113
  if (disposed || generation !== revision) return;
101
114
  const clear = source.clearOnError?.(error) === true;
102
115
  // Revoked access always ends what a revalidation showed, whether or not the source clears its rows.
103
116
  clearedByError = clear || /HTTP 40[13]\b/.test(String(error));
117
+ if (clearedByError) lastShown = undefined;
104
118
  if (clear) loadedPages = 0;
105
119
  state = { ...state, ...(clear ? { items: [], nextCursor: '', total: undefined, metadata: undefined } : {}),
106
120
  status: append && !clear ? 'ready' : 'error', loadingMore: false, pageError: append && !clear, complete: false,
107
- error: source.errorMessage?.(error) ?? '' };
121
+ provisional: false, error: source.errorMessage?.(error) ?? '' };
108
122
  }
109
123
  emit();
110
124
  };
@@ -117,8 +131,7 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
117
131
  const next = normalize(criteria);
118
132
  const same = JSON.stringify(next) === JSON.stringify(state.criteria);
119
133
  const count = restorePages && same ? Math.max(loadedPages, restoringPages, 1) : 1;
120
- const showing = shown && shown.state.status === 'ready' && shown.state.items.length > 0 && !shown.state.pageError
121
- && !shown.state.loadingMore && JSON.stringify(shown.state.criteria) === JSON.stringify(next) ? shown : undefined;
134
+ const showing = lastShown && sameCriteria(lastShown.state.criteria, next) ? lastShown : undefined;
122
135
  restoringPages = count;
123
136
  state = { ...state, criteria: next };
124
137
  if (revalidate && showing) { revalidating = generation + 1; clearedByError = false; }
@@ -140,6 +153,27 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
140
153
  emit();
141
154
  }
142
155
  },
156
+ /** The page the screen shows (rows ready, nothing failing or still paging), for the service to keep with its
157
+ * state; undefined when it shows none. */
158
+ shownPage(): CollectionShownPage<Row> | undefined {
159
+ if (!lastShown || !sameCriteria(lastShown.state.criteria, state.criteria)) return undefined;
160
+ const page = lastShown.state;
161
+ return { state: { ...page, criteria: copyQuery(page.criteria), items: [...page.items] }, loadedPages: lastShown.loadedPages };
162
+ },
163
+ /** A cold boot restored from disk: what the last run showed becomes what this one shows, so its first `load`
164
+ * revalidates behind it instead of starting empty. Only before the first query, and only a well-formed page. */
165
+ seed(page: unknown): boolean {
166
+ const candidate = page && typeof page === 'object' ? page as Partial<CollectionShownPage<Row>> : undefined;
167
+ const restored = candidate?.state;
168
+ if (generation !== 0 || state.status !== 'idle' || !restored || restored.status !== 'ready'
169
+ || !Array.isArray(restored.items) || restored.items.length === 0 || typeof restored.nextCursor !== 'string') return false;
170
+ try { restored.items.forEach(item => { if (!source.id(item)) throw new Error('A backend collection row requires an identity'); }); } catch { return false; }
171
+ state = { ...state, ...restored, criteria: normalize(restored.criteria ?? {}), items: [...restored.items], status: 'ready',
172
+ loadingMore: false, pageError: false, provisional: false, error: '' };
173
+ loadedPages = Math.max(1, Math.floor(Number(candidate?.loadedPages) || 1));
174
+ lastShown = { state: snapshot(), loadedPages };
175
+ return true;
176
+ },
143
177
  refresh: () => { restoringPages = 0; return fetch(false); },
144
178
  loadMore: () => fetch(true),
145
179
  retry: () => fetch(state.pageError),
@@ -142,6 +142,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
142
142
  // the query controller carries a recoverable failure. Treat each shape as
143
143
  // one collection state so the shared UI never renders a blank catalog.
144
144
  const backendState = backend?.controller.getState();
145
+ const provisional = backendState?.provisional === true;
145
146
  const errored = s.status === 'error' || s.isErrored === true || s.errored === true || backendState?.status === 'error';
146
147
  const domainError = typeof s.error === 'string' ? s.error.trim() : '';
147
148
  const queryError = typeof backendState?.error === 'string' ? backendState.error.trim() : '';
@@ -177,13 +178,17 @@ export function decorateCollection(name: string, def: { state: State; actions?:
177
178
  // un-narrowed failure. A re-query while typing keeps it (and the search field's focus).
178
179
  const hideChrome = (!narrowed && !s.nextCursor && projected.loaded < COLLECTION_CHROME_MIN_ITEMS)
179
180
  || sourceEmpty || ((loading || errored) && rows.length === 0 && !narrowed);
180
- return { ...s, collection: { ...prefs, ...projected,
181
+ // Kept with the state, so a cold boot restored from disk shows its last page and revalidates behind it.
182
+ const collectionShown = backend?.controller.shownPage();
183
+ return { ...s, ...(backend ? { collectionShown: collectionShown ?? null } : {}), collection: { ...prefs, ...projected,
181
184
  hideChrome, noActiveCriteria: !narrowed,
182
185
  viewName, viewMessage, saveMessage, noSavedViews: prefs.savedViews.length === 0,
183
186
  cursor: s.pageError === true || s.loadingMore === true ? '' : s.nextCursor,
184
187
  noMore: !s.nextCursor || s.pageError === true || s.loadingMore === true,
185
188
  noPageError: s.pageError !== true,
186
- noOffline: s.fromCache !== true,
189
+ // Rows read from the device ahead of the live read are shown as they are: "saved offline" is what stays on
190
+ // screen when the live read failed, not a first visit that is still loading.
191
+ noOffline: s.fromCache !== true || provisional,
187
192
  noError: !errored,
188
193
  noRetry: !canRetry || signInRequired,
189
194
  noSignIn: !signInRequired,
@@ -202,7 +207,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
202
207
  filtersPresented, previewPresented: !!previewId, preview: projected.items.filter(row => row.collectionId === previewId),
203
208
  persistenceLabel: persisted.available ? copyParam('collection.onDevice', 'Saved on this device') : copyParam('collection.sessionOnly', 'Choices last for this session'),
204
209
  noEmpty: loading || errored || sourceEmpty || domainNarrowed || projected.items.length > 0,
205
- summary: backend && config.backendQuery && s.fromCache
210
+ summary: backend && config.backendQuery && s.fromCache && !provisional
206
211
  ? copyParam('collection.cached', 'Saved offline · may be outdated')
207
212
  : collectionSummary({ shown: projected.items.length, loaded: projected.loaded, backend: !!(backend && config.backendQuery),
208
213
  total: typeof s.total === 'number' ? s.total : undefined, noun: config.countNoun
@@ -345,6 +350,13 @@ export function defineBackendCollection<S extends object, Row extends object>(na
345
350
  apply: (state, page) => options.apply(state as S, page as unknown as CollectionQueryState<Row>) as State,
346
351
  });
347
352
  const handle = (options.register ?? register)(name, definition);
353
+ // Registration restored the state a cold boot saved: the page it showed is this run's, before the first load. Only
354
+ // when the service's own rows came back with it: a bundle that keeps them out of the restore (its `notHydrated`)
355
+ // starts its first load as before, never from rows it chose not to restore.
356
+ const restored = (handle as { getState?: () => State }).getState?.();
357
+ const rowsKey = COLLECTIONS[name]?.rows;
358
+ const restoredRows = rowsKey ? restored?.[rowsKey] : undefined;
359
+ if (Array.isArray(restoredRows) && restoredRows.length > 0) controller.seed(restored?.collectionShown);
348
360
  publish = () => handle.collectionDataChanged();
349
361
  return handle;
350
362
  }
@@ -45,7 +45,9 @@ export function withIapPresentation<S extends object>(options: {
45
45
  return project(next);
46
46
  }]));
47
47
  const service = (options.register ?? defineService)(name, {
48
- ...definition, notHydrated: [...(definition.notHydrated ?? []), ...options.transientKeys],
48
+ // The collection's shown page goes with the rows and chrome it copies: kept out of the restore with them.
49
+ ...definition, notHydrated: [...(definition.notHydrated ?? []), ...options.transientKeys,
50
+ ...((options.transientKeys as string[]).includes('collection') ? ['collectionShown' as keyof S & string] : [])],
49
51
  actions: { ...actions, iapPublish: project, iapPoll: async () => { await commerce.poll(); return undefined; },
50
52
  iapRefresh: async () => { await commerce.loadPrices(items); return undefined; } },
51
53
  });
@@ -51769,20 +51769,6 @@ const SCREENS = runtimeSetting({
51769
51769
  }
51770
51770
  }
51771
51771
  },
51772
- {
51773
- "id": "",
51774
- "body": {
51775
- "package": "himalaya",
51776
- "type": "Text",
51777
- "props": {
51778
- "text": "$service:himiOwnerLiteManage.summaryNote",
51779
- "style": "caption",
51780
- "color": "textSecondary",
51781
- "maxLines": 2,
51782
- "collapseWhenEmpty": true
51783
- }
51784
- }
51785
- },
51786
51772
  {
51787
51773
  "id": "",
51788
51774
  "body": {
@@ -52407,6 +52393,9 @@ const SCREENS = runtimeSetting({
52407
52393
  }
52408
52394
  ]
52409
52395
  }
52396
+ },
52397
+ "modifiers": {
52398
+ "animateContentSize": true
52410
52399
  }
52411
52400
  }
52412
52401
  }
@@ -20,6 +20,13 @@ export interface CollectionQueryState<Row> extends CollectionPage<Row> {
20
20
  pageError: boolean;
21
21
  complete: boolean;
22
22
  error: string;
23
+ /** The rows are the source's `cached` page, shown while the live read is still out. */
24
+ provisional?: boolean;
25
+ }
26
+ /** What a collection showed, as `shownPage` hands it out and `seed` takes it back on a restored boot. */
27
+ export interface CollectionShownPage<Row> {
28
+ state: CollectionQueryState<Row>;
29
+ loadedPages: number;
23
30
  }
24
31
  export interface CollectionQuerySource<Row> {
25
32
  fetch(criteria: CollectionQuery, cursor: string): Promise<CollectionPage<Row>>;
@@ -50,13 +57,19 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
50
57
  let state: CollectionQueryState<Row> = { criteria: normalize({}), items: [], nextCursor: '', status: 'idle', loadingMore: false, pageError: false, complete: false, error: '' };
51
58
  /** The query a revalidation is running under: its snapshots are held back until it is done. */
52
59
  let revalidating = -1;
53
- /** What the screen shows: the last published state, restored when a revalidation fails. */
54
- let shown: { state: CollectionQueryState<Row>; loadedPages: number } | undefined;
60
+ /** The last page the screen showed whole (rows ready, nothing paging, failing or standing in): what a revalidation
61
+ * keeps on screen and restores when it fails, and what a restored boot shows. A next page loading or failing after
62
+ * it leaves those rows on screen, so it is still this. */
63
+ let lastShown: { state: CollectionQueryState<Row>; loadedPages: number } | undefined;
64
+ const sameCriteria = (a: CollectionQuery, b: CollectionQuery) => JSON.stringify(a) === JSON.stringify(b);
55
65
  let clearedByError = false;
56
66
  const snapshot = (): CollectionQueryState<Row> => ({ ...state, criteria: copyQuery(state.criteria), items: [...state.items] });
57
67
  const emit = () => {
58
68
  if (disposed || revalidating === generation) return;
59
- shown = { state: snapshot(), loadedPages };
69
+ // A settled answer replaces it, an empty one included: rows the live query proved gone are never kept.
70
+ if (state.status === 'ready' && !state.pageError && !state.loadingMore && !state.provisional) {
71
+ lastShown = state.items.length > 0 ? { state: snapshot(), loadedPages } : undefined;
72
+ }
60
73
  publish(snapshot());
61
74
  };
62
75
  const merge = (old: Row[], page: Row[]): Row[] => {
@@ -77,14 +90,14 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
77
90
  const criteria = copyQuery(state.criteria);
78
91
  if (!append) loadedPages = 0;
79
92
  state = { ...state, status: append ? 'ready' : 'loading', loadingMore: append, pageError: false, error: '',
80
- ...(append ? {} : { items: [], nextCursor: '', total: undefined, metadata: undefined, complete: false }) };
93
+ ...(append ? {} : { items: [], nextCursor: '', total: undefined, metadata: undefined, complete: false, provisional: false }) };
81
94
  emit();
82
95
  try {
83
96
  if (!append && source.cached) {
84
97
  const cached = await source.cached(criteria).catch(() => undefined);
85
98
  if (disposed || generation !== revision) return;
86
99
  if (cached?.items.length) {
87
- state = { ...state, items: merge([], cached.items), metadata: cached.metadata, status: 'ready', complete: false };
100
+ state = { ...state, items: merge([], cached.items), metadata: cached.metadata, status: 'ready', complete: false, provisional: true };
88
101
  emit();
89
102
  }
90
103
  }
@@ -94,17 +107,18 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
94
107
  state = { ...state, items: merge(append ? state.items : [], page.items), nextCursor: page.nextCursor,
95
108
  total: typeof page.total === 'number' && Number.isFinite(page.total) && page.total >= 0 ? page.total : (append ? state.total : undefined),
96
109
  metadata: page.metadata ?? (append ? state.metadata : undefined),
97
- status: 'ready', loadingMore: false, pageError: false, complete: page.complete ?? !page.nextCursor };
110
+ status: 'ready', loadingMore: false, pageError: false, complete: page.complete ?? !page.nextCursor, provisional: false };
98
111
  loadedPages++;
99
112
  } catch (error) {
100
113
  if (disposed || generation !== revision) return;
101
114
  const clear = source.clearOnError?.(error) === true;
102
115
  // Revoked access always ends what a revalidation showed, whether or not the source clears its rows.
103
116
  clearedByError = clear || /HTTP 40[13]\b/.test(String(error));
117
+ if (clearedByError) lastShown = undefined;
104
118
  if (clear) loadedPages = 0;
105
119
  state = { ...state, ...(clear ? { items: [], nextCursor: '', total: undefined, metadata: undefined } : {}),
106
120
  status: append && !clear ? 'ready' : 'error', loadingMore: false, pageError: append && !clear, complete: false,
107
- error: source.errorMessage?.(error) ?? '' };
121
+ provisional: false, error: source.errorMessage?.(error) ?? '' };
108
122
  }
109
123
  emit();
110
124
  };
@@ -117,8 +131,7 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
117
131
  const next = normalize(criteria);
118
132
  const same = JSON.stringify(next) === JSON.stringify(state.criteria);
119
133
  const count = restorePages && same ? Math.max(loadedPages, restoringPages, 1) : 1;
120
- const showing = shown && shown.state.status === 'ready' && shown.state.items.length > 0 && !shown.state.pageError
121
- && !shown.state.loadingMore && JSON.stringify(shown.state.criteria) === JSON.stringify(next) ? shown : undefined;
134
+ const showing = lastShown && sameCriteria(lastShown.state.criteria, next) ? lastShown : undefined;
122
135
  restoringPages = count;
123
136
  state = { ...state, criteria: next };
124
137
  if (revalidate && showing) { revalidating = generation + 1; clearedByError = false; }
@@ -140,6 +153,27 @@ export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, p
140
153
  emit();
141
154
  }
142
155
  },
156
+ /** The page the screen shows (rows ready, nothing failing or still paging), for the service to keep with its
157
+ * state; undefined when it shows none. */
158
+ shownPage(): CollectionShownPage<Row> | undefined {
159
+ if (!lastShown || !sameCriteria(lastShown.state.criteria, state.criteria)) return undefined;
160
+ const page = lastShown.state;
161
+ return { state: { ...page, criteria: copyQuery(page.criteria), items: [...page.items] }, loadedPages: lastShown.loadedPages };
162
+ },
163
+ /** A cold boot restored from disk: what the last run showed becomes what this one shows, so its first `load`
164
+ * revalidates behind it instead of starting empty. Only before the first query, and only a well-formed page. */
165
+ seed(page: unknown): boolean {
166
+ const candidate = page && typeof page === 'object' ? page as Partial<CollectionShownPage<Row>> : undefined;
167
+ const restored = candidate?.state;
168
+ if (generation !== 0 || state.status !== 'idle' || !restored || restored.status !== 'ready'
169
+ || !Array.isArray(restored.items) || restored.items.length === 0 || typeof restored.nextCursor !== 'string') return false;
170
+ try { restored.items.forEach(item => { if (!source.id(item)) throw new Error('A backend collection row requires an identity'); }); } catch { return false; }
171
+ state = { ...state, ...restored, criteria: normalize(restored.criteria ?? {}), items: [...restored.items], status: 'ready',
172
+ loadingMore: false, pageError: false, provisional: false, error: '' };
173
+ loadedPages = Math.max(1, Math.floor(Number(candidate?.loadedPages) || 1));
174
+ lastShown = { state: snapshot(), loadedPages };
175
+ return true;
176
+ },
143
177
  refresh: () => { restoringPages = 0; return fetch(false); },
144
178
  loadMore: () => fetch(true),
145
179
  retry: () => fetch(state.pageError),
@@ -142,6 +142,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
142
142
  // the query controller carries a recoverable failure. Treat each shape as
143
143
  // one collection state so the shared UI never renders a blank catalog.
144
144
  const backendState = backend?.controller.getState();
145
+ const provisional = backendState?.provisional === true;
145
146
  const errored = s.status === 'error' || s.isErrored === true || s.errored === true || backendState?.status === 'error';
146
147
  const domainError = typeof s.error === 'string' ? s.error.trim() : '';
147
148
  const queryError = typeof backendState?.error === 'string' ? backendState.error.trim() : '';
@@ -177,13 +178,17 @@ export function decorateCollection(name: string, def: { state: State; actions?:
177
178
  // un-narrowed failure. A re-query while typing keeps it (and the search field's focus).
178
179
  const hideChrome = (!narrowed && !s.nextCursor && projected.loaded < COLLECTION_CHROME_MIN_ITEMS)
179
180
  || sourceEmpty || ((loading || errored) && rows.length === 0 && !narrowed);
180
- return { ...s, collection: { ...prefs, ...projected,
181
+ // Kept with the state, so a cold boot restored from disk shows its last page and revalidates behind it.
182
+ const collectionShown = backend?.controller.shownPage();
183
+ return { ...s, ...(backend ? { collectionShown: collectionShown ?? null } : {}), collection: { ...prefs, ...projected,
181
184
  hideChrome, noActiveCriteria: !narrowed,
182
185
  viewName, viewMessage, saveMessage, noSavedViews: prefs.savedViews.length === 0,
183
186
  cursor: s.pageError === true || s.loadingMore === true ? '' : s.nextCursor,
184
187
  noMore: !s.nextCursor || s.pageError === true || s.loadingMore === true,
185
188
  noPageError: s.pageError !== true,
186
- noOffline: s.fromCache !== true,
189
+ // Rows read from the device ahead of the live read are shown as they are: "saved offline" is what stays on
190
+ // screen when the live read failed, not a first visit that is still loading.
191
+ noOffline: s.fromCache !== true || provisional,
187
192
  noError: !errored,
188
193
  noRetry: !canRetry || signInRequired,
189
194
  noSignIn: !signInRequired,
@@ -202,7 +207,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
202
207
  filtersPresented, previewPresented: !!previewId, preview: projected.items.filter(row => row.collectionId === previewId),
203
208
  persistenceLabel: persisted.available ? copyParam('collection.onDevice', 'Saved on this device') : copyParam('collection.sessionOnly', 'Choices last for this session'),
204
209
  noEmpty: loading || errored || sourceEmpty || domainNarrowed || projected.items.length > 0,
205
- summary: backend && config.backendQuery && s.fromCache
210
+ summary: backend && config.backendQuery && s.fromCache && !provisional
206
211
  ? copyParam('collection.cached', 'Saved offline · may be outdated')
207
212
  : collectionSummary({ shown: projected.items.length, loaded: projected.loaded, backend: !!(backend && config.backendQuery),
208
213
  total: typeof s.total === 'number' ? s.total : undefined, noun: config.countNoun
@@ -345,6 +350,13 @@ export function defineBackendCollection<S extends object, Row extends object>(na
345
350
  apply: (state, page) => options.apply(state as S, page as unknown as CollectionQueryState<Row>) as State,
346
351
  });
347
352
  const handle = (options.register ?? register)(name, definition);
353
+ // Registration restored the state a cold boot saved: the page it showed is this run's, before the first load. Only
354
+ // when the service's own rows came back with it: a bundle that keeps them out of the restore (its `notHydrated`)
355
+ // starts its first load as before, never from rows it chose not to restore.
356
+ const restored = (handle as { getState?: () => State }).getState?.();
357
+ const rowsKey = COLLECTIONS[name]?.rows;
358
+ const restoredRows = rowsKey ? restored?.[rowsKey] : undefined;
359
+ if (Array.isArray(restoredRows) && restoredRows.length > 0) controller.seed(restored?.collectionShown);
348
360
  publish = () => handle.collectionDataChanged();
349
361
  return handle;
350
362
  }
@@ -17,7 +17,7 @@ import { OWNER_MODULES, ownerModuleId } from '../_shared/owner-modules.js';
17
17
  import { localPreferences } from '../_shared/local-preferences.js';
18
18
  import { stashCopy, copyParam, copyTemplate } from '../_shared/himi-copy.js';
19
19
  import { fallbackNameFrom, selectedSiteName } from '../_shared/owner-selected-site.js';
20
- import { DASHBOARD_PATHS, deriveManage, parseAreas, recentAreas, rememberArea, withMetrics, type ManageArea, type Metric } from './logic.js';
20
+ import { DASHBOARD_PATHS, deriveManage, parseAreas, recentAreas, metricFailure, rememberArea, withMetrics, type ManageArea, type Metric, type MetricFailure } from './logic.js';
21
21
 
22
22
  interface State {
23
23
  /** The business the header names: the one picked on Sites, else the descriptor's
@@ -43,7 +43,6 @@ interface State {
43
43
  noSections: boolean;
44
44
  isLoading: boolean;
45
45
  notLoading: boolean;
46
- summaryNote: string;
47
46
  handoffError: string;
48
47
  }
49
48
 
@@ -242,20 +241,26 @@ async function loadMetrics(state: State): Promise<State> {
242
241
  return newestStarted ?? settled;
243
242
  }
244
243
 
244
+ /** A row's status when its summary could not load: why, so a missing app or a denied read is not taken for a fault. */
245
+ function failureText(failure: MetricFailure): string {
246
+ switch (failure) {
247
+ case 'notSetUp': return copyParam('ownerManage.notSetUp', 'Not set up on this site');
248
+ case 'noAccess': return copyParam('ownerManage.noAccess', 'No access');
249
+ default: return copyParam('ownerManage.summaryUnavailable', 'Couldn’t load summary');
250
+ }
251
+ }
252
+
245
253
  async function readMetrics(state: State): Promise<State> {
246
254
  const keys = [...new Set(state.areas.map(area => area.metricKey))];
247
255
  const settled = await Promise.allSettled(keys.map(metricFor));
248
256
  const metrics: Record<string, Metric | undefined> = {};
249
- const unavailable = new Set<string>();
257
+ const failures = new Map<string, string>();
250
258
  settled.forEach((result, index) => {
251
259
  if (result.status === 'fulfilled') metrics[keys[index]] = result.value;
252
- else unavailable.add(keys[index]);
260
+ else failures.set(keys[index], failureText(metricFailure(result.reason)));
253
261
  });
254
- const areas = withMetrics(state.areas, metrics, unavailable);
255
- const note = unavailable.size
256
- ? copyParam('ownerManage.partialSummary', 'Some summaries couldn’t load. You can still open every business area.')
257
- : '';
258
- return derive({ ...state, areas, isLoading: false, notLoading: true, summaryNote: note, handoffError: '' }, areas);
262
+ const areas = withMetrics(state.areas, metrics, failures);
263
+ return derive({ ...state, areas, isLoading: false, notLoading: true, handoffError: '' }, areas);
259
264
  }
260
265
 
261
266
  function findArea(state: State, arg: unknown): ManageArea | undefined {
@@ -294,7 +299,7 @@ const svc = defineService<State, {
294
299
  // 'All' is always a valid filter, so the chip row paints from the first frame
295
300
  // instead of appearing (and shifting the layout) when the areas arrive.
296
301
  groups: [{ id: 'all', label: allLabel() }], summary: '', noEmpty: true,
297
- hasRecents: false, noRecents: true, noSections: true, isLoading: true, notLoading: false, summaryNote: '', handoffError: '',
302
+ hasRecents: false, noRecents: true, noSections: true, isLoading: true, notLoading: false, handoffError: '',
298
303
  },
299
304
  actions: {
300
305
  load: async (state, arg) => {
@@ -313,7 +318,7 @@ const svc = defineService<State, {
313
318
  const parsed = (() => { try { return JSON.parse(str(arg, 'areas') || '[]'); } catch { return []; } })();
314
319
  const areas = parseAreas(parsed);
315
320
  if (state.status === 'ready' && sameAreas(state.areas, areas)) return loadMetrics(revalidating(state, areas));
316
- return loadMetrics(derive({ ...state, status: 'ready', areas, isLoading: true, notLoading: false, summaryNote: '', handoffError: '' }, areas));
321
+ return loadMetrics(derive({ ...state, status: 'ready', areas, isLoading: true, notLoading: false, handoffError: '' }, areas));
317
322
  },
318
323
  // Refresh re-reads summaries for KNOWN areas. Before the descriptor has
319
324
  // delivered them there is nothing to refresh, and settling here would open
@@ -321,7 +326,7 @@ const svc = defineService<State, {
321
326
  // it is re-read either way.
322
327
  refresh: async state => {
323
328
  currentBusinessName = selectedSiteName(fallbackBusinessName);
324
- return state.status !== 'ready' ? { ...state, businessName: currentBusinessName } : loadMetrics(derive({ ...state, isLoading: true, notLoading: false, summaryNote: '', handoffError: '' }));
329
+ return state.status !== 'ready' ? { ...state, businessName: currentBusinessName } : loadMetrics(derive({ ...state, isLoading: true, notLoading: false, handoffError: '' }));
325
330
  },
326
331
  search: (state, arg) => derive({ ...state, query: str(arg, 'value').slice(0, 256) }),
327
332
  filter: (state, arg) => {
@@ -110,13 +110,26 @@ export function countText(metric: Metric, label: string): string {
110
110
  return `${count}${metric.hasMore ? "+" : ""} ${label}`;
111
111
  }
112
112
 
113
- /** Apply independently loaded metrics. A failed source stays visibly unknown;
114
- * it never becomes a misleading zero. */
115
- export function withMetrics(areas: ManageArea[], metrics: Record<string, Metric | undefined>, unavailable: Set<string>): ManageArea[] {
113
+ /** Why a summary could not load: the area's app is not on the site, the owner may not read it, or the read failed.
114
+ * From the LEADING status only, as Today reads it (`isSectionUnavailable`): a transient
115
+ * `HTTP 503: {"message":"upstream returned 404"}` is a failure, not a missing app. */
116
+ export type MetricFailure = "notSetUp" | "noAccess" | "failed";
117
+
118
+ export function metricFailure(error: unknown): MetricFailure {
119
+ const text = String((error as Error)?.message ?? error);
120
+ if (/^HTTP (?:404|428)\b/.test(text) || /^HTTP \d{3} \[FAILED_PRECONDITION\]/.test(text)) return "notSetUp";
121
+ if (/^HTTP 403\b/.test(text) || /^HTTP \d{3} \[PERMISSION_DENIED\]/.test(text)) return "noAccess";
122
+ return "failed";
123
+ }
124
+
125
+ /** Apply independently loaded metrics. A failed source stays visibly unknown, saying why on its own row
126
+ * ([failures]: metric key → that row's status); it never becomes a misleading zero. */
127
+ export function withMetrics(areas: ManageArea[], metrics: Record<string, Metric | undefined>, failures: Map<string, string>): ManageArea[] {
116
128
  return areas.map(area => {
117
129
  const metric = metrics[area.metricKey];
118
- if (!metric || unavailable.has(area.metricKey)) {
119
- return { ...area, metricText: "—", statusText: "Couldn’t load summary", unavailable: true };
130
+ const failure = failures.get(area.metricKey);
131
+ if (!metric || failure !== undefined) {
132
+ return { ...area, metricText: "—", statusText: failure ?? "", unavailable: true };
120
133
  }
121
134
  return {
122
135
  ...area,