@marktiderman/genesis-ui-native 2.5.0 → 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/dist/{chunk-IDHW2NOP.js → chunk-3S5XVER4.js} +231 -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-YJV5MMZX.js → chunk-KZEIF4YI.js} +7 -741
- package/dist/chunk-KZEIF4YI.js.map +1 -0
- package/dist/{chunk-YI7XVY2D.js → chunk-VMSIKSU2.js} +13 -479
- package/dist/chunk-VMSIKSU2.js.map +1 -0
- package/dist/components/index.d.ts +3 -1
- 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 +2 -1
- package/dist/index.js +5 -5
- package/dist/layouts/index.d.ts +4 -195
- package/dist/layouts/index.js +3 -3
- package/package.json +2 -2
- package/src/components/image.tsx +5 -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/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-IDHW2NOP.js.map +0 -1
- package/dist/chunk-YI7XVY2D.js.map +0 -1
- package/dist/chunk-YJV5MMZX.js.map +0 -1
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// How a view's display hints draw on native. The same shape as genesis-ui's web renderers
|
|
2
|
+
// (`DisplayRenderers`, `DisplayRenderersProvider`, `useDisplayCell`): a view says
|
|
3
|
+
// `status: { display: "badge" }` and never imports a component, and an app replaces any hint with
|
|
4
|
+
// DisplayRenderersProvider. Links and images go through core's `isSafeUrl`; a calendar day is
|
|
5
|
+
// formatted from its parts, never `new Date(day)`. Rows show only `summary(row)`; these draw the
|
|
6
|
+
// peek and read-only form values.
|
|
7
|
+
|
|
8
|
+
import { createContext, useContext, useMemo, type ReactNode } from "react";
|
|
9
|
+
import { Linking, Text } from "react-native";
|
|
10
|
+
import { titleCase } from "@marktiderman/genesis-core";
|
|
11
|
+
import { isTimeZone, personTimeZone, wallClock } from "@marktiderman/genesis-core/dates";
|
|
12
|
+
import { isSafeUrl } from "@marktiderman/genesis-core/urls";
|
|
13
|
+
import type { DisplayHint, ResolvedColumn, ViewTone } from "@marktiderman/genesis-core/resource-view";
|
|
14
|
+
import { NativeBadge } from "../../components/badge";
|
|
15
|
+
import { NativeImage } from "../../components/image";
|
|
16
|
+
import { NativeText } from "../../components/text";
|
|
17
|
+
import { defaultNativeResourceViewMessages, type NativeResourceViewMessages } from "./messages";
|
|
18
|
+
|
|
19
|
+
/** The clocks a timestamp can be read on: the viewer's and the practice's (IANA names). */
|
|
20
|
+
export interface DisplayTimeZones {
|
|
21
|
+
viewer: string;
|
|
22
|
+
practice: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a renderer gets besides the value (as on the web, with native's messages and clocks). */
|
|
26
|
+
export interface DisplayContext {
|
|
27
|
+
row: Record<string, unknown>;
|
|
28
|
+
column: ResolvedColumn<Record<string, unknown>>;
|
|
29
|
+
messages: NativeResourceViewMessages;
|
|
30
|
+
zones: DisplayTimeZones;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type DisplayRenderer = (value: unknown, context: DisplayContext) => ReactNode;
|
|
34
|
+
export type DisplayRenderers = Readonly<Record<DisplayHint, DisplayRenderer>>;
|
|
35
|
+
|
|
36
|
+
export const isEmptyValue = (value: unknown) => value === null || value === undefined || value === "";
|
|
37
|
+
|
|
38
|
+
const NUMBER = new Intl.NumberFormat();
|
|
39
|
+
const DECIMAL = new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
40
|
+
const PERCENT = new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 1 });
|
|
41
|
+
const DAY = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
|
|
42
|
+
|
|
43
|
+
function numeric(value: unknown, format: Intl.NumberFormat): string {
|
|
44
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
45
|
+
return Number.isFinite(n) ? format.format(n) : String(value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const DAY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
49
|
+
|
|
50
|
+
/** A `YYYY-MM-DD` day as a local Date at midnight, from its parts (the picker's value). Null when it isn't a day. */
|
|
51
|
+
export function dayToDate(value: unknown): Date | null {
|
|
52
|
+
const day = typeof value === "string" ? DAY_PATTERN.exec(value) : null;
|
|
53
|
+
if (!day) return null;
|
|
54
|
+
return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A picked Date back to the `YYYY-MM-DD` day it shows, from its local parts (never `toISOString`). */
|
|
58
|
+
export function dateToDay(date: Date): string {
|
|
59
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
60
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A calendar day, the same day on every clock. */
|
|
64
|
+
export function formatDay(value: unknown): string {
|
|
65
|
+
const date = dayToDate(value);
|
|
66
|
+
return date ? DAY.format(date) : String(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A column's clock: "viewer" (the default) and "practice" from `zones`, else a valid IANA name. */
|
|
70
|
+
export function resolveZone(zone: string | undefined, zones: DisplayTimeZones): string {
|
|
71
|
+
if (!zone || zone === "viewer") return zones.viewer;
|
|
72
|
+
if (zone === "practice") return zones.practice;
|
|
73
|
+
return isTimeZone(zone) ? zone : zones.viewer;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// The wall clock's parts are drawn as UTC, so one formatter serves every zone.
|
|
77
|
+
const WALL = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
|
|
78
|
+
|
|
79
|
+
/** A timestamp as the clock on the wall in `zone` shows it (core's `wallClock`), not the device's. */
|
|
80
|
+
export function formatInstant(value: unknown, zone: string): string {
|
|
81
|
+
const at = new Date(String(value));
|
|
82
|
+
if (Number.isNaN(at.getTime()) || !isTimeZone(zone)) return String(value);
|
|
83
|
+
const wall = wallClock(zone, at);
|
|
84
|
+
return WALL.format(new Date(Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second)));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A link a row may open: http(s), mailto or tel that passes `isSafeUrl`. Root-relative paths mean nothing on a phone. */
|
|
88
|
+
export function openableUrl(value: unknown): string | null {
|
|
89
|
+
if (!isSafeUrl(value)) return null;
|
|
90
|
+
const url = value.trim();
|
|
91
|
+
return /^(https?:|mailto:|tel:)/i.test(url) ? url : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One value as plain text, for the places that take a string (a row's subtitle, a section title,
|
|
96
|
+
* a read-only form row). Renderers use the same words.
|
|
97
|
+
*/
|
|
98
|
+
export function displayText(
|
|
99
|
+
hint: DisplayHint,
|
|
100
|
+
value: unknown,
|
|
101
|
+
messages: NativeResourceViewMessages,
|
|
102
|
+
/** The resolved IANA zone a timestamp is read on (`resolveZone`). Default: the device's. */
|
|
103
|
+
timeZone: string = personTimeZone(),
|
|
104
|
+
): string {
|
|
105
|
+
if (isEmptyValue(value)) return messages.common.empty;
|
|
106
|
+
switch (hint) {
|
|
107
|
+
case "number":
|
|
108
|
+
return numeric(value, NUMBER);
|
|
109
|
+
case "currency":
|
|
110
|
+
return numeric(value, DECIMAL);
|
|
111
|
+
case "percent":
|
|
112
|
+
return numeric(value, PERCENT);
|
|
113
|
+
case "boolean":
|
|
114
|
+
return value === true || value === "true" ? messages.common.yes : messages.common.no;
|
|
115
|
+
case "badge":
|
|
116
|
+
return titleCase(String(value));
|
|
117
|
+
case "date":
|
|
118
|
+
return formatDay(value);
|
|
119
|
+
case "datetime":
|
|
120
|
+
return formatInstant(value, timeZone);
|
|
121
|
+
case "url": {
|
|
122
|
+
const url = openableUrl(value);
|
|
123
|
+
return url ? url.replace(/^https?:\/\//i, "") : String(value);
|
|
124
|
+
}
|
|
125
|
+
case "json":
|
|
126
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
127
|
+
default:
|
|
128
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const BADGE_VARIANT: Record<ViewTone, "success" | "warning" | "destructive" | "info" | "muted"> = {
|
|
133
|
+
success: "success",
|
|
134
|
+
warning: "warning",
|
|
135
|
+
danger: "destructive",
|
|
136
|
+
info: "info",
|
|
137
|
+
muted: "muted",
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/** A chip's tone as a NativeBadge variant. */
|
|
141
|
+
export function badgeVariant(tone: ViewTone | undefined) {
|
|
142
|
+
return BADGE_VARIANT[tone ?? "muted"];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function LinkText({ url, label }: { url: string; label: string }) {
|
|
146
|
+
return (
|
|
147
|
+
<Text
|
|
148
|
+
accessibilityRole="link"
|
|
149
|
+
className="text-base text-primary underline"
|
|
150
|
+
onPress={() => void Linking.openURL(url)}
|
|
151
|
+
>
|
|
152
|
+
{label}
|
|
153
|
+
</Text>
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const text = (hint: DisplayHint): DisplayRenderer => (value, { messages, column, zones }) => (
|
|
158
|
+
<NativeText preset="body">{displayText(hint, value, messages, resolveZone(column.timeZone, zones))}</NativeText>
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
/** Genesis's native renderers. Every one shows text it can't draw, never a broken row. */
|
|
162
|
+
export const nativeDisplayRenderers: DisplayRenderers = {
|
|
163
|
+
text: text("text"),
|
|
164
|
+
longText: (value) => (
|
|
165
|
+
<NativeText preset="body" numberOfLines={3}>
|
|
166
|
+
{String(value)}
|
|
167
|
+
</NativeText>
|
|
168
|
+
),
|
|
169
|
+
number: text("number"),
|
|
170
|
+
currency: text("currency"),
|
|
171
|
+
percent: text("percent"),
|
|
172
|
+
boolean: text("boolean"),
|
|
173
|
+
badge: (value, { column }) => (
|
|
174
|
+
<NativeBadge variant={badgeVariant(column.tones?.[String(value)])}>{titleCase(String(value))}</NativeBadge>
|
|
175
|
+
),
|
|
176
|
+
date: text("date"),
|
|
177
|
+
datetime: text("datetime"),
|
|
178
|
+
// The linked row's id until relation labels arrive (batched per page, never per row).
|
|
179
|
+
relation: text("relation"),
|
|
180
|
+
url: (value, { messages }) => {
|
|
181
|
+
const url = openableUrl(value);
|
|
182
|
+
return url && /^https?:/i.test(url) ? (
|
|
183
|
+
<LinkText url={url} label={displayText("url", value, messages)} />
|
|
184
|
+
) : (
|
|
185
|
+
<NativeText preset="body">{String(value)}</NativeText>
|
|
186
|
+
);
|
|
187
|
+
},
|
|
188
|
+
email: (value) => {
|
|
189
|
+
const address = String(value).trim();
|
|
190
|
+
// A plain address only: no `?subject=` or `&body=` riding along in the mailto link.
|
|
191
|
+
const url = /^[^\s@?&#/]+@[^\s@?&#/]+$/.test(address) ? openableUrl(`mailto:${address}`) : null;
|
|
192
|
+
return url ? <LinkText url={url} label={address} /> : <NativeText preset="body">{address}</NativeText>;
|
|
193
|
+
},
|
|
194
|
+
image: (value) => {
|
|
195
|
+
const url = openableUrl(value);
|
|
196
|
+
return url && /^https?:/i.test(url) ? (
|
|
197
|
+
<NativeImage src={url} width={64} height={64} className="rounded-md" />
|
|
198
|
+
) : (
|
|
199
|
+
<NativeText preset="body">{String(value)}</NativeText>
|
|
200
|
+
);
|
|
201
|
+
},
|
|
202
|
+
json: (value) => (
|
|
203
|
+
<NativeText preset="caption" numberOfLines={2}>
|
|
204
|
+
{typeof value === "string" ? value : JSON.stringify(value)}
|
|
205
|
+
</NativeText>
|
|
206
|
+
),
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const DisplayRenderersContext = createContext<DisplayRenderers>(nativeDisplayRenderers);
|
|
210
|
+
const MessagesContext = createContext<NativeResourceViewMessages>(defaultNativeResourceViewMessages);
|
|
211
|
+
const TimeZonesContext = createContext<DisplayTimeZones | null>(null);
|
|
212
|
+
|
|
213
|
+
/** The clocks timestamps are read on below. NativeResourceView sets it from ViewerScope. */
|
|
214
|
+
export const DisplayTimeZonesProvider = TimeZonesContext.Provider;
|
|
215
|
+
|
|
216
|
+
/** The clocks for timestamps: the nearest provider's, else the device's for both. */
|
|
217
|
+
export function useDisplayTimeZones(): DisplayTimeZones {
|
|
218
|
+
const zones = useContext(TimeZonesContext);
|
|
219
|
+
return useMemo(() => zones ?? { viewer: personTimeZone(), practice: personTimeZone() }, [zones]);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Replace some of the renderers for everything below (nested providers build on each other). */
|
|
223
|
+
export function DisplayRenderersProvider({
|
|
224
|
+
renderers,
|
|
225
|
+
children,
|
|
226
|
+
}: {
|
|
227
|
+
renderers: Partial<Record<DisplayHint, DisplayRenderer>>;
|
|
228
|
+
children: ReactNode;
|
|
229
|
+
}) {
|
|
230
|
+
const parent = useContext(DisplayRenderersContext);
|
|
231
|
+
const value = useMemo(() => ({ ...parent, ...renderers }), [parent, renderers]);
|
|
232
|
+
return <DisplayRenderersContext.Provider value={value}>{children}</DisplayRenderersContext.Provider>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The words NativeResourceView shows, for everything below. Pass a stable object. */
|
|
236
|
+
export const NativeResourceViewMessagesProvider = MessagesContext.Provider;
|
|
237
|
+
|
|
238
|
+
export function useNativeResourceViewMessages(): NativeResourceViewMessages {
|
|
239
|
+
return useContext(MessagesContext);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Draw one value: the empty mark for no value or a value the row hides (`when`), else its hint's renderer. */
|
|
243
|
+
export function useDisplayCell(): (column: ResolvedColumn<Record<string, unknown>>, row: Record<string, unknown>) => ReactNode {
|
|
244
|
+
const renderers = useContext(DisplayRenderersContext);
|
|
245
|
+
const messages = useNativeResourceViewMessages();
|
|
246
|
+
const zones = useDisplayTimeZones();
|
|
247
|
+
return useMemo(
|
|
248
|
+
() => (column, row) => {
|
|
249
|
+
if (column.when && !column.when(row)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
|
|
250
|
+
const value = column.value(row);
|
|
251
|
+
if (isEmptyValue(value)) return <NativeText preset="body">{messages.common.empty}</NativeText>;
|
|
252
|
+
return renderers[column.display](value, { row, column, messages, zones });
|
|
253
|
+
},
|
|
254
|
+
[renderers, messages, zones],
|
|
255
|
+
);
|
|
256
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// NativeResourceView: ResourceView's native renderer (docs/RESOURCE-VIEW.md, "Native").
|
|
2
|
+
export { NativeResourceView, type NativeResourceViewProps, type NativeResourceSwipeableProps } from "./NativeResourceView";
|
|
3
|
+
export {
|
|
4
|
+
useNativeResourceView,
|
|
5
|
+
SEARCH_DEBOUNCE_MS,
|
|
6
|
+
screenValues,
|
|
7
|
+
serverSort,
|
|
8
|
+
DEFAULT_MAX_PAGES,
|
|
9
|
+
type NativeResourceViewOptions,
|
|
10
|
+
type SaveResult,
|
|
11
|
+
type UseNativeResourceViewReturn,
|
|
12
|
+
} from "./use-native-resource-view";
|
|
13
|
+
export { NativeResourceFormSheet, type NativeResourceFormSheetProps } from "./NativeResourceFormSheet";
|
|
14
|
+
export {
|
|
15
|
+
DisplayRenderersProvider,
|
|
16
|
+
DisplayTimeZonesProvider,
|
|
17
|
+
useDisplayTimeZones,
|
|
18
|
+
resolveZone,
|
|
19
|
+
formatInstant,
|
|
20
|
+
NativeResourceViewMessagesProvider,
|
|
21
|
+
nativeDisplayRenderers,
|
|
22
|
+
useDisplayCell,
|
|
23
|
+
useNativeResourceViewMessages,
|
|
24
|
+
displayText,
|
|
25
|
+
dayToDate,
|
|
26
|
+
dateToDay,
|
|
27
|
+
formatDay,
|
|
28
|
+
openableUrl,
|
|
29
|
+
type DisplayContext,
|
|
30
|
+
type DisplayTimeZones,
|
|
31
|
+
type DisplayRenderer,
|
|
32
|
+
type DisplayRenderers,
|
|
33
|
+
} from "./display";
|
|
34
|
+
export {
|
|
35
|
+
allowed,
|
|
36
|
+
formFieldsFor,
|
|
37
|
+
rowItem,
|
|
38
|
+
sectionsFor,
|
|
39
|
+
swipeActionsFor,
|
|
40
|
+
validateValues,
|
|
41
|
+
writableValues,
|
|
42
|
+
type AnyResourceView,
|
|
43
|
+
type NativeFormField,
|
|
44
|
+
type NativeFormFieldKind,
|
|
45
|
+
type NativeResourceRowItem,
|
|
46
|
+
type NativeResourceScreenCan,
|
|
47
|
+
type NativeResourceSection,
|
|
48
|
+
type NativeResourceSwipeAction,
|
|
49
|
+
} from "./mapping";
|
|
50
|
+
export { defaultNativeResourceViewMessages, type NativeResourceViewMessages } from "./messages";
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// A view mapped onto native list pieces, with no React: rows for NativeListItem, sections for
|
|
2
|
+
// SectionList, guards as swipe actions, and the form sheet's fields. NativeResourceView and
|
|
3
|
+
// useNativeResourceView draw from these, and the tests check them directly.
|
|
4
|
+
|
|
5
|
+
import type { DataRow } from "@marktiderman/genesis-core";
|
|
6
|
+
import type {
|
|
7
|
+
Allowed,
|
|
8
|
+
DisplayHint,
|
|
9
|
+
ResourceView,
|
|
10
|
+
RowPicture,
|
|
11
|
+
RowSummary,
|
|
12
|
+
} from "@marktiderman/genesis-core/resource-view";
|
|
13
|
+
import { rowPicture } from "@marktiderman/genesis-core/resource-view";
|
|
14
|
+
import type { InboxSwipeAction } from "../../layouts/inbox-page";
|
|
15
|
+
import { displayText, isEmptyValue } from "./display";
|
|
16
|
+
import { fill, type NativeResourceViewMessages } from "./messages";
|
|
17
|
+
|
|
18
|
+
type Row = Record<string, unknown>;
|
|
19
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract; the row is what matters here
|
|
20
|
+
export type AnyResourceView<T extends Row = Row> = ResourceView<any, T & DataRow>;
|
|
21
|
+
|
|
22
|
+
/** What one row shows in a NativeListItem. */
|
|
23
|
+
export interface NativeResourceRowItem {
|
|
24
|
+
id: string;
|
|
25
|
+
title: string;
|
|
26
|
+
/** `summary(row).subtitle`, the only subtitle: never a raw column. */
|
|
27
|
+
subtitle?: string;
|
|
28
|
+
chips: NonNullable<RowSummary["chips"]>;
|
|
29
|
+
/**
|
|
30
|
+
* `rowPicture(summary)`: an image (passed `isSafeUrl`, with initials to fall back to), initials,
|
|
31
|
+
* or null. On a phone only an http(s) image can load, so any other safe src (a root-relative
|
|
32
|
+
* path) draws its initials instead.
|
|
33
|
+
*/
|
|
34
|
+
picture: RowPicture | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function nativePicture(summary: RowSummary): RowPicture | null {
|
|
38
|
+
const picture = rowPicture(summary);
|
|
39
|
+
if (picture?.kind === "image" && !/^https?:/i.test(picture.src)) {
|
|
40
|
+
return picture.fallback ? { kind: "initials", text: picture.fallback } : null;
|
|
41
|
+
}
|
|
42
|
+
return picture;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A row as NativeListItem draws it: `view.summary(row)`'s title, subtitle and chips, and nothing
|
|
47
|
+
* else. A view that wants a second line says so in its summary.
|
|
48
|
+
*/
|
|
49
|
+
export function rowItem<T extends Row>(view: AnyResourceView<T>, row: T): NativeResourceRowItem {
|
|
50
|
+
const summary = view.summary(row as T & DataRow);
|
|
51
|
+
return {
|
|
52
|
+
id: String(row.id ?? summary.title),
|
|
53
|
+
title: summary.title,
|
|
54
|
+
...(summary.subtitle ? { subtitle: summary.subtitle } : {}),
|
|
55
|
+
chips: summary.chips ?? [],
|
|
56
|
+
picture: nativePicture(summary),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface NativeResourceSection<T> {
|
|
61
|
+
key: string;
|
|
62
|
+
/** Empty for the one section of an ungrouped view (no header is drawn). */
|
|
63
|
+
title: string;
|
|
64
|
+
data: T[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Rows in sections by `definition.groupBy`, in the order each group first appears (the server's
|
|
69
|
+
* sort, so paging never reorders what's on screen). Without `groupBy`, one untitled section.
|
|
70
|
+
*/
|
|
71
|
+
export function sectionsFor<T extends Row>(
|
|
72
|
+
view: AnyResourceView<T>,
|
|
73
|
+
rows: readonly T[],
|
|
74
|
+
messages: NativeResourceViewMessages,
|
|
75
|
+
): NativeResourceSection<T>[] {
|
|
76
|
+
const field = view.definition.groupBy as string | undefined;
|
|
77
|
+
if (!field) return rows.length ? [{ key: "", title: "", data: [...rows] }] : [];
|
|
78
|
+
const display = view.display(field);
|
|
79
|
+
const groups = new Map<string, NativeResourceSection<T>>();
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
const value = row[field];
|
|
82
|
+
const key = isEmptyValue(value) ? "\u0000" : String(value);
|
|
83
|
+
let group = groups.get(key);
|
|
84
|
+
if (!group) {
|
|
85
|
+
const title = isEmptyValue(value)
|
|
86
|
+
? fill(messages.list.noGroup, { label: view.label(field).toLowerCase() })
|
|
87
|
+
: displayText(display, value, messages);
|
|
88
|
+
group = { key, title, data: [] };
|
|
89
|
+
groups.set(key, group);
|
|
90
|
+
}
|
|
91
|
+
group.data.push(row);
|
|
92
|
+
}
|
|
93
|
+
return [...groups.values()];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A row action: InboxPage's swipe action plus an icon name and, when a guard refuses it, why. */
|
|
97
|
+
export interface NativeResourceSwipeAction extends InboxSwipeAction {
|
|
98
|
+
/** An icon name from Genesis's set (`edit`, `trash`), mapped per platform. */
|
|
99
|
+
icon?: string;
|
|
100
|
+
/** Set when a guard refuses the action: pressing it explains instead of acting. */
|
|
101
|
+
reason?: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A screen's own rule. It only narrows: `false` hides the action, a sentence shows it refused. */
|
|
105
|
+
export type NativeResourceScreenCan<T> = (action: "create" | "update" | "delete", row?: T) => Allowed | boolean;
|
|
106
|
+
|
|
107
|
+
/** The effective right: the screen's rule AND the view's guard (never OR). */
|
|
108
|
+
export function allowed<T extends Row>(
|
|
109
|
+
view: AnyResourceView<T>,
|
|
110
|
+
action: "create" | "update" | "delete",
|
|
111
|
+
row: T | undefined,
|
|
112
|
+
screen?: NativeResourceScreenCan<T>,
|
|
113
|
+
): Allowed | false {
|
|
114
|
+
const own = screen?.(action, row);
|
|
115
|
+
if (own === false) return false;
|
|
116
|
+
if (typeof own === "string") return own;
|
|
117
|
+
const guard = action === "create" ? view.can("create") : row ? view.can(action, row as T & DataRow) : true;
|
|
118
|
+
return guard;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface SwipeActionOptions<T> {
|
|
122
|
+
messages: NativeResourceViewMessages;
|
|
123
|
+
/** The provider moves deleted rows to a recycle bin (`capabilities(resource).softDelete`). */
|
|
124
|
+
softDelete: boolean;
|
|
125
|
+
/** The view has fields a writer may change when editing. */
|
|
126
|
+
editable: boolean;
|
|
127
|
+
screen?: NativeResourceScreenCan<T>;
|
|
128
|
+
onEdit: (row: T) => void;
|
|
129
|
+
onDelete: (row: T) => void;
|
|
130
|
+
/** A refused action was pressed: say why. */
|
|
131
|
+
onRefused: (label: string, reason: string) => void;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A row's swipe actions, from the view's guards. A refused action stays in the list with its
|
|
136
|
+
* reason, so the person learns why; one the screen turns off (`false`) is left out.
|
|
137
|
+
*/
|
|
138
|
+
export function swipeActionsFor<T extends Row>(
|
|
139
|
+
view: AnyResourceView<T>,
|
|
140
|
+
row: T,
|
|
141
|
+
options: SwipeActionOptions<T>,
|
|
142
|
+
): NativeResourceSwipeAction[] {
|
|
143
|
+
const { messages, softDelete, editable, screen, onEdit, onDelete, onRefused } = options;
|
|
144
|
+
const actions: NativeResourceSwipeAction[] = [];
|
|
145
|
+
const add = (id: string, label: string, icon: string, right: Allowed | false, run: () => void, destructive = false) => {
|
|
146
|
+
if (right === false) return;
|
|
147
|
+
const reason = right === true ? undefined : right;
|
|
148
|
+
actions.push({
|
|
149
|
+
id,
|
|
150
|
+
label,
|
|
151
|
+
icon,
|
|
152
|
+
...(destructive ? { destructive } : {}),
|
|
153
|
+
...(reason ? { reason } : {}),
|
|
154
|
+
onPress: reason ? () => onRefused(label, reason) : run,
|
|
155
|
+
});
|
|
156
|
+
};
|
|
157
|
+
if (editable) add("edit", messages.common.edit, "edit", allowed(view, "update", row, screen), () => onEdit(row));
|
|
158
|
+
add(
|
|
159
|
+
"delete",
|
|
160
|
+
softDelete ? messages.bin.action : messages.delete.action,
|
|
161
|
+
"trash",
|
|
162
|
+
allowed(view, "delete", row, screen),
|
|
163
|
+
() => onDelete(row),
|
|
164
|
+
true,
|
|
165
|
+
);
|
|
166
|
+
return actions;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** How a form field is drawn. */
|
|
170
|
+
export type NativeFormFieldKind =
|
|
171
|
+
| "text"
|
|
172
|
+
| "email"
|
|
173
|
+
| "url"
|
|
174
|
+
| "number"
|
|
175
|
+
| "textarea"
|
|
176
|
+
| "switch"
|
|
177
|
+
| "segmented"
|
|
178
|
+
| "select"
|
|
179
|
+
| "date"
|
|
180
|
+
| "datetime";
|
|
181
|
+
|
|
182
|
+
export interface NativeFormField {
|
|
183
|
+
key: string;
|
|
184
|
+
label: string;
|
|
185
|
+
kind: NativeFormFieldKind;
|
|
186
|
+
display: DisplayHint;
|
|
187
|
+
required: boolean;
|
|
188
|
+
/** Shown as text, never as an input, and never sent. */
|
|
189
|
+
readOnly: boolean;
|
|
190
|
+
max?: number;
|
|
191
|
+
options?: { value: string; label: string }[];
|
|
192
|
+
/** The heading it sits under; null for the form's first, untitled group. */
|
|
193
|
+
section: string | null;
|
|
194
|
+
sectionTitle: string | null;
|
|
195
|
+
visible?: (values: Readonly<Record<string, unknown>>) => boolean;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Choices that fit a segmented control; more go to a list. */
|
|
199
|
+
const SEGMENTED_MAX = 4;
|
|
200
|
+
|
|
201
|
+
function kindFor(display: DisplayHint, options: unknown[] | undefined): NativeFormFieldKind {
|
|
202
|
+
if (options) return options.length <= SEGMENTED_MAX ? "segmented" : "select";
|
|
203
|
+
switch (display) {
|
|
204
|
+
case "boolean":
|
|
205
|
+
return "switch";
|
|
206
|
+
case "date":
|
|
207
|
+
return "date";
|
|
208
|
+
case "datetime":
|
|
209
|
+
return "datetime";
|
|
210
|
+
case "number":
|
|
211
|
+
case "currency":
|
|
212
|
+
case "percent":
|
|
213
|
+
return "number";
|
|
214
|
+
case "longText":
|
|
215
|
+
return "textarea";
|
|
216
|
+
case "email":
|
|
217
|
+
return "email";
|
|
218
|
+
case "url":
|
|
219
|
+
case "image":
|
|
220
|
+
return "url";
|
|
221
|
+
default:
|
|
222
|
+
return "text";
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The form sheet's fields: `view.form(mode)` (which already leaves out JSON, lists, links, scope,
|
|
228
|
+
* sensitive and unreadable fields and server-filled keys), each marked read-only unless
|
|
229
|
+
* `view.writable(mode)` lists it. Copied, never mutated: core caches and freezes `form()`. A create leaves read-only fields out (there is nothing to show yet); an edit shows
|
|
230
|
+
* them as text.
|
|
231
|
+
*/
|
|
232
|
+
export function formFieldsFor<T extends Row>(view: AnyResourceView<T>, mode: "create" | "edit"): NativeFormField[] {
|
|
233
|
+
const writable = new Set(view.writable(mode));
|
|
234
|
+
return view
|
|
235
|
+
.form(mode)
|
|
236
|
+
// JSON and lists need editors of their own; a plain input would send them back as text (as the web).
|
|
237
|
+
.filter((f) => f.display !== "json" && !f.field.array)
|
|
238
|
+
.filter((f) => mode === "edit" || writable.has(f.field.name))
|
|
239
|
+
.map((f) => {
|
|
240
|
+
const options = f.field.enumValues?.map((value) => ({ value, label: displayText("badge", value, EMPTY_WORDS) }));
|
|
241
|
+
const readOnly = !writable.has(f.field.name);
|
|
242
|
+
return {
|
|
243
|
+
key: f.field.name,
|
|
244
|
+
label: f.label,
|
|
245
|
+
kind: kindFor(f.display, options),
|
|
246
|
+
display: f.display,
|
|
247
|
+
required: !readOnly && f.required,
|
|
248
|
+
readOnly,
|
|
249
|
+
...(f.max !== undefined ? { max: f.max } : {}),
|
|
250
|
+
...(options ? { options } : {}),
|
|
251
|
+
section: f.section,
|
|
252
|
+
sectionTitle: f.sectionTitle,
|
|
253
|
+
...(f.visible ? { visible: f.visible } : {}),
|
|
254
|
+
};
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Only `badge` is formatted here, which reads no messages.
|
|
259
|
+
const EMPTY_WORDS = { common: { empty: "", yes: "", no: "" } } as NativeResourceViewMessages;
|
|
260
|
+
|
|
261
|
+
/** Fields shown for these values: a field whose `visible` says no is hidden, and isn't saved. */
|
|
262
|
+
export function shownFields(fields: readonly NativeFormField[], values: Readonly<Record<string, unknown>>): NativeFormField[] {
|
|
263
|
+
return fields.filter((f) => !f.visible || f.visible(values));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* What a save sends: only the keys `view.writable(mode)` lists and the form shows. Read-only,
|
|
268
|
+
* generated, key and scope fields, and anything else the values carry (joined columns), never go.
|
|
269
|
+
* An edit passes `dirty`, the fields the person changed, so a save never rewrites the rest. A
|
|
270
|
+
* cleared optional value (an empty text, a cleared number or date) is sent as null.
|
|
271
|
+
*/
|
|
272
|
+
export function writableValues<T extends Row>(
|
|
273
|
+
view: AnyResourceView<T>,
|
|
274
|
+
mode: "create" | "edit",
|
|
275
|
+
fields: readonly NativeFormField[],
|
|
276
|
+
values: Readonly<Record<string, unknown>>,
|
|
277
|
+
dirty?: ReadonlySet<string>,
|
|
278
|
+
): Record<string, unknown> {
|
|
279
|
+
const writable = new Set(view.writable(mode));
|
|
280
|
+
const out: Record<string, unknown> = {};
|
|
281
|
+
for (const field of shownFields(fields, values)) {
|
|
282
|
+
if (field.readOnly || !writable.has(field.key)) continue;
|
|
283
|
+
if (dirty && !dirty.has(field.key)) continue;
|
|
284
|
+
const value = values[field.key];
|
|
285
|
+
out[field.key] = (value === "" || value === undefined) && !field.required ? null : value;
|
|
286
|
+
}
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Field errors for a save: required fields with no value, and text over `max`. */
|
|
291
|
+
export function validateValues(
|
|
292
|
+
fields: readonly NativeFormField[],
|
|
293
|
+
values: Readonly<Record<string, unknown>>,
|
|
294
|
+
messages: NativeResourceViewMessages,
|
|
295
|
+
): Record<string, string> {
|
|
296
|
+
const errors: Record<string, string> = {};
|
|
297
|
+
for (const field of shownFields(fields, values)) {
|
|
298
|
+
if (field.readOnly) continue;
|
|
299
|
+
const value = values[field.key];
|
|
300
|
+
if (field.required && field.kind !== "switch" && (isEmptyValue(value) || (typeof value === "string" && !value.trim()))) {
|
|
301
|
+
errors[field.key] = fill(messages.form.required, { label: field.label });
|
|
302
|
+
} else if (field.max !== undefined && typeof value === "string" && value.length > field.max) {
|
|
303
|
+
errors[field.key] = fill(messages.form.tooLong, { label: field.label, max: field.max });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return errors;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* A refused write in plain words. A provider's `DataWriteError` (a zero-row update or delete it
|
|
311
|
+
* read back: forbidden, gone, a guard's message) already says it plainly; anything else gets the
|
|
312
|
+
* fallback sentence, never a raw driver message.
|
|
313
|
+
*/
|
|
314
|
+
export function refusalMessage(error: unknown, fallback: string): string {
|
|
315
|
+
if (error instanceof Error && error.name === "DataWriteError" && error.message) return error.message;
|
|
316
|
+
return fallback;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Per-field messages a provider attached to a refused write (`DataWriteError.fields`). */
|
|
320
|
+
export function refusalFields(error: unknown): Record<string, string> {
|
|
321
|
+
if (error instanceof Error && error.name === "DataWriteError") {
|
|
322
|
+
const fields = (error as Error & { fields?: Record<string, string> }).fields;
|
|
323
|
+
if (fields) return { ...fields };
|
|
324
|
+
}
|
|
325
|
+
return {};
|
|
326
|
+
}
|