@wix/himalaya-cli 0.1871.0 → 0.1873.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/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +3 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/portfolio/src/index.d.ts +19 -0
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{ab91dfb9c348c8c78f942a5b88ba90df456c5b436e135d97791d5dd95d6a40dc.bin → a9d34f09c807f1cde9ab000737f0f7b849670c37908aa47cb77889b7e01d34cb.bin} +1 -1
- package/dist/browser-plane/sw.js +9 -9
- package/dist/cli.mjs +506 -323
- package/dist/preview-assets.generated.bin +0 -0
- package/fixtures/wix-canned.json +8 -0
- package/guides/release-notes.md +18 -0
- package/guides/sdk-reference.json +8 -1
- package/package.json +2 -2
- package/template-icons/professional-services.png +0 -0
- package/templates/bare-fashion/config.ts +37 -2
- package/templates/bare-fashion/dev/index.ts +4006 -48
- package/templates/bare-fashion/himalaya.content.json +15 -0
- package/templates/bare-fashion/tier5-src/_shared/member-account-routes.ts +56 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
- package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
- package/templates/branded-lite/dev/index.ts +2 -1
- package/templates/branded-lite/tier5-src/_shared/portfolio-details.ts +70 -0
- package/templates/branded-lite/tier5-src/himi-branded-lite-coupons/index.ts +13 -2
- package/templates/branded-lite/tier5-src/himi-branded-lite-portfolio/index.ts +90 -9
- package/templates/branded-lite/tier5-src/himi-branded-lite-portfolio-project/index.ts +53 -4
- package/templates/branded-lite/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/community-club/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/conference/config.ts +43 -1
- package/templates/conference/dev/index.ts +4127 -0
- package/templates/conference/himalaya.content.json +18 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
- package/templates/conference/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
- package/templates/conference/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/conference/tier5-src/wix-spaces-delete-account/index.ts +59 -0
- package/templates/events-meetups/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/gym-fitness/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/medical-services/config.ts +42 -0
- package/templates/medical-services/dev/index.ts +4136 -0
- package/templates/medical-services/himalaya.content.json +18 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
- package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
- package/templates/medical-services/tier5-src/wix-spaces-delete-account/index.ts +59 -0
- package/templates/nonprofit-cause/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/podcast-creator/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/portfolio-creative/dev/index.ts +2 -1
- package/templates/portfolio-creative/tier5-src/_shared/portfolio-details.ts +70 -0
- package/templates/portfolio-creative/tier5-src/himi-branded-lite-portfolio/index.ts +90 -9
- package/templates/portfolio-creative/tier5-src/himi-branded-lite-portfolio-project/index.ts +53 -4
- package/templates/portfolio-creative/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/professional-services/README.md +55 -0
- package/templates/professional-services/config.ts +436 -0
- package/templates/professional-services/dev/index.ts +44772 -0
- package/templates/professional-services/himalaya.content.json +100 -0
- package/templates/professional-services/himalaya.template.json +16 -0
- package/templates/professional-services/icon.png +0 -0
- package/templates/professional-services/platforms.json +1 -0
- package/templates/professional-services/tier5-src/_shared/app-locale.ts +70 -0
- package/templates/professional-services/tier5-src/_shared/booking-location.ts +147 -0
- package/templates/professional-services/tier5-src/_shared/booking-session.ts +224 -0
- package/templates/professional-services/tier5-src/_shared/branded-lite-hosted.ts +282 -0
- package/templates/professional-services/tier5-src/_shared/branded-load-state.ts +109 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-copy.ts +40 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-history.ts +51 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-model.ts +56 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-presenter.ts +587 -0
- package/templates/professional-services/tier5-src/_shared/business-chat-transport.ts +164 -0
- package/templates/professional-services/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/professional-services/tier5-src/_shared/collection-contract.ts +232 -0
- package/templates/professional-services/tier5-src/_shared/collection-query.ts +201 -0
- package/templates/professional-services/tier5-src/_shared/collection-service.ts +429 -0
- package/templates/professional-services/tier5-src/_shared/detail-presence.ts +51 -0
- package/templates/professional-services/tier5-src/_shared/engine-intl.ts +538 -0
- package/templates/professional-services/tier5-src/_shared/event-registration.ts +86 -0
- package/templates/professional-services/tier5-src/_shared/events-inline-options.ts +77 -0
- package/templates/professional-services/tier5-src/_shared/faq-list.ts +405 -0
- package/templates/professional-services/tier5-src/_shared/featured-event.ts +63 -0
- package/templates/professional-services/tier5-src/_shared/group-member-count.ts +15 -0
- package/templates/professional-services/tier5-src/_shared/group-privacy.ts +14 -0
- package/templates/professional-services/tier5-src/_shared/guest-sign-in.ts +36 -0
- package/templates/professional-services/tier5-src/_shared/himi-account.ts +222 -0
- package/templates/professional-services/tier5-src/_shared/himi-blog-hidden.ts +66 -0
- package/templates/professional-services/tier5-src/_shared/himi-blog-post-row.ts +214 -0
- package/templates/professional-services/tier5-src/_shared/himi-blog-saved.ts +64 -0
- package/templates/professional-services/tier5-src/_shared/himi-booking-saved.ts +88 -0
- package/templates/professional-services/tier5-src/_shared/himi-bookings.ts +318 -0
- package/templates/professional-services/tier5-src/_shared/himi-copy.ts +123 -0
- package/templates/professional-services/tier5-src/_shared/himi-events.ts +92 -0
- package/templates/professional-services/tier5-src/_shared/himi-media.ts +33 -0
- package/templates/professional-services/tier5-src/_shared/himi-store.ts +7 -0
- package/templates/professional-services/tier5-src/_shared/himi-text.ts +24 -0
- package/templates/professional-services/tier5-src/_shared/host-events.ts +66 -0
- package/templates/professional-services/tier5-src/_shared/hosted-checkout.ts +70 -0
- package/templates/professional-services/tier5-src/_shared/iap-attendance-form.ts +106 -0
- package/templates/professional-services/tier5-src/_shared/iap-attendance-purchase.ts +235 -0
- package/templates/professional-services/tier5-src/_shared/iap-attendance.ts +38 -0
- package/templates/professional-services/tier5-src/_shared/iap-worker.ts +127 -0
- package/templates/professional-services/tier5-src/_shared/inbox-rooms.ts +163 -0
- package/templates/professional-services/tier5-src/_shared/local-preferences.ts +38 -0
- package/templates/professional-services/tier5-src/_shared/member-access.ts +63 -0
- package/templates/professional-services/tier5-src/_shared/member-account-routes.ts +56 -0
- package/templates/professional-services/tier5-src/_shared/member-avatar.ts +76 -0
- package/templates/professional-services/tier5-src/_shared/member-bookings.ts +107 -0
- package/templates/professional-services/tier5-src/_shared/member-read.ts +82 -0
- package/templates/professional-services/tier5-src/_shared/member-screen.ts +99 -0
- package/templates/professional-services/tier5-src/_shared/notification-target.ts +141 -0
- package/templates/professional-services/tier5-src/_shared/offset-page.ts +10 -0
- package/templates/professional-services/tier5-src/_shared/online-actions.ts +76 -0
- package/templates/professional-services/tier5-src/_shared/owner-load-error.ts +348 -0
- package/templates/professional-services/tier5-src/_shared/payment-setup.ts +6 -0
- package/templates/professional-services/tier5-src/_shared/portfolio-details.ts +70 -0
- package/templates/professional-services/tier5-src/_shared/pricing-plan-display.ts +64 -0
- package/templates/professional-services/tier5-src/_shared/relative-time.ts +21 -0
- package/templates/professional-services/tier5-src/_shared/result-snackbar.ts +26 -0
- package/templates/professional-services/tier5-src/_shared/rich-body.ts +78 -0
- package/templates/professional-services/tier5-src/_shared/rich-content-link.ts +34 -0
- package/templates/professional-services/tier5-src/_shared/sign-in-sheet.ts +18 -0
- package/templates/professional-services/tier5-src/_shared/staff-name.ts +18 -0
- package/templates/professional-services/tier5-src/_shared/weekly-goal.ts +111 -0
- package/templates/professional-services/tier5-src/_shared/wix-bi.ts +85 -0
- package/templates/professional-services/tier5-src/_shared/wix-member-links.ts +114 -0
- package/templates/professional-services/tier5-src/_shared/wix-service-price.ts +146 -0
- package/templates/professional-services/tier5-src/business-chat/index.ts +797 -0
- package/templates/professional-services/tier5-src/business-contact/index.ts +6 -0
- package/templates/professional-services/tier5-src/himi-blog-feed/index.ts +444 -0
- package/templates/professional-services/tier5-src/himi-blog-post/index.ts +1239 -0
- package/templates/professional-services/tier5-src/himi-booking-account/index.ts +278 -0
- package/templates/professional-services/tier5-src/himi-booking-bookings/index.ts +475 -0
- package/templates/professional-services/tier5-src/himi-booking-service/index.ts +1197 -0
- package/templates/professional-services/tier5-src/himi-booking-services/index.ts +795 -0
- package/templates/professional-services/tier5-src/himi-booking-time/index.ts +1840 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-coupons/index.ts +96 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-faq/index.ts +6 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-file-share/index.ts +12 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-group/index.ts +310 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-group-about/index.ts +240 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-my-groups/index.ts +237 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-notifications/index.ts +263 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-plans/index.ts +498 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-portfolio/index.ts +136 -0
- package/templates/professional-services/tier5-src/himi-branded-lite-portfolio-project/index.ts +198 -0
- package/templates/professional-services/tier5-src/himi-events-detail/index.ts +1306 -0
- package/templates/professional-services/tier5-src/himi-events-list/index.ts +171 -0
- package/templates/professional-services/tier5-src/himi-events-my-events/index.ts +227 -0
- package/templates/professional-services/tier5-src/himi-events-rsvp/index.ts +230 -0
- package/templates/professional-services/tier5-src/himi-professional-services-community/index.ts +318 -0
- package/templates/professional-services/tier5-src/himi-professional-services-home/index.ts +772 -0
- package/templates/professional-services/tier5-src/himi-store-account/index.ts +1514 -0
- package/templates/professional-services/tier5-src/wix-spaces-coupon-detail/index.ts +43 -0
- package/templates/professional-services/tier5-src/wix-spaces-my-subscriptions/index.ts +89 -0
- package/templates/professional-services/tier5-src/wix-spaces-subscription-detail/index.ts +139 -0
- package/templates/professional-services/tokens.json +456 -0
- package/templates/restaurant/tier5-src/himi-events-list/index.ts +5 -1
- package/templates/salon-spa/config.ts +42 -0
- package/templates/salon-spa/dev/index.ts +4136 -0
- package/templates/salon-spa/himalaya.content.json +18 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
- package/templates/salon-spa/tier5-src/wix-spaces-delete-account/index.ts +59 -0
- package/templates/wholesale-store/config.ts +43 -1
- package/templates/wholesale-store/dev/index.ts +4136 -0
- package/templates/wholesale-store/himalaya.content.json +18 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
- package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
- package/templates/wholesale-store/tier5-src/wix-spaces-delete-account/index.ts +59 -0
- package/templates/yoga-studio/tier5-src/himi-events-list/index.ts +5 -1
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Backend collection lifecycle shared by domain workers. The domain supplies
|
|
2
|
+
* the query and row mapper; this layer never calls a domain API or mutates it. */
|
|
3
|
+
export interface CollectionQuery {
|
|
4
|
+
query: string;
|
|
5
|
+
filter: string;
|
|
6
|
+
sort: 'default' | 'az' | 'za';
|
|
7
|
+
savedIds: string[];
|
|
8
|
+
/** What the list is limited to beyond the controls above (a domain's own selection, e.g. the events of some categories), as one
|
|
9
|
+
* canonical string. Part of the criteria, so a list opened on another selection never shows or restores this one's rows. Absent
|
|
10
|
+
* when there is none: criteria without it keep the key they always had. */
|
|
11
|
+
scope?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface CollectionPage<Row> {
|
|
14
|
+
items: Row[];
|
|
15
|
+
nextCursor: string;
|
|
16
|
+
total?: number;
|
|
17
|
+
metadata?: Record<string, unknown>;
|
|
18
|
+
complete?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface CollectionQueryState<Row> extends CollectionPage<Row> {
|
|
21
|
+
criteria: CollectionQuery;
|
|
22
|
+
status: 'idle' | 'loading' | 'ready' | 'error';
|
|
23
|
+
loadingMore: boolean;
|
|
24
|
+
pageError: boolean;
|
|
25
|
+
complete: boolean;
|
|
26
|
+
error: string;
|
|
27
|
+
/** The rows are the source's `cached` page, shown while the live read is still out. */
|
|
28
|
+
provisional?: boolean;
|
|
29
|
+
}
|
|
30
|
+
/** What a collection showed, as `shownPage` hands it out and `seed` takes it back on a restored boot. */
|
|
31
|
+
export interface CollectionShownPage<Row> {
|
|
32
|
+
state: CollectionQueryState<Row>;
|
|
33
|
+
loadedPages: number;
|
|
34
|
+
}
|
|
35
|
+
export interface CollectionQuerySource<Row> {
|
|
36
|
+
fetch(criteria: CollectionQuery, cursor: string): Promise<CollectionPage<Row>>;
|
|
37
|
+
/** Optional public cache for immediate paint; always incomplete, never a paging authority. */
|
|
38
|
+
cached?(criteria: CollectionQuery): Promise<CollectionPage<Row> | undefined>;
|
|
39
|
+
id(row: Row): string;
|
|
40
|
+
errorMessage?(error: unknown): string;
|
|
41
|
+
/** Private collections must discard prior rows when access or identity changes. A revalidation keeps the
|
|
42
|
+
* rows it shows through any other failure: safe because one worker never serves two identities (its pool
|
|
43
|
+
* key carries the account, and a purge tears parked workers down). */
|
|
44
|
+
clearOnError?(error: unknown): boolean;
|
|
45
|
+
}
|
|
46
|
+
/** A scope is read back by its domain, so it is never cut: this exceeds the largest selection the events list encodes (100 ids of 64 characters, about 6.9k). */
|
|
47
|
+
const SCOPE_MAX = 8192;
|
|
48
|
+
const normalize = (q: Partial<CollectionQuery>): CollectionQuery => ({
|
|
49
|
+
query: typeof q.query === 'string' ? q.query.trim().slice(0, 256) : '',
|
|
50
|
+
filter: typeof q.filter === 'string' ? q.filter.slice(0, 256) : 'all',
|
|
51
|
+
sort: q.sort === 'az' || q.sort === 'za' ? q.sort : 'default',
|
|
52
|
+
savedIds: Array.isArray(q.savedIds) ? [...new Set(q.savedIds.filter(id => typeof id === 'string' && id.length > 0 && id.length <= 256))].slice(0, 500) : [],
|
|
53
|
+
|
|
54
|
+
...(typeof q.scope === 'string' && q.scope ? { scope: q.scope.slice(0, SCOPE_MAX) } : {}),
|
|
55
|
+
});
|
|
56
|
+
const copyQuery = (q: CollectionQuery): CollectionQuery => ({ ...q, savedIds: [...q.savedIds] });
|
|
57
|
+
|
|
58
|
+
/** New criteria cancel the old result logically, including an in-flight next
|
|
59
|
+
* page. Failures preserve the cursor and rows for an explicit retry. Callers
|
|
60
|
+
* publish each snapshot through their ordinary service reducer, so loading and
|
|
61
|
+
* filtered-empty never masquerade as a successfully completed query. */
|
|
62
|
+
export function createCollectionQuery<Row>(source: CollectionQuerySource<Row>, publish: (state: CollectionQueryState<Row>) => void) {
|
|
63
|
+
let generation = 0, disposed = false;
|
|
64
|
+
let loadedPages = 0, restoringPages = 0;
|
|
65
|
+
let state: CollectionQueryState<Row> = { criteria: normalize({}), items: [], nextCursor: '', status: 'idle', loadingMore: false, pageError: false, complete: false, error: '' };
|
|
66
|
+
/** The query a revalidation is running under: its snapshots are held back until it is done. */
|
|
67
|
+
let revalidating = -1;
|
|
68
|
+
/** The last page the screen showed whole (rows ready, nothing paging, failing or standing in): what a revalidation
|
|
69
|
+
* keeps on screen and restores when it fails, and what a restored boot shows. A next page loading or failing after
|
|
70
|
+
* it leaves those rows on screen, so it is still this. */
|
|
71
|
+
let lastShown: { state: CollectionQueryState<Row>; loadedPages: number } | undefined;
|
|
72
|
+
const sameCriteria = (a: CollectionQuery, b: CollectionQuery) => JSON.stringify(a) === JSON.stringify(b);
|
|
73
|
+
let clearedByError = false;
|
|
74
|
+
const snapshot = (): CollectionQueryState<Row> => ({ ...state, criteria: copyQuery(state.criteria), items: [...state.items] });
|
|
75
|
+
const emit = () => {
|
|
76
|
+
if (disposed || revalidating === generation) return;
|
|
77
|
+
// A settled answer replaces it, an empty one included: rows the live query proved gone are never kept, and a list
|
|
78
|
+
// with nothing in it comes back as its empty state, never its loading look.
|
|
79
|
+
if (state.status === 'ready' && !state.pageError && !state.loadingMore && !state.provisional) {
|
|
80
|
+
lastShown = { state: snapshot(), loadedPages };
|
|
81
|
+
}
|
|
82
|
+
publish(snapshot());
|
|
83
|
+
};
|
|
84
|
+
const merge = (old: Row[], page: Row[]): Row[] => {
|
|
85
|
+
const positions = new Map<string, number>(), result: Row[] = [];
|
|
86
|
+
for (const item of [...old, ...page]) {
|
|
87
|
+
const id = source.id(item);
|
|
88
|
+
if (!id) throw new Error('A backend collection row requires an identity');
|
|
89
|
+
const index = positions.get(id);
|
|
90
|
+
if (index === undefined) { positions.set(id, result.length); result.push(item); }
|
|
91
|
+
else result[index] = item;
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
};
|
|
95
|
+
/** [keepRows]: a search typed over the rows on screen leaves them there until its answer arrives (status stays
|
|
96
|
+
* `loading`, and nothing pages under the old answer), so the list is not blanked on each keystroke. */
|
|
97
|
+
const fetch = async (append: boolean, keepRows = false): Promise<void> => {
|
|
98
|
+
if (disposed || (append && (state.loadingMore || state.status === 'loading' || !state.nextCursor))) return;
|
|
99
|
+
const revision = append ? generation : ++generation;
|
|
100
|
+
const cursor = append ? state.nextCursor : '';
|
|
101
|
+
const criteria = copyQuery(state.criteria);
|
|
102
|
+
if (!append) loadedPages = 0;
|
|
103
|
+
state = { ...state, status: append ? 'ready' : 'loading', loadingMore: append, pageError: false, error: '',
|
|
104
|
+
...(append ? {} : keepRows ? { nextCursor: '', complete: false, provisional: false }
|
|
105
|
+
: { items: [], nextCursor: '', total: undefined, metadata: undefined, complete: false, provisional: false }) };
|
|
106
|
+
emit();
|
|
107
|
+
try {
|
|
108
|
+
if (!append && source.cached) {
|
|
109
|
+
const cached = await source.cached(criteria).catch(() => undefined);
|
|
110
|
+
if (disposed || generation !== revision) return;
|
|
111
|
+
if (cached?.items.length) {
|
|
112
|
+
state = { ...state, items: merge([], cached.items), metadata: cached.metadata, status: 'ready', complete: false, provisional: true };
|
|
113
|
+
emit();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const page = await source.fetch(criteria, cursor);
|
|
117
|
+
if (disposed || generation !== revision) return;
|
|
118
|
+
if (!Array.isArray(page.items) || typeof page.nextCursor !== 'string' || (cursor && page.nextCursor === cursor)) throw new Error('Invalid collection page');
|
|
119
|
+
state = { ...state, items: merge(append ? state.items : [], page.items), nextCursor: page.nextCursor,
|
|
120
|
+
total: typeof page.total === 'number' && Number.isFinite(page.total) && page.total >= 0 ? page.total : (append ? state.total : undefined),
|
|
121
|
+
metadata: page.metadata ?? (append ? state.metadata : undefined),
|
|
122
|
+
status: 'ready', loadingMore: false, pageError: false, complete: page.complete ?? !page.nextCursor, provisional: false };
|
|
123
|
+
loadedPages++;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (disposed || generation !== revision) return;
|
|
126
|
+
const clear = source.clearOnError?.(error) === true;
|
|
127
|
+
// Revoked access always ends what a revalidation showed, whether or not the source clears its rows.
|
|
128
|
+
clearedByError = clear || /HTTP 40[13]\b/.test(String(error));
|
|
129
|
+
if (clearedByError) lastShown = undefined;
|
|
130
|
+
if (clear) loadedPages = 0;
|
|
131
|
+
// The rows a typed search kept on screen while it ran were never its answer: a failed one shows none of them.
|
|
132
|
+
const drop = clear || keepRows;
|
|
133
|
+
state = { ...state, ...(drop ? { items: [], nextCursor: '', total: undefined, metadata: undefined } : {}),
|
|
134
|
+
status: append && !clear ? 'ready' : 'error', loadingMore: false, pageError: append && !clear, complete: false,
|
|
135
|
+
provisional: false, error: source.errorMessage?.(error) ?? '' };
|
|
136
|
+
}
|
|
137
|
+
emit();
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
getState: snapshot,
|
|
141
|
+
/** [revalidate]: a screen coming back re-queries the rows it shows. They stay on screen until every
|
|
142
|
+
* page is in, and a failure keeps them; revoked access still clears them, and other criteria reset. */
|
|
143
|
+
async query(criteria: Partial<CollectionQuery>, restorePages = false, revalidate = false): Promise<void> {
|
|
144
|
+
if (disposed) return Promise.resolve();
|
|
145
|
+
const next = normalize(criteria);
|
|
146
|
+
const same = JSON.stringify(next) === JSON.stringify(state.criteria);
|
|
147
|
+
const count = restorePages && same ? Math.max(loadedPages, restoringPages, 1) : 1;
|
|
148
|
+
const showing = lastShown && sameCriteria(lastShown.state.criteria, next) ? lastShown : undefined;
|
|
149
|
+
restoringPages = count;
|
|
150
|
+
// Only the search text changed: the user is typing over the rows on screen, also while the last keystroke's
|
|
151
|
+
// search is still out.
|
|
152
|
+
const typing = !same && (state.status === 'ready' || state.status === 'loading')
|
|
153
|
+
&& sameCriteria({ ...state.criteria, query: '' }, { ...next, query: '' });
|
|
154
|
+
state = { ...state, criteria: next };
|
|
155
|
+
if (revalidate && showing) { revalidating = generation + 1; clearedByError = false; }
|
|
156
|
+
const pending = fetch(false, typing);
|
|
157
|
+
const revision = generation;
|
|
158
|
+
await pending;
|
|
159
|
+
// Re-appearance revalidates every previously opened page using fresh
|
|
160
|
+
// cursors. A changed query, error or revoked access stops the restoration.
|
|
161
|
+
while (!disposed && generation === revision && loadedPages < count && state.status === 'ready'
|
|
162
|
+
&& !state.pageError && !state.loadingMore && state.nextCursor) await fetch(true);
|
|
163
|
+
if (generation === revision) restoringPages = 0;
|
|
164
|
+
if (revalidating === revision) {
|
|
165
|
+
revalidating = -1;
|
|
166
|
+
if (generation !== revision) return;
|
|
167
|
+
if ((state.status !== 'ready' || state.pageError) && showing && !clearedByError) {
|
|
168
|
+
state = { ...showing.state, criteria: next };
|
|
169
|
+
loadedPages = showing.loadedPages;
|
|
170
|
+
}
|
|
171
|
+
emit();
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
/** The page the screen shows (rows ready, nothing failing or still paging), for the service to keep with its
|
|
175
|
+
* state; undefined when it shows none. */
|
|
176
|
+
shownPage(): CollectionShownPage<Row> | undefined {
|
|
177
|
+
if (!lastShown || !sameCriteria(lastShown.state.criteria, state.criteria)) return undefined;
|
|
178
|
+
const page = lastShown.state;
|
|
179
|
+
return { state: { ...page, criteria: copyQuery(page.criteria), items: [...page.items] }, loadedPages: lastShown.loadedPages };
|
|
180
|
+
},
|
|
181
|
+
/** A cold boot restored from disk: what the last run showed becomes what this one shows, so its first `load`
|
|
182
|
+
* revalidates behind it instead of starting empty. Only before the first query, and only a well-formed page; an
|
|
183
|
+
* empty one is the list's empty state. */
|
|
184
|
+
seed(page: unknown): boolean {
|
|
185
|
+
const candidate = page && typeof page === 'object' ? page as Partial<CollectionShownPage<Row>> : undefined;
|
|
186
|
+
const restored = candidate?.state;
|
|
187
|
+
if (generation !== 0 || state.status !== 'idle' || !restored || restored.status !== 'ready'
|
|
188
|
+
|| !Array.isArray(restored.items) || typeof restored.nextCursor !== 'string') return false;
|
|
189
|
+
try { restored.items.forEach(item => { if (!source.id(item)) throw new Error('A backend collection row requires an identity'); }); } catch { return false; }
|
|
190
|
+
state = { ...state, ...restored, criteria: normalize(restored.criteria ?? {}), items: [...restored.items], status: 'ready',
|
|
191
|
+
loadingMore: false, pageError: false, provisional: false, error: '' };
|
|
192
|
+
loadedPages = Math.max(1, Math.floor(Number(candidate?.loadedPages) || 1));
|
|
193
|
+
lastShown = { state: snapshot(), loadedPages };
|
|
194
|
+
return true;
|
|
195
|
+
},
|
|
196
|
+
refresh: () => { restoringPages = 0; return fetch(false); },
|
|
197
|
+
loadMore: () => fetch(true),
|
|
198
|
+
retry: () => fetch(state.pageError),
|
|
199
|
+
dispose() { disposed = true; generation++; },
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
import { defineService as register, type ServiceDefinition } from '@himalaya/state';
|
|
2
|
+
import { COLLECTIONS, COLLECTION_CHROME_MIN_ITEMS, initialCollection, normalizeCollection, projectCollection, collectionId, collectionActionsLabel, type CollectionRow } from './collection-contract.js';
|
|
3
|
+
import { localPreferences, type PreferenceRuntime } from './local-preferences.js';
|
|
4
|
+
import { copyParam, stashCopy } from './himi-copy.js';
|
|
5
|
+
import { createCollectionQuery, type CollectionQuerySource, type CollectionQueryState } from './collection-query.js';
|
|
6
|
+
// The shape `memberAvatarSource` (member-avatar.ts) returns, declared here rather than imported:
|
|
7
|
+
// a starter that never asks for the avatar does not ship member-avatar.ts, and a type import of a
|
|
8
|
+
// missing file fails its strict type check.
|
|
9
|
+
type MemberAvatarFactory = (changed: () => void) => {
|
|
10
|
+
readonly keys: readonly string[];
|
|
11
|
+
onLoad(arg: unknown): void;
|
|
12
|
+
merge<T extends object>(state: T): T;
|
|
13
|
+
resetRestored(svc: { getState(): unknown }): void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export interface CollectionSaving {
|
|
17
|
+
read(): string[];
|
|
18
|
+
write(ids: string[], rows: Record<string, unknown>[]): void;
|
|
19
|
+
}
|
|
20
|
+
type State = Record<string, unknown>;
|
|
21
|
+
interface BackendCollection {
|
|
22
|
+
restorePagesOnLoad?: boolean;
|
|
23
|
+
/** Sees the load action's argument (the screen's onAppear params) BEFORE the query runs. A returned
|
|
24
|
+
* `{ filter, sort }` resets the criteria for that load (a screen that always opens on one view). */
|
|
25
|
+
onLoad?(arg: unknown): CollectionCriteriaReset | void;
|
|
26
|
+
/** The collection's own selection as part of every query's criteria (see `CollectionQuery.scope`); "" for none. */
|
|
27
|
+
scope?(): string;
|
|
28
|
+
controller: ReturnType<typeof createCollectionQuery<CollectionRow>>;
|
|
29
|
+
apply(state: State, page: CollectionQueryState<CollectionRow>): State;
|
|
30
|
+
}
|
|
31
|
+
/** A filter and a sort set together (`collectionCriteria`, `onLoad`). Values the collection's contract does
|
|
32
|
+
* not list are ignored. */
|
|
33
|
+
export interface CollectionCriteriaReset { filter?: string; sort?: string; query?: string }
|
|
34
|
+
type Reducer = (s: State, ...args: unknown[]) => State | undefined | Promise<State | undefined>;
|
|
35
|
+
const object = (x: unknown): State => x && typeof x === 'object' && !Array.isArray(x) ? x as State : {};
|
|
36
|
+
const str = (arg: unknown, key: string): string => typeof arg === 'string' ? arg : String(object(arg)[key] ?? '');
|
|
37
|
+
|
|
38
|
+
/** The toolbar count line — "12 dishes", or "3 of 12 dishes" while a filter narrows the list.
|
|
39
|
+
*
|
|
40
|
+
* It used to read "12 / 12 loaded" and "2 / 2 results" ([branded-lite-qa] #3002): the numbers
|
|
41
|
+
* described the implementation (a client-side filter over a fetched page) rather than what the
|
|
42
|
+
* customer is looking at, and the slash-and-suffix wrapped onto two lines on web. When the
|
|
43
|
+
* backend total is unknown the count shown is simply what is shown; the "Load more" button is
|
|
44
|
+
* what says there is more. */
|
|
45
|
+
export function collectionSummary(o: { shown: number; loaded: number; total?: number; backend?: boolean; noun?: [string, string] }): string {
|
|
46
|
+
const [one, many] = o.noun ?? [copyParam('collection.itemOne', 'item'), copyParam('collection.itemMany', 'items')];
|
|
47
|
+
const whole = o.backend ? (typeof o.total === 'number' ? o.total : o.shown) : o.loaded;
|
|
48
|
+
const noun = (whole === 1 ? one : many);
|
|
49
|
+
return o.shown < whole ? `${o.shown} ${copyParam('collection.of', 'of')} ${whole} ${noun}` : `${o.shown} ${o.shown === 1 ? one : many}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Opt-in decorator. Domain reducers remain authoritative; collection preferences
|
|
53
|
+
* survive reducers which replace their entire state, including async refreshes. */
|
|
54
|
+
export function decorateCollection(name: string, def: { state: State; actions?: Record<string, Reducer> }, saving?: CollectionSaving, backend?: BackendCollection) {
|
|
55
|
+
const config = COLLECTIONS[name];
|
|
56
|
+
if (!config) return def;
|
|
57
|
+
const runtime = (globalThis as { himalaya?: PreferenceRuntime }).himalaya;
|
|
58
|
+
let instanceId = '';
|
|
59
|
+
if (config.instanceInput) {
|
|
60
|
+
let instance = runtime?.input?.[config.instanceInput];
|
|
61
|
+
try { if (typeof instance === 'string') instance = JSON.parse(instance); } catch { instance = undefined; }
|
|
62
|
+
const id = object(instance).id;
|
|
63
|
+
if (typeof id === 'string' && id.length > 0 && id.length <= 256) instanceId = id;
|
|
64
|
+
}
|
|
65
|
+
// Dynamic collections must never read the shared service-level key. Without
|
|
66
|
+
// a configured instance identity they remain session-only.
|
|
67
|
+
const persisted = localPreferences(`collection.${name}${config.instanceInput ? `.${encodeURIComponent(instanceId)}` : ''}`,
|
|
68
|
+
value => normalizeCollection(config, value), config.instanceInput && !instanceId ? {} : runtime);
|
|
69
|
+
let prefs = persisted.read();
|
|
70
|
+
let lastUndo: string[] | undefined;
|
|
71
|
+
let generation = 0;
|
|
72
|
+
let previewId = '';
|
|
73
|
+
let filtersPresented = false;
|
|
74
|
+
let viewName = '';
|
|
75
|
+
let viewMessage = '';
|
|
76
|
+
let saveMessage = '';
|
|
77
|
+
const syncSaved = () => {
|
|
78
|
+
if (!saving) return;
|
|
79
|
+
try {
|
|
80
|
+
const ids = saving.read();
|
|
81
|
+
if (JSON.stringify(ids) !== JSON.stringify(prefs.savedIds)) lastUndo = undefined;
|
|
82
|
+
prefs.savedIds = ids;
|
|
83
|
+
} catch { prefs.savedIds = []; }
|
|
84
|
+
};
|
|
85
|
+
/** Navigation can open a collection in a useful, reviewable context. Keep
|
|
86
|
+
* this input additive and constrained to the same criteria the collection UI
|
|
87
|
+
* can select; arbitrary route values must never become backend filters. */
|
|
88
|
+
/** Labels of the worker-listed filter choices (`filterValuesFrom`), minus the "All" row. */
|
|
89
|
+
const listedFilters = (state: State): string[] => config.filterValuesFrom && Array.isArray(state[config.filterValuesFrom])
|
|
90
|
+
? (state[config.filterValuesFrom] as unknown[]).flatMap(row => {
|
|
91
|
+
const r = row && typeof row === 'object' ? row as Record<string, unknown> : {};
|
|
92
|
+
return typeof r.label === 'string' && r.id !== '' ? [r.label] : [];
|
|
93
|
+
})
|
|
94
|
+
: [];
|
|
95
|
+
let pendingFilter = '';
|
|
96
|
+
const applyNavigationCriteria = (arg: unknown, state: State): boolean => {
|
|
97
|
+
const input = object(arg);
|
|
98
|
+
let changed = false;
|
|
99
|
+
if (Object.prototype.hasOwnProperty.call(input, 'collectionQuery')) {
|
|
100
|
+
prefs.query = String(input.collectionQuery ?? '').slice(0, 256);
|
|
101
|
+
changed = true;
|
|
102
|
+
}
|
|
103
|
+
if (Object.prototype.hasOwnProperty.call(input, 'collectionSort')) {
|
|
104
|
+
const sort = String(input.collectionSort ?? '');
|
|
105
|
+
if (sort === 'default' || sort === 'az' || sort === 'za') { prefs.sort = sort; changed = true; }
|
|
106
|
+
}
|
|
107
|
+
if (Object.prototype.hasOwnProperty.call(input, 'collectionFilter')) {
|
|
108
|
+
const filter = String(input.collectionFilter ?? '');
|
|
109
|
+
const configured = config.filterValues ?? [];
|
|
110
|
+
const rows = Array.isArray(state[config.rows]) ? state[config.rows] as CollectionRow[] : [];
|
|
111
|
+
const derived = config.filter ? rows.map(row => String(row[config.filter!] ?? '')).filter(Boolean) : [];
|
|
112
|
+
const known = listedFilters(state);
|
|
113
|
+
const allowed = filter === 'all' || filter === 'saved' ||
|
|
114
|
+
(filter.startsWith('value:') && [...configured, ...derived, ...known].includes(filter.slice(6)));
|
|
115
|
+
if (allowed) { prefs.filter = filter; changed = true; }
|
|
116
|
+
// A worker-listed choice (e.g. a blog category) may not have loaded yet at boot:
|
|
117
|
+
// hold it and settle it against the list once the list arrives, instead of
|
|
118
|
+
// discarding a valid deep link before load().
|
|
119
|
+
else if (filter.startsWith('value:') && config.filterValuesFrom && known.length === 0) pendingFilter = filter;
|
|
120
|
+
}
|
|
121
|
+
if (changed) {
|
|
122
|
+
prefs.selectedIds = [];
|
|
123
|
+
prefs.selecting = false;
|
|
124
|
+
persisted.write(prefs);
|
|
125
|
+
}
|
|
126
|
+
return changed;
|
|
127
|
+
};
|
|
128
|
+
// A worker's module-level `svc.load()` has no action argument. Navigation
|
|
129
|
+
// params are injected into `himalaya.input` before module evaluation, so
|
|
130
|
+
// apply the same constrained criteria here before that boot request reads
|
|
131
|
+
// `prefs`. The load wrapper below still handles hosts that pass criteria as
|
|
132
|
+
// an explicit action argument.
|
|
133
|
+
applyNavigationCriteria(runtime?.input, def.state);
|
|
134
|
+
const derive = (s: State): State => {
|
|
135
|
+
syncSaved();
|
|
136
|
+
const rows = Array.isArray(s[config.rows]) ? (s[config.rows] as CollectionRow[]).filter(x => x && typeof x === 'object') : [];
|
|
137
|
+
const known = listedFilters(s);
|
|
138
|
+
if (pendingFilter && known.length) {
|
|
139
|
+
if (known.includes(pendingFilter.slice(6))) { prefs.filter = pendingFilter; persisted.write(prefs); }
|
|
140
|
+
pendingFilter = '';
|
|
141
|
+
}
|
|
142
|
+
const projected = projectCollection(rows, config, prefs, !!backend && config.backendQuery === true, known);
|
|
143
|
+
projected.items.forEach(row => {
|
|
144
|
+
row.collectionSelectLabel = row.collectionSelected ? copyParam('collection.selected', 'Selected') : copyParam('collection.select', 'Select');
|
|
145
|
+
// the save toggle names the action it WILL take for this row. The
|
|
146
|
+
// old static "Save / unsave" made the owner work out the row's state.
|
|
147
|
+
row.collectionSaveLabel = row.collectionSaved ? copyParam('collection.unsave', 'Remove from saved') : copyParam('collection.save', 'Save');
|
|
148
|
+
row.collectionActionsLabel = collectionActionsLabel(String(row.collectionTitle ?? ''),
|
|
149
|
+
copyParam('collection.itemActionsFor', 'Actions for {title}'), copyParam('collection.itemActions', 'Item actions'));
|
|
150
|
+
});
|
|
151
|
+
if (previewId && !rows.some(row => collectionId(row) === previewId)) previewId = '';
|
|
152
|
+
const filterChoices = [{ id: 'all', label: copyParam('collection.all', 'All') }, { id: 'saved', label: copyParam('collection.saved', 'Saved') },
|
|
153
|
+
...projected.filters.map(label => ({ id: `value:${label}`, label: copyParam(`collection.filter.${label}`, label) }))];
|
|
154
|
+
const loading = s.status === 'loading' || s.isLoading === true;
|
|
155
|
+
// Older domain reducers expose `errored` rather than `isErrored`; backend
|
|
156
|
+
// adapters can also intentionally keep their display status "ready" while
|
|
157
|
+
// the query controller carries a recoverable failure. Treat each shape as
|
|
158
|
+
// one collection state so the shared UI never renders a blank catalog.
|
|
159
|
+
const backendState = backend?.controller.getState();
|
|
160
|
+
const provisional = backendState?.provisional === true;
|
|
161
|
+
const errored = s.status === 'error' || s.isErrored === true || s.errored === true || backendState?.status === 'error';
|
|
162
|
+
const domainError = typeof s.error === 'string' ? s.error.trim() : '';
|
|
163
|
+
const queryError = typeof backendState?.error === 'string' ? backendState.error.trim() : '';
|
|
164
|
+
// Some domains carry their failure sentence in `emptyText` (portfolio, podcasts);
|
|
165
|
+
// the screen folds that node into this block, so keep the domain's own words.
|
|
166
|
+
const domainEmptyError = errored && typeof s.emptyText === 'string' ? s.emptyText.trim() : '';
|
|
167
|
+
const errorMessage = queryError || domainError || domainEmptyError || copyParam('collection.loadError', 'This collection could not load. Try again.');
|
|
168
|
+
const canRetry = !!backend || typeof def.actions?.refresh === 'function' || typeof def.actions?.load === 'function' || typeof def.actions?.collectionRetry === 'function';
|
|
169
|
+
// Wix refused the visitor: retrying cannot help, signing in can.
|
|
170
|
+
const signInRequired = errored && s.signInRequired === true;
|
|
171
|
+
// "the source has nothing" and "your filter matched nothing" are
|
|
172
|
+
// different states. Only the second may offer "Clear filters", and the list chrome
|
|
173
|
+
// (view, refine, chips, counter, search) means nothing over a source with no rows.
|
|
174
|
+
// Loaded-row collections hold the whole source in `rows`, so zero rows IS an empty
|
|
175
|
+
// source. A backend query returns only matches, so zero rows is source-empty only
|
|
176
|
+
// when nothing narrowed it.
|
|
177
|
+
// Anything the customer (or the domain) narrowed the result by. While narrowed, zero rows
|
|
178
|
+
// is "your filter matched nothing" and the controls that got them here must stay.
|
|
179
|
+
// The DOMAIN's own filter (config.narrowedBy, e.g. blog category) narrowed the rows: the
|
|
180
|
+
// domain owns that empty state and its clear action. The shared "Clear filters" block
|
|
181
|
+
// cannot reset a domain filter, so it never shows for one.
|
|
182
|
+
const domainNarrowed = !!config.narrowedBy && !!s[config.narrowedBy];
|
|
183
|
+
// A default view is what the screen opens on; anything else is the member's own
|
|
184
|
+
// narrowing, which keeps the chrome (and the Clear that undoes it) on screen.
|
|
185
|
+
// "All" and the collection's own default (e.g. Upcoming) are both un-narrowed: Clear
|
|
186
|
+
// resets to "All", so showing it on either would offer a reset that changes nothing.
|
|
187
|
+
const narrowed = !!prefs.query.trim() || (prefs.filter !== 'all' && prefs.filter !== initialCollection(config).filter) || domainNarrowed;
|
|
188
|
+
const sourceEmpty = !loading && !errored && rows.length === 0 &&
|
|
189
|
+
(!(backend && config.backendQuery) || !narrowed) && !domainNarrowed;
|
|
190
|
+
const emptySourceText = (typeof s.emptyText === 'string' && s.emptyText.trim()) || copyParam('collection.emptySource', 'Nothing here yet');
|
|
191
|
+
// Chrome is noise over a small un-narrowed list (fewer than COLLECTION_CHROME_MIN_ITEMS
|
|
192
|
+
// records, no further page), over an empty source, and before the FIRST load or an
|
|
193
|
+
// un-narrowed failure. A re-query while typing keeps it (and the search field's focus).
|
|
194
|
+
const hideChrome = (!narrowed && !s.nextCursor && projected.loaded < COLLECTION_CHROME_MIN_ITEMS)
|
|
195
|
+
|| sourceEmpty || ((loading || errored) && rows.length === 0 && !narrowed);
|
|
196
|
+
// Kept with the state, so a cold boot restored from disk shows its last page and revalidates behind it.
|
|
197
|
+
const collectionShown = backend?.controller.shownPage();
|
|
198
|
+
return { ...s, ...(backend ? { collectionShown: collectionShown ?? null } : {}), collection: { ...prefs, ...projected,
|
|
199
|
+
hideChrome, noActiveCriteria: !narrowed,
|
|
200
|
+
viewName, viewMessage, saveMessage, noSavedViews: prefs.savedViews.length === 0,
|
|
201
|
+
cursor: s.pageError === true || s.loadingMore === true ? '' : s.nextCursor,
|
|
202
|
+
noMore: !s.nextCursor || s.pageError === true || s.loadingMore === true,
|
|
203
|
+
noPageError: s.pageError !== true,
|
|
204
|
+
// Rows read from the device ahead of the live read are shown as they are: "saved offline" is what stays on
|
|
205
|
+
// screen when the live read failed, not a first visit that is still loading.
|
|
206
|
+
noOffline: s.fromCache !== true || provisional,
|
|
207
|
+
noError: !errored,
|
|
208
|
+
noRetry: !canRetry || signInRequired,
|
|
209
|
+
noSignIn: !signInRequired,
|
|
210
|
+
errorTitle: signInRequired ? copyParam('collection.signInTitle', 'Sign in to see this') : copyParam('collection.loadErrorTitle', 'This collection could not load'),
|
|
211
|
+
errorMessage,
|
|
212
|
+
// A skeleton only with nothing to show: a search re-running over the rows on screen keeps them.
|
|
213
|
+
noLoading: !loading || rows.length > 0,
|
|
214
|
+
// De-dup against a domain that paints its OWN empty block (screen-kit emptyBlock is
|
|
215
|
+
// gated on the domain's top-level `noEmpty`): only one empty state ever shows.
|
|
216
|
+
noEmptySource: !sourceEmpty || s.noEmpty === false,
|
|
217
|
+
emptySourceText,
|
|
218
|
+
hideList: prefs.view !== 'list', hideGrid: prefs.view !== 'grid',
|
|
219
|
+
hideComfortable: prefs.density !== 'comfortable', hideCompact: prefs.density !== 'compact',
|
|
220
|
+
selectingLabel: prefs.selecting ? copyParam('collection.done', 'Done') : copyParam('collection.select', 'Select'),
|
|
221
|
+
noSelection: !prefs.selecting, noUndo: !lastUndo,
|
|
222
|
+
cannotSaveSelected: !prefs.selectedIds.length || prefs.selectedIds.some(id => !rows.some(row => collectionId(row) === id)),
|
|
223
|
+
filtersPresented, previewPresented: !!previewId, preview: projected.items.filter(row => row.collectionId === previewId),
|
|
224
|
+
persistenceLabel: persisted.available ? copyParam('collection.onDevice', 'Saved on this device') : copyParam('collection.sessionOnly', 'Choices last for this session'),
|
|
225
|
+
noEmpty: loading || errored || sourceEmpty || domainNarrowed || projected.items.length > 0,
|
|
226
|
+
summary: backend && config.backendQuery && s.fromCache && !provisional
|
|
227
|
+
? copyParam('collection.cached', 'Saved offline · may be outdated')
|
|
228
|
+
: collectionSummary({ shown: projected.items.length, loaded: projected.loaded, backend: !!(backend && config.backendQuery),
|
|
229
|
+
total: typeof s.total === 'number' ? s.total : undefined, noun: config.countNoun
|
|
230
|
+
? [copyParam(`collection.${name}.countOne`, config.countNoun[0]), copyParam(`collection.${name}.countMany`, config.countNoun[1])] : undefined }),
|
|
231
|
+
selectedSummary: `${prefs.selectedIds.length} ${copyParam('collection.selected', 'selected')}`,
|
|
232
|
+
filterChoices,
|
|
233
|
+
chips: config.filterValues ? filterChoices.filter(choice => ['all', 'saved', prefs.filter].includes(choice.id)) : filterChoices,
|
|
234
|
+
} };
|
|
235
|
+
};
|
|
236
|
+
const actions: Record<string, Reducer> = {};
|
|
237
|
+
for (const [key, action] of Object.entries(def.actions ?? {})) {
|
|
238
|
+
actions[key] = (s, ...args) => {
|
|
239
|
+
stashCopy(args[0]);
|
|
240
|
+
const actionState = key === 'load' && applyNavigationCriteria(args[0], s) ? derive(s) : s;
|
|
241
|
+
// A new data request invalidates older requests, while presentation actions
|
|
242
|
+
// are merged at completion rather than clobbered by a captured state.
|
|
243
|
+
const isQuery = /^(load|refresh|retry|search|clearSearch)$/.test(key);
|
|
244
|
+
const previous = generation;
|
|
245
|
+
const revision = isQuery ? ++generation : generation;
|
|
246
|
+
const result = action(actionState, ...args);
|
|
247
|
+
const finish = (next: State | undefined) => {
|
|
248
|
+
// Some workers deduplicate onAppear against their boot request and return
|
|
249
|
+
// the identical state. A no-op must not supersede the request it joined.
|
|
250
|
+
if (next === actionState) {
|
|
251
|
+
if (revision !== generation) return undefined;
|
|
252
|
+
if (isQuery) generation = previous;
|
|
253
|
+
return derive(next);
|
|
254
|
+
}
|
|
255
|
+
return next === undefined || revision !== generation ? undefined : derive(next);
|
|
256
|
+
};
|
|
257
|
+
return result && typeof (result as Promise<unknown>).then === 'function'
|
|
258
|
+
? (result as Promise<State | undefined>).then(finish) : finish(result as State | undefined);
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const change = (update: (arg: unknown, s: State) => void): Reducer => (s, arg) => {
|
|
262
|
+
syncSaved();
|
|
263
|
+
const criteriaBefore = criteriaKey();
|
|
264
|
+
const before = [...prefs.savedIds], undoBefore = lastUndo;
|
|
265
|
+
update(arg, s);
|
|
266
|
+
if (saving && JSON.stringify(before) !== JSON.stringify(prefs.savedIds)) {
|
|
267
|
+
try {
|
|
268
|
+
saving.write(prefs.savedIds, Array.isArray(s[config.rows]) ? s[config.rows] as CollectionRow[] : []);
|
|
269
|
+
saveMessage = '';
|
|
270
|
+
} catch {
|
|
271
|
+
prefs.savedIds = before; lastUndo = undoBefore;
|
|
272
|
+
saveMessage = copyParam('collection.saveError', 'Could not save this change. Try again.');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
persisted.write(prefs);
|
|
276
|
+
if (backend && config.backendQuery && criteriaBefore !== criteriaKey()) return backend.controller.query(criteria()).then(() => undefined);
|
|
277
|
+
return derive(s);
|
|
278
|
+
};
|
|
279
|
+
/** Filter and sort in ONE criteria change, so a tab that sets both runs one query, not two. */
|
|
280
|
+
const setCriteria = (arg: unknown): void => {
|
|
281
|
+
const input = object(arg);
|
|
282
|
+
const sort = String(input.sort ?? '');
|
|
283
|
+
if (sort === 'default' || sort === 'az' || sort === 'za') prefs.sort = sort;
|
|
284
|
+
const filter = String(input.filter ?? '');
|
|
285
|
+
if (filter === 'all' || (filter.startsWith('value:') && (config.filterValues ?? []).includes(filter.slice(6)))) prefs.filter = filter;
|
|
286
|
+
// A screen with no search field clears a query an older screen persisted, or it narrows every view for good.
|
|
287
|
+
if (typeof input.query === 'string') prefs.query = input.query.slice(0, 256);
|
|
288
|
+
};
|
|
289
|
+
const criteria = () => ({ query: prefs.query, sort: prefs.sort, filter: prefs.filter, savedIds: prefs.filter === 'saved' ? prefs.savedIds : [], ...(backend?.scope ? { scope: backend.scope() } : {}) });
|
|
290
|
+
const criteriaKey = () => JSON.stringify(criteria());
|
|
291
|
+
actions.collectionDismissFilters = change(() => { filtersPresented = false; });
|
|
292
|
+
actions.collectionFilters = change(() => { filtersPresented = !filtersPresented; });
|
|
293
|
+
actions.collectionPreview = change(arg => { previewId = str(arg, 'id'); });
|
|
294
|
+
actions.collectionDismissPreview = change(() => { previewId = ''; });
|
|
295
|
+
actions.collectionView = change(arg => { const value = str(arg, 'selectedId'); if (value === 'list' || value === 'grid') prefs.view = value; });
|
|
296
|
+
actions.collectionDensity = change(arg => { const value = str(arg, 'selectedId'); if (value === 'compact' || value === 'comfortable') prefs.density = value; });
|
|
297
|
+
actions.collectionSort = change(arg => { const value = str(arg, 'selectedId'); if (value === 'default' || value === 'az' || value === 'za') prefs.sort = value; });
|
|
298
|
+
actions.collectionFilter = change(arg => { const values = object(arg).selectedIds; prefs.filter = Array.isArray(values) && typeof values[0] === 'string' ? values[0] : 'all'; });
|
|
299
|
+
actions.collectionSearch = change(arg => { prefs.query = str(arg, 'value').slice(0, 256); });
|
|
300
|
+
actions.collectionCriteria = change(arg => setCriteria(arg));
|
|
301
|
+
actions.collectionViewName = change(arg => { viewName = str(arg, 'value').slice(0, 40); viewMessage = ''; });
|
|
302
|
+
actions.collectionRememberView = change(() => {
|
|
303
|
+
const name = viewName.trim();
|
|
304
|
+
if (!name) { viewMessage = copyParam('collection.nameRequired', 'Give this view a name'); return; }
|
|
305
|
+
const existing = prefs.savedViews.findIndex(v => v.name.toLocaleLowerCase() === name.toLocaleLowerCase());
|
|
306
|
+
if (existing < 0 && prefs.savedViews.length >= 8) { viewMessage = copyParam('collection.viewLimit', 'Remove a saved view to add another (maximum 8)'); return; }
|
|
307
|
+
const { view, density, sort, query, filter } = prefs;
|
|
308
|
+
const entry = { id: `view-${existing < 0 ? prefs.savedViews.length : existing}`, name, view, density, sort, query, filter };
|
|
309
|
+
if (existing < 0) prefs.savedViews.push(entry); else prefs.savedViews[existing] = entry;
|
|
310
|
+
viewName = ''; viewMessage = copyParam('collection.viewSaved', 'View saved');
|
|
311
|
+
});
|
|
312
|
+
actions.collectionApplyView = change(arg => {
|
|
313
|
+
const view = prefs.savedViews.find(v => v.id === str(arg, 'id'));
|
|
314
|
+
if (!view) return;
|
|
315
|
+
const { query, filter, sort, density, view: mode } = view;
|
|
316
|
+
prefs = { ...prefs, query, filter, sort, density, view: mode, selectedIds: [], selecting: false };
|
|
317
|
+
filtersPresented = false; previewId = '';
|
|
318
|
+
});
|
|
319
|
+
actions.collectionRemoveView = change(arg => {
|
|
320
|
+
prefs.savedViews = prefs.savedViews.filter(v => v.id !== str(arg, 'id')).map((v, i) => ({ ...v, id: `view-${i}` }));
|
|
321
|
+
});
|
|
322
|
+
actions.collectionClear = change(() => { prefs.query = ''; prefs.filter = 'all'; prefs.sort = 'default'; });
|
|
323
|
+
actions.collectionSelecting = change(() => { prefs.selecting = !prefs.selecting; if (!prefs.selecting) prefs.selectedIds = []; });
|
|
324
|
+
const known = (s: State, id: string) => !!id && Array.isArray(s[config.rows]) && (s[config.rows] as CollectionRow[]).some(row => collectionId(row) === id);
|
|
325
|
+
actions.collectionSelect = change((arg, s) => { const id = str(arg, 'id'); if (known(s, id)) prefs.selectedIds = prefs.selectedIds.includes(id) ? prefs.selectedIds.filter(x => x !== id) : [...prefs.selectedIds, id]; });
|
|
326
|
+
actions.collectionSave = change((arg, s) => { const id = str(arg, 'id'); if (!known(s, id)) return; lastUndo = [...prefs.savedIds]; prefs.savedIds = prefs.savedIds.includes(id) ? prefs.savedIds.filter(x => x !== id) : [...prefs.savedIds, id]; });
|
|
327
|
+
actions.collectionSaveSelected = change((_arg, s) => { if (!prefs.selectedIds.length || prefs.selectedIds.some(id => !known(s, id))) return; lastUndo = [...prefs.savedIds]; prefs.savedIds = [...new Set([...prefs.savedIds, ...prefs.selectedIds.filter(id => known(s, id))])]; prefs.selecting = false; prefs.selectedIds = []; });
|
|
328
|
+
actions.collectionUndo = change(() => { if (lastUndo) prefs.savedIds = lastUndo; lastUndo = undefined; });
|
|
329
|
+
if (backend) {
|
|
330
|
+
actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
|
|
331
|
+
actions.load = (_s, arg) => {
|
|
332
|
+
stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
|
|
333
|
+
const reset = backend.onLoad?.(arg);
|
|
334
|
+
if (reset) { setCriteria(reset); persisted.write(prefs); }
|
|
335
|
+
// A load of what the screen already shows is the screen coming back: it revalidates behind its rows.
|
|
336
|
+
return backend.controller.query(criteria(), backend.restorePagesOnLoad, true).then(() => undefined);
|
|
337
|
+
};
|
|
338
|
+
actions.refresh = (_s, arg) => {
|
|
339
|
+
stashCopy(arg); syncSaved();
|
|
340
|
+
return backend.controller.query(criteria()).then(() => undefined);
|
|
341
|
+
};
|
|
342
|
+
actions.loadMore = () => backend.controller.loadMore().then(() => undefined);
|
|
343
|
+
actions.retry = actions.collectionRetry = () => backend.controller.retry().then(() => undefined);
|
|
344
|
+
actions.search = actions.collectionSearch;
|
|
345
|
+
actions.clearSearch = actions.collectionClear;
|
|
346
|
+
}
|
|
347
|
+
// Non-paged collections retain their domain-owned retry behavior. The shared
|
|
348
|
+
// error surface only points at an existing load/refresh reducer; it never
|
|
349
|
+
// invents a fetch or claims that a retry happened.
|
|
350
|
+
if (!actions.collectionRetry && !backend) {
|
|
351
|
+
const retry = actions.refresh ?? actions.load;
|
|
352
|
+
if (retry) actions.collectionRetry = retry;
|
|
353
|
+
}
|
|
354
|
+
return { state: derive(def.state), actions };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Domain-owned page source with shared query controls. Publishing uses a normal
|
|
358
|
+
* reducer and reads the private controller snapshot, never an SDUI payload. */
|
|
359
|
+
export function defineBackendCollection<S extends object, Row extends object>(name: string, options: {
|
|
360
|
+
register?: typeof register;
|
|
361
|
+
/** Explicit mutation preflight; unrelated collection services keep their current reducers. */
|
|
362
|
+
onlineWrites?: boolean;
|
|
363
|
+
/** Where the offline refusal is written (default `actionMessage`) — the field the screen shows next to the action. */
|
|
364
|
+
onlineWriteMessageFields?: readonly string[];
|
|
365
|
+
/** Revalidate already opened pages on navigation return; explicit refresh resets. */
|
|
366
|
+
restorePagesOnLoad?: boolean;
|
|
367
|
+
/** The load action's argument (onAppear params beyond `copy`), before the query runs — for a
|
|
368
|
+
* domain setting that rides the descriptor, e.g. My Bookings' `weeklyGoal`. */
|
|
369
|
+
onLoad?(arg: unknown): CollectionCriteriaReset | void;
|
|
370
|
+
/** A selection the list is limited to, as one canonical string ("" for none): it joins the criteria, so another selection is another
|
|
371
|
+
* result set (no stale rows behind a revalidation, no restore of another selection's pages) and `source` reads it off `criteria.scope`. */
|
|
372
|
+
scope?(): string;
|
|
373
|
+
state: S;
|
|
374
|
+
source: CollectionQuerySource<Row>;
|
|
375
|
+
apply(state: S, page: CollectionQueryState<Row>): S;
|
|
376
|
+
saving?: CollectionSaving;
|
|
377
|
+
actions?: Record<string, (state: S, ...args: unknown[]) => S | undefined | Promise<S | undefined>>;
|
|
378
|
+
/** A top-bar avatar for the signed-in member: `memberAvatarSource` from `member-avatar.ts`. Off
|
|
379
|
+
* until the screen's onAppear asks for it (`memberAvatar: "1"`); the fields are never persisted. */
|
|
380
|
+
memberAvatar?: MemberAvatarFactory;
|
|
381
|
+
}) {
|
|
382
|
+
let publish: (() => unknown) | undefined;
|
|
383
|
+
const avatar = options.memberAvatar?.(() => { publish?.(); });
|
|
384
|
+
const controller = createCollectionQuery(options.source, () => { publish?.(); });
|
|
385
|
+
const definition = decorateCollection(name, { state: options.state as State, actions: options.actions as Record<string, Reducer> | undefined }, options.saving, {
|
|
386
|
+
restorePagesOnLoad: options.restorePagesOnLoad,
|
|
387
|
+
onLoad: avatar ? arg => { avatar.onLoad(arg); return options.onLoad?.(arg); } : options.onLoad,
|
|
388
|
+
scope: options.scope,
|
|
389
|
+
controller: controller as unknown as BackendCollection['controller'],
|
|
390
|
+
apply: (state, page) => {
|
|
391
|
+
const applied = options.apply(state as S, page as unknown as CollectionQueryState<Row>) as State;
|
|
392
|
+
return avatar ? avatar.merge(applied) : applied;
|
|
393
|
+
},
|
|
394
|
+
});
|
|
395
|
+
// The member's photo belongs to this run's account: a cold boot never restores it.
|
|
396
|
+
const baseRegister = options.register ?? register;
|
|
397
|
+
const registerService = (avatar ? ((n: string, def: ServiceDefinition<unknown>) => {
|
|
398
|
+
const own = def as { notHydrated?: string[]; notPersisted?: string[] };
|
|
399
|
+
return baseRegister(n, { ...def, notHydrated: [...(own.notHydrated ?? []), ...avatar.keys], notPersisted: [...(own.notPersisted ?? []), ...avatar.keys] } as never);
|
|
400
|
+
}) : baseRegister) as typeof register;
|
|
401
|
+
// Compatibility starters retain their existing mutation behavior; accept the
|
|
402
|
+
// current authoring contract without enabling the offline-write rollout.
|
|
403
|
+
const handle = registerService(name, definition);
|
|
404
|
+
avatar?.resetRestored(handle as unknown as { getState(): unknown });
|
|
405
|
+
// Registration restored the state a cold boot saved: the page it showed is this run's, before the first load. Only
|
|
406
|
+
// when the service's own rows came back with it: a bundle that keeps them out of the restore (its `notHydrated`)
|
|
407
|
+
// starts its first load as before, never from rows it chose not to restore. Rows that came back empty are the
|
|
408
|
+
// list's own only when the page it showed was empty too; a page with rows means they were kept out.
|
|
409
|
+
const restored = (handle as { getState?: () => State }).getState?.();
|
|
410
|
+
const rowsKey = COLLECTIONS[name]?.rows;
|
|
411
|
+
const restoredRows = rowsKey ? restored?.[rowsKey] : undefined;
|
|
412
|
+
const shownItems = (restored?.collectionShown as { state?: { items?: unknown } } | undefined)?.state?.items;
|
|
413
|
+
const shownEmpty = Array.isArray(shownItems) && shownItems.length === 0;
|
|
414
|
+
if (Array.isArray(restoredRows) && (restoredRows.length > 0 || shownEmpty)) controller.seed(restored?.collectionShown);
|
|
415
|
+
publish = () => handle.collectionDataChanged();
|
|
416
|
+
return handle;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Keep the domain service's existing TypeScript API. Extra collection verbs are
|
|
420
|
+
* dispatched through SDUI and do not widen the native capability surface. */
|
|
421
|
+
export const defineService: typeof register = ((name: string, def: ServiceDefinition<unknown>) =>
|
|
422
|
+
register(name, { ...def, ...decorateCollection(name, def as unknown as { state: State; actions?: Record<string, Reducer> }) } as ServiceDefinition<State>)) as typeof register;
|
|
423
|
+
|
|
424
|
+
/** Domains can supply their existing saved-items store without putting domain
|
|
425
|
+
* data or mutations in the shared collection layer. */
|
|
426
|
+
export function withCollectionSaving(saving: CollectionSaving): typeof register {
|
|
427
|
+
return ((name: string, def: ServiceDefinition<unknown>) =>
|
|
428
|
+
register(name, decorateCollection(name, def as unknown as { state: State; actions?: Record<string, Reducer> }, saving))) as typeof register;
|
|
429
|
+
}
|