@marktiderman/genesis-ui-native 2.4.1 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/dist/{chunk-BPD5DCFP.js → chunk-3S5XVER4.js} +271 -6
- package/dist/chunk-3S5XVER4.js.map +1 -0
- package/dist/chunk-56QLEHHV.js +1231 -0
- package/dist/chunk-56QLEHHV.js.map +1 -0
- package/dist/chunk-6JBNSW4D.js +479 -0
- package/dist/chunk-6JBNSW4D.js.map +1 -0
- package/dist/{chunk-RARJGZA3.js → chunk-KZEIF4YI.js} +7 -741
- package/dist/chunk-KZEIF4YI.js.map +1 -0
- package/dist/{chunk-6TLBCRS6.js → chunk-VMSIKSU2.js} +13 -477
- package/dist/chunk-VMSIKSU2.js.map +1 -0
- package/dist/components/index.d.ts +29 -3
- package/dist/components/index.js +3 -4
- package/dist/data/index.d.ts +382 -4
- package/dist/data/index.js +1067 -19
- package/dist/data/index.js.map +1 -1
- package/dist/inbox-page-DZUR-PJ1.d.ts +199 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +5 -5
- package/dist/layouts/index.d.ts +4 -186
- package/dist/layouts/index.js +3 -3
- package/package.json +2 -2
- package/src/components/__tests__/loading-state.test.tsx +41 -0
- package/src/components/image.tsx +5 -0
- package/src/components/index.ts +3 -0
- package/src/components/loading-state.tsx +92 -0
- package/src/data/NativeDetailPanel.tsx +8 -1
- package/src/data/index.ts +1 -0
- package/src/data/resource-view/NativeResourceFormSheet.tsx +305 -0
- package/src/data/resource-view/NativeResourceView.tsx +528 -0
- package/src/data/resource-view/__tests__/native-resource-view.test.tsx +870 -0
- package/src/data/resource-view/display.tsx +256 -0
- package/src/data/resource-view/index.ts +50 -0
- package/src/data/resource-view/mapping.ts +326 -0
- package/src/data/resource-view/messages.ts +121 -0
- package/src/data/resource-view/use-native-resource-view.ts +307 -0
- package/src/layouts/__tests__/inbox-page.test.tsx +2 -1
- package/src/layouts/__tests__/screen-container.test.tsx +27 -0
- package/src/layouts/inbox-page.tsx +4 -7
- package/src/layouts/screen-container.tsx +18 -1
- package/dist/chunk-6TLBCRS6.js.map +0 -1
- package/dist/chunk-BPD5DCFP.js.map +0 -1
- package/dist/chunk-EFXCJ5AN.js +0 -234
- package/dist/chunk-EFXCJ5AN.js.map +0 -1
- package/dist/chunk-FIITITXO.js +0 -492
- package/dist/chunk-FIITITXO.js.map +0 -1
- package/dist/chunk-RARJGZA3.js.map +0 -1
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// The words NativeResourceView shows. `common` matches genesis-ui's `uiMessages.common`, so a
|
|
2
|
+
// renderer written for one platform reads the same keys on the other. `{name}`-style placeholders
|
|
3
|
+
// are filled with `fill`.
|
|
4
|
+
|
|
5
|
+
export interface NativeResourceViewMessages {
|
|
6
|
+
common: {
|
|
7
|
+
/** Shown for an empty value. */
|
|
8
|
+
empty: string;
|
|
9
|
+
yes: string;
|
|
10
|
+
no: string;
|
|
11
|
+
cancel: string;
|
|
12
|
+
save: string;
|
|
13
|
+
edit: string;
|
|
14
|
+
close: string;
|
|
15
|
+
/** "New {noun}". */
|
|
16
|
+
create: string;
|
|
17
|
+
/** "Edit {noun}". */
|
|
18
|
+
editTitle: string;
|
|
19
|
+
/** "Search {nounPlural}". */
|
|
20
|
+
search: string;
|
|
21
|
+
};
|
|
22
|
+
delete: {
|
|
23
|
+
/** The action when a delete removes the row for good. */
|
|
24
|
+
action: string;
|
|
25
|
+
/** `{name}`: the row's title. */
|
|
26
|
+
confirmTitle: string;
|
|
27
|
+
confirmBody: string;
|
|
28
|
+
};
|
|
29
|
+
bin: {
|
|
30
|
+
/** The action when the provider moves deleted rows to a recycle bin (`softDelete`). */
|
|
31
|
+
action: string;
|
|
32
|
+
confirmTitle: string;
|
|
33
|
+
confirmBody: string;
|
|
34
|
+
};
|
|
35
|
+
list: {
|
|
36
|
+
/** `{nounPlural}`. */
|
|
37
|
+
emptyTitle: string;
|
|
38
|
+
emptyBody: string;
|
|
39
|
+
noResultsTitle: string;
|
|
40
|
+
noResultsBody: string;
|
|
41
|
+
loadingMore: string;
|
|
42
|
+
/** `{nounPlural}`. */
|
|
43
|
+
loadFailed: string;
|
|
44
|
+
retry: string;
|
|
45
|
+
/** A section for rows with no value in the group field. `{label}`: the field. */
|
|
46
|
+
noGroup: string;
|
|
47
|
+
};
|
|
48
|
+
form: {
|
|
49
|
+
/** `{label}`. */
|
|
50
|
+
required: string;
|
|
51
|
+
/** `{label}`, `{max}`. */
|
|
52
|
+
tooLong: string;
|
|
53
|
+
/** `{noun}`. A save failed with no message of its own. */
|
|
54
|
+
saveFailed: string;
|
|
55
|
+
/** An empty day field's button. */
|
|
56
|
+
pickDate: string;
|
|
57
|
+
/** An empty date-and-time field's button. */
|
|
58
|
+
pickDateTime: string;
|
|
59
|
+
/** Empties an optional date. `{label}`. */
|
|
60
|
+
clear: string;
|
|
61
|
+
loading: string;
|
|
62
|
+
};
|
|
63
|
+
refusal: {
|
|
64
|
+
/** `{noun}`. A delete failed with no message of its own. */
|
|
65
|
+
deleteFailed: string;
|
|
66
|
+
dismiss: string;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const defaultNativeResourceViewMessages: NativeResourceViewMessages = {
|
|
71
|
+
common: {
|
|
72
|
+
empty: "—",
|
|
73
|
+
yes: "Yes",
|
|
74
|
+
no: "No",
|
|
75
|
+
cancel: "Cancel",
|
|
76
|
+
save: "Save",
|
|
77
|
+
edit: "Edit",
|
|
78
|
+
close: "Close",
|
|
79
|
+
create: "New {noun}",
|
|
80
|
+
editTitle: "Edit {noun}",
|
|
81
|
+
search: "Search {nounPlural}",
|
|
82
|
+
},
|
|
83
|
+
delete: {
|
|
84
|
+
action: "Delete",
|
|
85
|
+
confirmTitle: "Delete “{name}”?",
|
|
86
|
+
confirmBody: "This can't be undone.",
|
|
87
|
+
},
|
|
88
|
+
bin: {
|
|
89
|
+
action: "Move to Bin",
|
|
90
|
+
confirmTitle: "Move “{name}” to the bin?",
|
|
91
|
+
confirmBody: "You can restore it from the bin.",
|
|
92
|
+
},
|
|
93
|
+
list: {
|
|
94
|
+
emptyTitle: "No {nounPlural} yet",
|
|
95
|
+
emptyBody: "When there are some, they show up here.",
|
|
96
|
+
noResultsTitle: "No results",
|
|
97
|
+
noResultsBody: "Try a different search.",
|
|
98
|
+
loadingMore: "Loading more",
|
|
99
|
+
loadFailed: "These {nounPlural} couldn't be loaded.",
|
|
100
|
+
retry: "Try again",
|
|
101
|
+
noGroup: "No {label}",
|
|
102
|
+
},
|
|
103
|
+
form: {
|
|
104
|
+
required: "{label} is required.",
|
|
105
|
+
tooLong: "{label} can be at most {max} characters.",
|
|
106
|
+
saveFailed: "This {noun} couldn't be saved. Try again.",
|
|
107
|
+
pickDate: "Add a date",
|
|
108
|
+
pickDateTime: "Add a date and time",
|
|
109
|
+
clear: "Clear {label}",
|
|
110
|
+
loading: "Loading",
|
|
111
|
+
},
|
|
112
|
+
refusal: {
|
|
113
|
+
deleteFailed: "This {noun} couldn't be deleted. Try again.",
|
|
114
|
+
dismiss: "Dismiss",
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** Fill `{name}` placeholders. A placeholder with no value is left as it is. */
|
|
119
|
+
export function fill(template: string, values: Readonly<Record<string, string | number>>): string {
|
|
120
|
+
return template.replace(/\{(\w+)\}/g, (match, key: string) => (key in values ? String(values[key]) : match));
|
|
121
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
// useNativeResourceView: the headless NativeResourceView. Cursor paging through
|
|
2
|
+
// useInfiniteResource (onEndReached), search debounced 300 ms, writes through useResource (so they
|
|
3
|
+
// share its cache patching, rollback and refusal handling), and the view's rows, sections, swipe
|
|
4
|
+
// actions and form fields resolved once.
|
|
5
|
+
|
|
6
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
7
|
+
import type { BaseRecord, DataRow, FilterParam } from "@marktiderman/genesis-core";
|
|
8
|
+
import { useCapabilities, useInfiniteResource, useResource } from "@marktiderman/genesis-core/hooks";
|
|
9
|
+
import type { Allowed } from "@marktiderman/genesis-core/resource-view";
|
|
10
|
+
import { useNativeResourceViewMessages } from "./display";
|
|
11
|
+
import {
|
|
12
|
+
allowed,
|
|
13
|
+
formFieldsFor,
|
|
14
|
+
refusalFields,
|
|
15
|
+
refusalMessage,
|
|
16
|
+
rowItem,
|
|
17
|
+
sectionsFor,
|
|
18
|
+
swipeActionsFor,
|
|
19
|
+
validateValues,
|
|
20
|
+
writableValues,
|
|
21
|
+
type AnyResourceView,
|
|
22
|
+
type NativeFormField,
|
|
23
|
+
type NativeResourceRowItem,
|
|
24
|
+
type NativeResourceScreenCan,
|
|
25
|
+
type NativeResourceSection,
|
|
26
|
+
type NativeResourceSwipeAction,
|
|
27
|
+
} from "./mapping";
|
|
28
|
+
import { fill } from "./messages";
|
|
29
|
+
|
|
30
|
+
type Row = Record<string, unknown>;
|
|
31
|
+
type Filter = Readonly<Record<string, string | number | boolean | null>>;
|
|
32
|
+
|
|
33
|
+
/** How long typing waits before the search goes to the server. */
|
|
34
|
+
export const SEARCH_DEBOUNCE_MS = 300;
|
|
35
|
+
|
|
36
|
+
export interface NativeResourceViewOptions<T extends Row = Row> {
|
|
37
|
+
/** A tab the view defines: its server filter. */
|
|
38
|
+
preset?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Equality filters sent to the server (`{ client_id: id }`); `null` means "is empty". A create
|
|
41
|
+
* also saves every non-null value here (a tab's filter too), even for read-only fields such as
|
|
42
|
+
* a required link: they come from the screen, never from an input. An edit never sends them.
|
|
43
|
+
*/
|
|
44
|
+
filter?: Filter;
|
|
45
|
+
/** Rows per page. Default 25. */
|
|
46
|
+
perPage?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Pages kept loaded when the provider pages by cursor (and serves `prevCursor`): scrolling far
|
|
49
|
+
* drops pages from the front, and scrolling back to the top loads them again (`loadPrevious` on
|
|
50
|
+
* the list's `onStartReached`, with `maintainVisibleContentPosition` so the rows on screen stay
|
|
51
|
+
* put). Offset paging never drops pages. Default 10.
|
|
52
|
+
*/
|
|
53
|
+
maxPages?: number;
|
|
54
|
+
/** Fields the search box searches. Default: the view's `labelField`. */
|
|
55
|
+
searchFields?: string[];
|
|
56
|
+
/** The screen's own rule. It only narrows the view's guards. */
|
|
57
|
+
can?: NativeResourceScreenCan<T>;
|
|
58
|
+
/** Refetch loaded pages when the provider reports a change. */
|
|
59
|
+
live?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type SaveResult = { ok: true } | { ok: false; message?: string; fields: Record<string, string> };
|
|
63
|
+
|
|
64
|
+
export interface UseNativeResourceViewReturn<T extends Row = Row> {
|
|
65
|
+
rows: T[];
|
|
66
|
+
/** Rows in `groupBy` sections (one untitled section when the view doesn't group). */
|
|
67
|
+
sections: NativeResourceSection<T>[];
|
|
68
|
+
/** Rows matching the filters and search, when the provider counts them. */
|
|
69
|
+
total: number | undefined;
|
|
70
|
+
/** The first page is loading. */
|
|
71
|
+
loading: boolean;
|
|
72
|
+
/** The read failed: its message, in plain words. */
|
|
73
|
+
error: string | null;
|
|
74
|
+
refreshing: boolean;
|
|
75
|
+
refresh: () => Promise<void>;
|
|
76
|
+
/** Pass to the list's `onEndReached`: loads the next page by cursor. */
|
|
77
|
+
loadMore: () => void;
|
|
78
|
+
loadingMore: boolean;
|
|
79
|
+
hasMore: boolean;
|
|
80
|
+
/** Pass to the list's `onStartReached`: loads back a page `maxPages` dropped from the front. */
|
|
81
|
+
loadPrevious: () => void;
|
|
82
|
+
loadingPrevious: boolean;
|
|
83
|
+
hasPrevious: boolean;
|
|
84
|
+
/** What the search box shows (the server sees it 300 ms after the last keystroke). */
|
|
85
|
+
search: string;
|
|
86
|
+
setSearch: (text: string) => void;
|
|
87
|
+
/** The last refused write, in plain words, shown inline until dismissed or the next write. */
|
|
88
|
+
refusal: string | null;
|
|
89
|
+
dismissRefusal: () => void;
|
|
90
|
+
item: (row: T) => NativeResourceRowItem;
|
|
91
|
+
/** The row's swipe actions. Edit and delete call `onEdit` / `onDelete` you pass here. */
|
|
92
|
+
actions: (row: T, handlers: { onEdit: (row: T) => void; onDelete: (row: T) => void; onRefused: (label: string, reason: string) => void }) => NativeResourceSwipeAction[];
|
|
93
|
+
/** Whether a new row may be created: true, or the guard's reason. False when the screen turns it off or there's no form. */
|
|
94
|
+
canCreate: Allowed | false;
|
|
95
|
+
/** The form sheet's fields. */
|
|
96
|
+
formFields: (mode: "create" | "edit") => NativeFormField[];
|
|
97
|
+
/**
|
|
98
|
+
* Check and save the form's values. Sends only writable keys, and for an edit only the `dirty`
|
|
99
|
+
* ones (all writable keys when `dirty` is left out). Stays pessimistic so the sheet can show
|
|
100
|
+
* refusals.
|
|
101
|
+
*/
|
|
102
|
+
save: (mode: "create" | "edit", values: Readonly<Record<string, unknown>>, row?: T, dirty?: ReadonlySet<string>) => Promise<SaveResult>;
|
|
103
|
+
/** Delete a row optimistically: it leaves the list at once and comes back if the server refuses. */
|
|
104
|
+
remove: (row: T) => void;
|
|
105
|
+
/** The provider bins deleted rows (they can be restored). */
|
|
106
|
+
softDelete: boolean;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function filterParams(filter: Filter | undefined): FilterParam[] {
|
|
110
|
+
return Object.entries(filter ?? {}).map(([field, value]) =>
|
|
111
|
+
value === null ? { field, operator: "is_null" as const } : { field, operator: "eq" as const, value },
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The values a create takes from the screen: every non-null equality filter, the screen's over the tab's. */
|
|
116
|
+
export function screenValues(...filters: (Filter | undefined)[]): Record<string, string | number | boolean> {
|
|
117
|
+
const out: Record<string, string | number | boolean> = {};
|
|
118
|
+
for (const filter of filters) {
|
|
119
|
+
for (const [field, value] of Object.entries(filter ?? {})) if (value !== null) out[field] = value;
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Pages kept loaded by default (cursor paging). */
|
|
125
|
+
export const DEFAULT_MAX_PAGES = 10;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The server sort: the `groupBy` field first, so every page arrives in section order and a later
|
|
129
|
+
* page never lands in the middle of an earlier section; else the view's `orderBy`. (A second sort
|
|
130
|
+
* key within a group needs `useInfiniteResource` to take several sorts.)
|
|
131
|
+
*/
|
|
132
|
+
export function serverSort<T extends Row>(view: AnyResourceView<T>): { field: string; order: "asc" | "desc" } | undefined {
|
|
133
|
+
const groupBy = view.definition.groupBy as string | undefined;
|
|
134
|
+
const orderBy = view.definition.orderBy;
|
|
135
|
+
// TODO: within a group the view's orderBy is dropped (one sort only). Pass [groupBy, orderBy] once
|
|
136
|
+
// useInfiniteResource takes several sorts (the coming multi-sort, owned by core).
|
|
137
|
+
if (groupBy) return { field: groupBy, order: orderBy?.field === groupBy ? (orderBy.direction ?? "asc") : "asc" };
|
|
138
|
+
return orderBy ? { field: orderBy.field as string, order: orderBy.direction ?? "asc" } : undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function useNativeResourceView<T extends Row = Row>(
|
|
142
|
+
view: AnyResourceView<T>,
|
|
143
|
+
options: NativeResourceViewOptions<T> = {},
|
|
144
|
+
): UseNativeResourceViewReturn<T> {
|
|
145
|
+
const { preset, filter, perPage, maxPages = DEFAULT_MAX_PAGES, searchFields: searchOption, can, live } = options;
|
|
146
|
+
const messages = useNativeResourceViewMessages();
|
|
147
|
+
const tab = preset ? view.definition.presets?.[preset] : undefined;
|
|
148
|
+
if (preset && !tab) throw new Error(`NativeResourceView(${view.resource}): no preset "${preset}"`);
|
|
149
|
+
|
|
150
|
+
// ── Reads: cursor pages, server filters, server search ──────────────────
|
|
151
|
+
const tabFilter = tab?.filter as Filter | undefined;
|
|
152
|
+
const defaultFilters = useMemo(() => [...filterParams(tabFilter), ...filterParams(filter)], [tabFilter, filter]);
|
|
153
|
+
// By value, so an inline `filter={{ client_id }}` doesn't rebuild the form every render.
|
|
154
|
+
const createKey = JSON.stringify(screenValues(tabFilter, filter));
|
|
155
|
+
const createDefaults = useMemo(() => JSON.parse(createKey) as Record<string, string | number | boolean>, [createKey]);
|
|
156
|
+
const sort = useMemo(() => serverSort(view), [view]);
|
|
157
|
+
const searchFields = useMemo(
|
|
158
|
+
() => searchOption ?? (view.labelField ? [view.labelField] : undefined),
|
|
159
|
+
[searchOption, view.labelField],
|
|
160
|
+
);
|
|
161
|
+
const pages = useInfiniteResource<T & BaseRecord>(view.resource, {
|
|
162
|
+
defaultFilters,
|
|
163
|
+
...(sort ? { defaultSort: sort } : {}),
|
|
164
|
+
...(perPage ? { perPage } : {}),
|
|
165
|
+
maxPages,
|
|
166
|
+
...(searchFields ? { searchFields } : {}),
|
|
167
|
+
keepPreviousData: true,
|
|
168
|
+
...(live ? { live } : {}),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const [search, setSearchText] = useState("");
|
|
172
|
+
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
173
|
+
const { setSearch: sendSearch } = pages;
|
|
174
|
+
const setSearch = useCallback(
|
|
175
|
+
(text: string) => {
|
|
176
|
+
setSearchText(text);
|
|
177
|
+
if (timer.current) clearTimeout(timer.current);
|
|
178
|
+
timer.current = setTimeout(() => sendSearch(text), SEARCH_DEBOUNCE_MS);
|
|
179
|
+
},
|
|
180
|
+
[sendSearch],
|
|
181
|
+
);
|
|
182
|
+
useEffect(() => () => {
|
|
183
|
+
if (timer.current) clearTimeout(timer.current);
|
|
184
|
+
}, []);
|
|
185
|
+
|
|
186
|
+
// ── Writes ────────────────────────────────────────────────────────────
|
|
187
|
+
const [refusal, setRefusal] = useState<string | null>(null);
|
|
188
|
+
const deleteFailed = fill(messages.refusal.deleteFailed, { noun: view.noun });
|
|
189
|
+
const optimistic = useResource<T & BaseRecord>(view.resource, {
|
|
190
|
+
enabled: false,
|
|
191
|
+
mutationMode: "optimistic",
|
|
192
|
+
// The row is already back in the list (the cache is put back); say why, inline.
|
|
193
|
+
onError: (error) => setRefusal(refusalMessage(error, deleteFailed)),
|
|
194
|
+
});
|
|
195
|
+
const pessimistic = useResource<T & BaseRecord>(view.resource, { enabled: false, onError: () => {} });
|
|
196
|
+
const capabilities = useCapabilities(view.resource);
|
|
197
|
+
const softDelete = capabilities.data?.softDelete === true;
|
|
198
|
+
|
|
199
|
+
// A create's form leaves out the fields the screen's filter fixes: the filter's value is what's
|
|
200
|
+
// saved, so an input for it would be overridden without a word (the web hides them too).
|
|
201
|
+
const formFields = useCallback(
|
|
202
|
+
(mode: "create" | "edit") =>
|
|
203
|
+
mode === "create" ? formFieldsFor(view, "create").filter((f) => !(f.key in createDefaults)) : formFieldsFor(view, "edit"),
|
|
204
|
+
[view, createDefaults],
|
|
205
|
+
);
|
|
206
|
+
const editable = useMemo(() => formFieldsFor(view, "edit").some((f) => !f.readOnly), [view]);
|
|
207
|
+
const canCreate = useMemo(
|
|
208
|
+
() => (formFieldsFor(view, "create").length ? allowed(view, "create", undefined, can) : false),
|
|
209
|
+
[view, can],
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
const writers = useRef(pessimistic);
|
|
213
|
+
writers.current = pessimistic;
|
|
214
|
+
const save = useCallback(
|
|
215
|
+
async (mode: "create" | "edit", values: Readonly<Record<string, unknown>>, row?: T, dirty?: ReadonlySet<string>): Promise<SaveResult> => {
|
|
216
|
+
const fields = formFields(mode);
|
|
217
|
+
const errors = validateValues(fields, values, messages);
|
|
218
|
+
if (Object.keys(errors).length) return { ok: false, fields: errors };
|
|
219
|
+
// A create is the person's writable values plus the screen's filter values, which win (the
|
|
220
|
+
// new row must land in this list). An edit sends only writable values. The server's
|
|
221
|
+
// WITH CHECK still decides.
|
|
222
|
+
const data = (
|
|
223
|
+
mode === "create"
|
|
224
|
+
? { ...writableValues(view, mode, fields, values), ...createDefaults }
|
|
225
|
+
: writableValues(view, mode, fields, values, dirty)
|
|
226
|
+
) as Partial<T & BaseRecord>;
|
|
227
|
+
setRefusal(null);
|
|
228
|
+
// Nothing changed: nothing to send.
|
|
229
|
+
if (mode === "edit" && Object.keys(data).length === 0) return { ok: true };
|
|
230
|
+
try {
|
|
231
|
+
if (mode === "create") await writers.current.create(data);
|
|
232
|
+
else await writers.current.update(row!.id as string, data);
|
|
233
|
+
return { ok: true };
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return {
|
|
236
|
+
ok: false,
|
|
237
|
+
message: refusalMessage(error, fill(messages.form.saveFailed, { noun: view.noun })),
|
|
238
|
+
fields: refusalFields(error),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
[view, messages, createDefaults, formFields],
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
// useResource's writers change identity every render; a ref keeps `remove` (and so every row's
|
|
246
|
+
// actions) stable, so typing in the search doesn't redraw the rows.
|
|
247
|
+
const removeRow = useRef(optimistic.remove);
|
|
248
|
+
removeRow.current = optimistic.remove;
|
|
249
|
+
const remove = useCallback((row: T) => {
|
|
250
|
+
setRefusal(null);
|
|
251
|
+
// Optimistic: resolves at once; a refusal arrives through onError after the rollback.
|
|
252
|
+
removeRow.current(row.id as string).catch(() => {});
|
|
253
|
+
}, []);
|
|
254
|
+
|
|
255
|
+
const item = useCallback((row: T) => rowItem(view, row), [view]);
|
|
256
|
+
const actions = useCallback<UseNativeResourceViewReturn<T>["actions"]>(
|
|
257
|
+
(row, handlers) => swipeActionsFor(view, row, { messages, softDelete, editable, screen: can, ...handlers }),
|
|
258
|
+
[view, messages, softDelete, editable, can],
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
const sections = useMemo(() => sectionsFor(view, pages.rows, messages), [view, pages.rows, messages]);
|
|
262
|
+
|
|
263
|
+
const { query } = pages;
|
|
264
|
+
const [refreshing, setRefreshing] = useState(false);
|
|
265
|
+
const refresh = useCallback(async () => {
|
|
266
|
+
setRefreshing(true);
|
|
267
|
+
try {
|
|
268
|
+
await query.refetch();
|
|
269
|
+
} finally {
|
|
270
|
+
setRefreshing(false);
|
|
271
|
+
}
|
|
272
|
+
}, [query]);
|
|
273
|
+
|
|
274
|
+
const error = query.isError
|
|
275
|
+
? query.error?.name === "DataReadError" && query.error.message
|
|
276
|
+
? query.error.message
|
|
277
|
+
: fill(messages.list.loadFailed, { nounPlural: view.nounPlural })
|
|
278
|
+
: null;
|
|
279
|
+
|
|
280
|
+
return {
|
|
281
|
+
rows: pages.rows as T[],
|
|
282
|
+
sections: sections as NativeResourceSection<T>[],
|
|
283
|
+
total: pages.total,
|
|
284
|
+
loading: query.isLoading,
|
|
285
|
+
error,
|
|
286
|
+
refreshing,
|
|
287
|
+
refresh,
|
|
288
|
+
loadMore: pages.fetchNextPage,
|
|
289
|
+
loadingMore: pages.isFetchingNextPage,
|
|
290
|
+
hasMore: pages.hasNextPage,
|
|
291
|
+
loadPrevious: pages.fetchPreviousPage,
|
|
292
|
+
loadingPrevious: query.isFetchingPreviousPage,
|
|
293
|
+
hasPrevious: pages.hasPreviousPage,
|
|
294
|
+
search,
|
|
295
|
+
setSearch,
|
|
296
|
+
refusal,
|
|
297
|
+
dismissRefusal: useCallback(() => setRefusal(null), []),
|
|
298
|
+
item,
|
|
299
|
+
actions,
|
|
300
|
+
canCreate,
|
|
301
|
+
formFields,
|
|
302
|
+
save,
|
|
303
|
+
remove,
|
|
304
|
+
softDelete,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
@@ -46,7 +46,8 @@ describe("InboxPage", () => {
|
|
|
46
46
|
it("shows a spinner while the first page loads, and an error (with Try again) when the read failed", () => {
|
|
47
47
|
const onRefresh = vi.fn();
|
|
48
48
|
const { unmount } = render(<InboxPage testID="inbox" items={[]} loading emptyTitle="No reports" />);
|
|
49
|
-
expect(screen.getByTestId("inbox-loading")).
|
|
49
|
+
expect(screen.getByTestId("inbox-loading").getAttribute("role")).toBe("progressbar");
|
|
50
|
+
expect(screen.getByTestId("inbox-loading").getAttribute("aria-label")).toBe("Loading");
|
|
50
51
|
expect(screen.queryByTestId("inbox-empty")).toBeNull();
|
|
51
52
|
unmount();
|
|
52
53
|
render(<InboxPage testID="inbox" items={[]} error errorTitle="Couldn't load" onRefresh={onRefresh} />);
|
|
@@ -78,3 +78,30 @@ describe("composeHeaderOptions", () => {
|
|
|
78
78
|
expect(opts.headerRight).toBe(right);
|
|
79
79
|
});
|
|
80
80
|
});
|
|
81
|
+
|
|
82
|
+
describe("ScreenContainer loading", () => {
|
|
83
|
+
it("replaces the body with a centred loading state inside the same safe area", () => {
|
|
84
|
+
render(
|
|
85
|
+
<ScreenContainer testID="screen" loading loadingLabel="Opening your space" scroll>
|
|
86
|
+
<span data-testid="child">Hello</span>
|
|
87
|
+
</ScreenContainer>,
|
|
88
|
+
);
|
|
89
|
+
expect(screen.queryByTestId("child")).toBeNull();
|
|
90
|
+
expect(screen.queryByTestId("screen-scroll")).toBeNull();
|
|
91
|
+
expect(screen.getByTestId("screen-body")).toBeTruthy();
|
|
92
|
+
const loading = screen.getByTestId("screen-loading");
|
|
93
|
+
expect(loading.getAttribute("role")).toBe("progressbar");
|
|
94
|
+
expect(loading.getAttribute("aria-label")).toBe("Opening your space");
|
|
95
|
+
expect(screen.getByTestId("screen").getAttribute("data-edges")).toBe("left,right");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("renders the children once loading ends", () => {
|
|
99
|
+
render(
|
|
100
|
+
<ScreenContainer testID="screen" loading={false}>
|
|
101
|
+
<span data-testid="child">Hello</span>
|
|
102
|
+
</ScreenContainer>,
|
|
103
|
+
);
|
|
104
|
+
expect(screen.getByTestId("child")).toBeTruthy();
|
|
105
|
+
expect(screen.queryByTestId("screen-loading")).toBeNull();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
*/
|
|
32
32
|
import { Fragment, useState, type ReactNode } from "react";
|
|
33
33
|
import { renderSlot, type SlotPropsFor, type Slots } from "@marktiderman/genesis-core/slots";
|
|
34
|
-
import {
|
|
34
|
+
import { Alert, FlatList, Platform, Pressable, ScrollView, StyleSheet, View } from "react-native";
|
|
35
35
|
import { SafeAreaView } from "react-native-safe-area-context";
|
|
36
36
|
import { useThemeRoles } from "../hooks/use-theme-roles";
|
|
37
37
|
import { NativeEmptyState } from "../components/empty-state";
|
|
@@ -39,6 +39,7 @@ import { NativeText } from "../components/text";
|
|
|
39
39
|
import { NativeButton } from "../components/button";
|
|
40
40
|
import { NativeBadge } from "../components/badge";
|
|
41
41
|
import { NativeRefreshControl } from "../components/refresh-control";
|
|
42
|
+
import { NativeLoadingState } from "../components/loading-state";
|
|
42
43
|
import { composeHeaderOptions, type ScreenHeaderProps } from "./screen-container";
|
|
43
44
|
|
|
44
45
|
/** An action on a row: swipe, long press, or an accessibility action. */
|
|
@@ -220,9 +221,7 @@ export function InboxPage({
|
|
|
220
221
|
>
|
|
221
222
|
{headerNode}
|
|
222
223
|
{loading ? (
|
|
223
|
-
<
|
|
224
|
-
<ActivityIndicator accessibilityLabel="Loading" />
|
|
225
|
-
</View>
|
|
224
|
+
<NativeLoadingState fullScreen={false} testID={`${testID}-loading`} />
|
|
226
225
|
) : (
|
|
227
226
|
renderSlot(
|
|
228
227
|
DefaultEmpty,
|
|
@@ -430,9 +429,7 @@ function UnreadDot({ unread, testID, color }: { unread: boolean; testID: string;
|
|
|
430
429
|
function DefaultFooter({ loadingMore, testID }: InboxPageSlotMap["footer"]) {
|
|
431
430
|
if (!loadingMore) return null;
|
|
432
431
|
return (
|
|
433
|
-
<
|
|
434
|
-
<ActivityIndicator accessibilityLabel="Loading more" />
|
|
435
|
-
</View>
|
|
432
|
+
<NativeLoadingState fullScreen={false} size="small" accessibilityLabel="Loading more" className="py-4" testID={testID} />
|
|
436
433
|
);
|
|
437
434
|
}
|
|
438
435
|
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* - StatusBar style (light / dark / auto)
|
|
7
7
|
* - Scroll vs static body
|
|
8
8
|
* - Tokens-aware background (`bg-background`)
|
|
9
|
+
* - A loading state (`loading`): a centred `NativeLoadingState` in place of the body
|
|
9
10
|
*
|
|
10
11
|
* Header customization is delegated: pass `headerLeft`, `headerRight`,
|
|
11
12
|
* `large`, `scrollEdgeBehavior`, `safeAreaEdges`, plus any direct
|
|
@@ -31,6 +32,7 @@ import { ScrollView, StatusBar, View, type ViewStyle } from "react-native";
|
|
|
31
32
|
import { SafeAreaView } from "react-native-safe-area-context";
|
|
32
33
|
import { cn } from "../utils";
|
|
33
34
|
import { useThemeMode } from "../hooks/use-theme-mode";
|
|
35
|
+
import { NativeLoadingState } from "../components/loading-state";
|
|
34
36
|
|
|
35
37
|
export type SafeAreaEdge = "top" | "bottom" | "left" | "right";
|
|
36
38
|
|
|
@@ -64,6 +66,15 @@ export interface ScreenContainerProps {
|
|
|
64
66
|
* Only used when `scroll` is true.
|
|
65
67
|
*/
|
|
66
68
|
keyboardShouldPersistTaps?: "always" | "never" | "handled";
|
|
69
|
+
/**
|
|
70
|
+
* When `true`, a centred `NativeLoadingState` (theme-tinted spinner,
|
|
71
|
+
* announced as loading) replaces the body, inside the same safe area and
|
|
72
|
+
* background. Use it for redirect and first-load screens: the body is
|
|
73
|
+
* unmounted while it's on, so a form underneath loses its state. Default `false`.
|
|
74
|
+
*/
|
|
75
|
+
loading?: boolean;
|
|
76
|
+
/** Text under the spinner while `loading`, and what screen readers announce: pass translated text. */
|
|
77
|
+
loadingLabel?: string;
|
|
67
78
|
/** Style on the root, e.g. a theme-role background color. */
|
|
68
79
|
style?: ViewStyle;
|
|
69
80
|
/** testID on the root container. */
|
|
@@ -170,6 +181,8 @@ export function ScreenContainer({
|
|
|
170
181
|
className,
|
|
171
182
|
contentClassName,
|
|
172
183
|
keyboardShouldPersistTaps = "handled",
|
|
184
|
+
loading = false,
|
|
185
|
+
loadingLabel,
|
|
173
186
|
style,
|
|
174
187
|
testID,
|
|
175
188
|
}: ScreenContainerProps) {
|
|
@@ -177,7 +190,11 @@ export function ScreenContainer({
|
|
|
177
190
|
const resolvedMode = themeMode === "system" ? osMode : themeMode;
|
|
178
191
|
const barStyle = resolveBarStyle(statusBar, resolvedMode);
|
|
179
192
|
|
|
180
|
-
const body =
|
|
193
|
+
const body = loading ? (
|
|
194
|
+
<View testID={testID ? `${testID}-body` : undefined} className={cn("flex-1", contentClassName)}>
|
|
195
|
+
<NativeLoadingState fullScreen={false} label={loadingLabel} testID={`${testID ?? "screen-container"}-loading`} />
|
|
196
|
+
</View>
|
|
197
|
+
) : scroll ? (
|
|
181
198
|
<ScrollView
|
|
182
199
|
testID={testID ? `${testID}-scroll` : undefined}
|
|
183
200
|
keyboardShouldPersistTaps={keyboardShouldPersistTaps}
|