@marktiderman/genesis-ui-native 3.3.0 → 3.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-ui-native",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -83,8 +83,8 @@
83
83
  "@expo/ui": ">=58.0.0",
84
84
  "@gorhom/bottom-sheet": ">=5.0.0",
85
85
  "@hookform/resolvers": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0",
86
- "@marktiderman/genesis-core": "^2.4.1",
87
- "@marktiderman/genesis-design-system": "^1.6.1",
86
+ "@marktiderman/genesis-core": "^2.6.0",
87
+ "@marktiderman/genesis-design-system": "^1.7.0",
88
88
  "@react-native-community/datetimepicker": ">=8.0.0",
89
89
  "@shopify/flash-list": ">=2.0.0",
90
90
  "@tanstack/react-query": "^5.0.0",
@@ -1,7 +1,7 @@
1
1
  import { titleCase } from "@marktiderman/genesis-core";
2
2
  import type { ResourceFormFieldDef } from "@marktiderman/genesis-core";
3
3
  import { Controller, type Control } from "react-hook-form";
4
- import { Pressable, View } from "react-native";
4
+ import { Pressable, View, type TextInputProps } from "react-native";
5
5
  import { NativeCheckbox } from "../components/checkbox";
6
6
  import { NativeInput } from "../components/input";
7
7
  import { NativeLabel } from "../components/label";
@@ -31,9 +31,10 @@ export interface NativeResourceFormFieldRendererProps {
31
31
  // Static lookup maps (module-scoped to avoid re-creation on each render)
32
32
  // ---------------------------------------------------------------------------
33
33
 
34
- const KEYBOARD_TYPE_MAP: Record<string, "default" | "email-address" | "url"> = {
34
+ const KEYBOARD_TYPE_MAP: Record<string, "default" | "email-address" | "url" | "phone-pad"> = {
35
35
  email: "email-address",
36
36
  url: "url",
37
+ tel: "phone-pad",
37
38
  text: "default",
38
39
  date: "default",
39
40
  };
@@ -41,6 +42,7 @@ const KEYBOARD_TYPE_MAP: Record<string, "default" | "email-address" | "url"> = {
41
42
  const AUTO_CAPITALIZE_MAP: Record<string, "none" | "sentences" | "words" | "characters"> = {
42
43
  email: "none",
43
44
  url: "none",
45
+ tel: "none",
44
46
  text: "sentences",
45
47
  date: "none",
46
48
  };
@@ -246,7 +248,9 @@ function NativeResourceFormFieldRenderer({
246
248
  }
247
249
 
248
250
  // ------------------------------------------------------------------
249
- // Text, email, url, date (and any other text-like types)
251
+ // Text, email, tel, url, date (and any other text-like types). Autofill only when the
252
+ // field asks for it (as on the web): on a form about someone else it would fill in the
253
+ // person holding the phone.
250
254
  // ------------------------------------------------------------------
251
255
  return (
252
256
  <View className="gap-1.5">
@@ -255,6 +259,11 @@ function NativeResourceFormFieldRenderer({
255
259
  placeholder={field.placeholder}
256
260
  keyboardType={KEYBOARD_TYPE_MAP[fieldType] ?? "default"}
257
261
  autoCapitalize={AUTO_CAPITALIZE_MAP[fieldType] ?? "sentences"}
262
+ {...(field.autoComplete
263
+ ? { autoComplete: field.autoComplete as TextInputProps["autoComplete"] }
264
+ : {})}
265
+ {...(field.inputMode ? { inputMode: field.inputMode } : {})}
266
+ {...(field.enterKeyHint ? { enterKeyHint: field.enterKeyHint } : {})}
258
267
  value={f.value != null ? String(f.value) : ""}
259
268
  onChangeText={f.onChange}
260
269
  editable={!isDisabled}
@@ -0,0 +1,191 @@
1
+ // A link's picker in NativeResourceView's form sheet (docs/RESOURCE-VIEW.md, "Links in forms"): the
2
+ // same rows as the web's RelationField, from core's useLinkOptions: the linked resource through
3
+ // the provider, under the linked view's scope and default filter, searched on the server and a
4
+ // page at a time. A row shows the chosen row's words; pressing it opens the list in place (no
5
+ // second sheet over the form), with a search bar, None for an optional link, and Show more.
6
+
7
+ import { useEffect, useMemo, useState } from "react";
8
+ import { Pressable, Text, View } from "react-native";
9
+ import { useLinkOptions, useRelationLabel, useViewer } from "@marktiderman/genesis-core/hooks";
10
+ import { NativeLabel } from "../../components/label";
11
+ import { NativeSearchBar } from "../../components/search-bar";
12
+ import { NativeText } from "../../components/text";
13
+ import { NativeButton } from "../../components/button";
14
+ import { isEmptyValue, useNativeResourceViewMessages } from "./display";
15
+ import { defaultNativeResourceViewMessages } from "./messages";
16
+ import type { NativeFormField } from "./mapping";
17
+
18
+ /** How long typing settles before the search goes to the server. */
19
+ const SEARCH_DEBOUNCE_MS = 300;
20
+
21
+ export interface NativeLinkPickerProps {
22
+ field: NativeFormField;
23
+ value: unknown;
24
+ /** The picked row's key as the row holds it; `null` when None is chosen. */
25
+ onChange: (value: string | number | null) => void;
26
+ /** The form's values, for a picker whose filters follow another field. */
27
+ values: Readonly<Record<string, unknown>>;
28
+ error?: string | undefined;
29
+ testID: string;
30
+ }
31
+
32
+ export function NativeLinkPicker({ field, value, onChange, values, error, testID }: NativeLinkPickerProps) {
33
+ const messages = useNativeResourceViewMessages();
34
+ const words = { ...defaultNativeResourceViewMessages.link!, ...messages.link };
35
+ const link = field.link!;
36
+ const viewer = useViewer();
37
+ const [open, setOpen] = useState(false);
38
+ const [query, setQuery] = useState("");
39
+ const [search, setSearch] = useState("");
40
+ useEffect(() => {
41
+ const timer = setTimeout(() => setSearch(query), SEARCH_DEBOUNCE_MS);
42
+ return () => clearTimeout(timer);
43
+ }, [query]);
44
+
45
+ // By value: the sheet re-renders on every keystroke.
46
+ const filtersKey = JSON.stringify(link.filters(viewer.scope, values));
47
+ const filters = useMemo(() => JSON.parse(filtersKey) as ReturnType<typeof link.filters>, [filtersKey]);
48
+ const labelField = field.labelField ?? link.labelField;
49
+ const list = useLinkOptions(
50
+ { resource: link.resource, field: link.field, labelField, searchFields: link.searchFields },
51
+ { filters, search, enabled: open, untitled: words.untitled! },
52
+ );
53
+
54
+ const loaded = isEmptyValue(value) ? undefined : list.options.find((o) => String(o.value) === String(value));
55
+ const looked = useRelationLabel({ resource: link.resource, field: link.field }, value, {
56
+ ...((list.labelField ?? labelField) ? { labelField: (list.labelField ?? labelField)! } : {}),
57
+ enabled: !isEmptyValue(value) && !loaded,
58
+ });
59
+ const chosen = isEmptyValue(value)
60
+ ? null
61
+ : (loaded?.label ??
62
+ (looked === undefined
63
+ ? undefined
64
+ : (looked ?? field.missingLabel ?? messages.common.hiddenLink ?? defaultNativeResourceViewMessages.common.hiddenLink!)));
65
+ const shown = chosen === undefined ? messages.common.empty : (chosen ?? words.placeholder!);
66
+
67
+ const pick = (next: string | number | null) => {
68
+ onChange(next);
69
+ setOpen(false);
70
+ setQuery("");
71
+ };
72
+
73
+ return (
74
+ <View testID={testID} style={{ gap: 6 }}>
75
+ <NativeLabel>{field.label}</NativeLabel>
76
+ <Pressable
77
+ testID={`${testID}-trigger`}
78
+ accessibilityRole="button"
79
+ // The error is read with the field, not only shown under it.
80
+ accessibilityLabel={error ? `${field.label}, ${shown}, ${error}` : `${field.label}, ${shown}`}
81
+ accessibilityState={{ expanded: open }}
82
+ onPress={() => setOpen((was) => !was)}
83
+ className="min-h-[44px] flex-row items-center justify-between rounded-md border border-input bg-background px-3"
84
+ >
85
+ <Text className={chosen ? "text-base text-foreground" : "text-base text-muted-foreground"} numberOfLines={1}>
86
+ {shown}
87
+ </Text>
88
+ <Text className="text-muted-foreground" accessible={false}>
89
+ {open ? "▴" : "▾"}
90
+ </Text>
91
+ </Pressable>
92
+ {open ? (
93
+ <View testID={`${testID}-list`} style={{ gap: 4 }} accessibilityRole="radiogroup" accessibilityLabel={field.label}>
94
+ {list.searchable ? (
95
+ <NativeSearchBar
96
+ testID={`${testID}-search`}
97
+ value={query}
98
+ onChange={setQuery}
99
+ placeholder={words.search!}
100
+ showCancel={false}
101
+ />
102
+ ) : null}
103
+ {!field.required && query === "" ? (
104
+ <Option
105
+ testID={`${testID}-none`}
106
+ label={words.none!}
107
+ muted
108
+ selected={isEmptyValue(value)}
109
+ onPress={() => pick(null)}
110
+ />
111
+ ) : null}
112
+ {list.isLoading ? (
113
+ <NativeText preset="caption" className="px-3 py-2 text-muted-foreground" testID={`${testID}-loading`}>
114
+ {messages.form.loading}
115
+ </NativeText>
116
+ ) : list.isError ? (
117
+ <NativeText preset="caption" className="px-3 py-2 text-destructive" accessibilityRole="alert">
118
+ {words.loadFailed}
119
+ </NativeText>
120
+ ) : list.options.length === 0 ? (
121
+ <NativeText preset="caption" className="px-3 py-2 text-muted-foreground" testID={`${testID}-empty`}>
122
+ {words.noResults}
123
+ </NativeText>
124
+ ) : (
125
+ list.options.map((option) => (
126
+ <Option
127
+ key={String(option.value)}
128
+ testID={`${testID}-option-${String(option.value)}`}
129
+ label={option.label}
130
+ selected={!isEmptyValue(value) && String(value) === String(option.value)}
131
+ onPress={() => pick(option.value)}
132
+ />
133
+ ))
134
+ )}
135
+ {list.hasMore ? (
136
+ <NativeButton
137
+ variant="ghost"
138
+ size="sm"
139
+ testID={`${testID}-more`}
140
+ disabled={list.isLoadingMore}
141
+ onPress={list.loadMore}
142
+ >
143
+ {list.isLoadingMore ? messages.list.loadingMore : words.loadMore!}
144
+ </NativeButton>
145
+ ) : null}
146
+ </View>
147
+ ) : null}
148
+ {error ? (
149
+ // A live region on Android; the alert role on iOS and the web.
150
+ <View accessibilityLiveRegion="polite">
151
+ <NativeText preset="caption" className="text-destructive" testID={`${testID}-error`} accessibilityRole="alert">
152
+ {error}
153
+ </NativeText>
154
+ </View>
155
+ ) : null}
156
+ </View>
157
+ );
158
+ }
159
+
160
+ function Option({
161
+ label,
162
+ selected,
163
+ muted = false,
164
+ onPress,
165
+ testID,
166
+ }: {
167
+ label: string;
168
+ selected: boolean;
169
+ muted?: boolean;
170
+ onPress: () => void;
171
+ testID: string;
172
+ }) {
173
+ return (
174
+ <Pressable
175
+ testID={testID}
176
+ // One choice of several: a radio, checked when it's the link's row.
177
+ accessibilityRole="radio"
178
+ accessibilityLabel={label}
179
+ accessibilityState={{ checked: selected }}
180
+ onPress={onPress}
181
+ className="min-h-[44px] flex-row items-center justify-between px-3"
182
+ >
183
+ <Text className={muted ? "text-base text-muted-foreground" : "text-base text-foreground"}>{label}</Text>
184
+ {selected ? (
185
+ <Text className="text-base text-primary" accessible={false}>
186
+ ✓
187
+ </Text>
188
+ ) : null}
189
+ </Pressable>
190
+ );
191
+ }
@@ -1,6 +1,7 @@
1
1
  // The form sheet a NativeResourceView opens for New and Edit: Cancel and Save in the bar, the
2
2
  // view's sections as grouped sections, native date and time pickers, choices as a segmented
3
- // control (up to four) or a list. Text, number, switch and list fields are drawn by
3
+ // control (up to four) or a list, links as a searchable list of the linked rows (NativeLinkPicker).
4
+ // Text, number, switch and list fields are drawn by
4
5
  // NativeResourceFormFieldRenderer, the same as NativeResourceForm. Read-only fields are text, never
5
6
  // inputs, and a save sends only the view's writable keys.
6
7
 
@@ -22,6 +23,7 @@ import { NativeResourceFormFieldRenderer } from "../NativeResourceFormField";
22
23
  import { dateToDay, dayToDate, displayText, isEmptyValue, resolveZone, useDisplayTimeZones, useNativeResourceViewMessages } from "./display";
23
24
  import { defaultNativeResourceViewMessages, fill } from "./messages";
24
25
  import { shownFields, type NativeFormField } from "./mapping";
26
+ import { NativeLinkPicker } from "./NativeLinkPicker";
25
27
  import type { SaveResult } from "./use-native-resource-view";
26
28
 
27
29
  type Values = Record<string, unknown>;
@@ -46,6 +48,7 @@ export interface NativeResourceFormSheetProps {
46
48
  const FIELD_TYPE: Partial<Record<NativeFormField["kind"], ResourceFormFieldDef["type"]>> = {
47
49
  text: "text",
48
50
  email: "email",
51
+ tel: "tel",
49
52
  url: "url",
50
53
  number: "number",
51
54
  textarea: "textarea",
@@ -221,6 +224,24 @@ function FormField({
221
224
  </View>
222
225
  );
223
226
  }
227
+ if (field.kind === "link" && field.link) {
228
+ return (
229
+ <Controller
230
+ name={field.key}
231
+ control={f.control}
232
+ render={({ field: input }) => (
233
+ <NativeLinkPicker
234
+ field={field}
235
+ value={input.value}
236
+ onChange={input.onChange}
237
+ values={f.getValues()}
238
+ error={error}
239
+ testID={id}
240
+ />
241
+ )}
242
+ />
243
+ );
244
+ }
224
245
  const type = FIELD_TYPE[field.kind];
225
246
  if (type) {
226
247
  const def: ResourceFormFieldDef = {
@@ -230,6 +251,9 @@ function FormField({
230
251
  required: field.required,
231
252
  ...(field.options ? { options: field.options } : {}),
232
253
  ...(field.max !== undefined ? { maxLength: field.max } : {}),
254
+ ...(field.autoComplete ? { autoComplete: field.autoComplete } : {}),
255
+ ...(field.inputMode ? { inputMode: field.inputMode } : {}),
256
+ ...(field.enterKeyHint ? { enterKeyHint: field.enterKeyHint } : {}),
233
257
  };
234
258
  return (
235
259
  <View testID={id}>
@@ -0,0 +1,201 @@
1
+ // @feat:resource-view-links
2
+ /**
3
+ * A link's picker in NativeResourceView's form sheet: the linked rows through the provider, under
4
+ * the linked view's scope and default filter; the picked key saved; None clears to null; a link
5
+ * the screen's filter pins stays read-only.
6
+ */
7
+ import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
8
+ import { QueryClient } from "@tanstack/react-query";
9
+ import type { ReactNode } from "react";
10
+ import { describe, expect, it, vi } from "vitest";
11
+ import { defineResource, GenesisProvider, ViewerScope, type DataProvider, type FilterParam, type ListParams } from "@marktiderman/genesis-core";
12
+ import { defineView } from "@marktiderman/genesis-core/resource-view";
13
+ import { formFieldsFor, NativeResourceView, useNativeResourceView, writableValues } from "..";
14
+
15
+ type Task = { id: string; org_id: string; title: string; owner_id: string; reviewer_id: string | null };
16
+ type Person = { id: string; org_id: string; full_name: string; active: boolean };
17
+
18
+ const tasks = defineResource<Task>()({
19
+ name: "tasks",
20
+ key: "id",
21
+ labelField: "title",
22
+ fields: [
23
+ { name: "id", type: "string", hasDefault: true },
24
+ { name: "org_id", type: "string" },
25
+ { name: "title", type: "string" },
26
+ { name: "owner_id", type: "string", references: { resource: "people", field: "id" } },
27
+ { name: "reviewer_id", type: "string", nullable: true, references: { resource: "people", field: "id" } },
28
+ ],
29
+ });
30
+ const people = defineResource<Person>()({
31
+ name: "people",
32
+ key: "id",
33
+ labelField: "full_name",
34
+ fields: [
35
+ { name: "id", type: "string" },
36
+ { name: "org_id", type: "string" },
37
+ { name: "full_name", type: "string" },
38
+ { name: "active", type: "boolean" },
39
+ ],
40
+ });
41
+ const peopleView = defineView(people, { scope: ["org_id"], presets: { default: { filter: { active: true } } } });
42
+ const tasksView = defineView(tasks, {
43
+ scope: ["org_id"],
44
+ form: ["title", "owner_id", "reviewer_id"],
45
+ fields: { owner_id: { label: "Owner", link: { view: peopleView } }, reviewer_id: { label: "Reviewer", link: { view: peopleView } } },
46
+ });
47
+
48
+ const PEOPLE: Person[] = [
49
+ { id: "ada", org_id: "o1", full_name: "Ada Lovelace", active: true },
50
+ { id: "grace", org_id: "o1", full_name: "Grace Hopper", active: true },
51
+ { id: "gone", org_id: "o1", full_name: "Former Person", active: false },
52
+ { id: "other", org_id: "o2", full_name: "Elsewhere Person", active: true },
53
+ ];
54
+ const TASK: Task = { id: "t1", org_id: "o1", title: "Write", owner_id: "ada", reviewer_id: "grace" };
55
+
56
+ const matches = (row: Record<string, unknown>, f: FilterParam) =>
57
+ f.operator === "eq" ? row[f.field] === f.value : f.operator === "in" ? (f.value as unknown[]).includes(row[f.field]) : true;
58
+
59
+ function setup() {
60
+ const getList = vi.fn(async (resource: string, params: ListParams) => {
61
+ if (resource === "tasks") return { data: [TASK], total: 1 };
62
+ let rows = PEOPLE.filter((p) => (params.filters ?? []).every((f) => matches(p, f)));
63
+ if (params.search?.query) rows = rows.filter((p) => p.full_name.toLowerCase().includes(params.search!.query.toLowerCase()));
64
+ return { data: rows, total: rows.length };
65
+ });
66
+ const provider: DataProvider = {
67
+ getList: getList as unknown as DataProvider["getList"],
68
+ getOne: vi.fn(async () => ({ data: TASK })) as DataProvider["getOne"],
69
+ getMany: vi.fn(async () => ({ data: [] })),
70
+ create: vi.fn(async (_r, { data }) => ({ data: { id: "new", ...(data as object) } })) as DataProvider["create"],
71
+ update: vi.fn(async (_r, { id, data }) => ({ data: { id, ...(data as object) } })) as DataProvider["update"],
72
+ deleteOne: vi.fn(),
73
+ };
74
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
75
+ const Wrapper = ({ children }: { children: ReactNode }) => (
76
+ <GenesisProvider provider={provider} queryClient={queryClient}>
77
+ <ViewerScope viewer="u1" scope={{ orgId: "o1" }} timeZone="UTC">
78
+ {children}
79
+ </ViewerScope>
80
+ </GenesisProvider>
81
+ );
82
+ const peopleLists = () => getList.mock.calls.filter(([r, p]) => r === "people" && !(p.filters ?? []).some((f) => f.field === "id"));
83
+ return { Wrapper, provider, peopleLists };
84
+ }
85
+
86
+ const field = (key: string) => `native-resource-view-form-field-${key}`;
87
+
88
+ describe("a link's picker in the native form sheet", () => {
89
+ it("is a picker, not a typed id", () => {
90
+ const fields = formFieldsFor(tasksView, "create");
91
+ expect(fields.find((f) => f.key === "owner_id")).toMatchObject({ kind: "link", readOnly: false, required: true });
92
+ expect(fields.find((f) => f.key === "reviewer_id")).toMatchObject({ kind: "link", required: false });
93
+ });
94
+
95
+ it("lists the linked rows through the provider under the linked view's scope and default filter, and saves the picked key", async () => {
96
+ const { Wrapper, provider, peopleLists } = setup();
97
+ render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
98
+ fireEvent.click(await screen.findByTestId("native-resource-view-create"));
99
+ const form = await screen.findByTestId("native-resource-view-form");
100
+ fireEvent.change(within(form).getByTestId(field("title")).querySelector("input")!, { target: { value: "Ship" } });
101
+ expect(peopleLists()).toHaveLength(0);
102
+ fireEvent.click(within(form).getByTestId(`${field("owner_id")}-trigger`));
103
+ await waitFor(() => expect(within(form).getByTestId(`${field("owner_id")}-option-grace`)).toBeTruthy());
104
+ expect(peopleLists()[0]![1].filters).toEqual([
105
+ { field: "org_id", operator: "eq", value: "o1" },
106
+ { field: "active", operator: "eq", value: true },
107
+ ]);
108
+ expect(within(form).queryByTestId(`${field("owner_id")}-option-gone`)).toBeNull();
109
+ expect(within(form).queryByTestId(`${field("owner_id")}-option-other`)).toBeNull();
110
+ // A required link has no None.
111
+ expect(within(form).queryByTestId(`${field("owner_id")}-none`)).toBeNull();
112
+ fireEvent.click(within(form).getByTestId(`${field("owner_id")}-option-grace`));
113
+ await waitFor(() => expect(within(form).getByTestId(`${field("owner_id")}-trigger`).textContent).toContain("Grace Hopper"));
114
+ fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
115
+ await waitFor(() => expect(provider.create).toHaveBeenCalled());
116
+ expect((provider.create as ReturnType<typeof vi.fn>).mock.calls[0]![1].data).toMatchObject({ title: "Ship", owner_id: "grace" });
117
+ });
118
+
119
+ it("clears an optional link to null with None", () => {
120
+ const fields = formFieldsFor(tasksView, "edit");
121
+ expect(writableValues(tasksView, "edit", fields, { ...TASK, reviewer_id: null }, new Set(["reviewer_id"]))).toEqual({ reviewer_id: null });
122
+ });
123
+
124
+ it("offers None for an optional link, and saves null", async () => {
125
+ const { Wrapper, provider } = setup();
126
+ render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
127
+ const row = await screen.findByTestId("native-resource-view-row-t1");
128
+ act(() => {
129
+ row.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "edit" }));
130
+ });
131
+ const form = await screen.findByTestId("native-resource-view-form");
132
+ const trigger = await within(form).findByTestId(`${field("reviewer_id")}-trigger`);
133
+ await waitFor(() => expect(trigger.textContent).toContain("Grace Hopper"));
134
+ fireEvent.click(trigger);
135
+ fireEvent.click(await within(form).findByTestId(`${field("reviewer_id")}-none`));
136
+ fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
137
+ await waitFor(() => expect(provider.update).toHaveBeenCalled());
138
+ expect((provider.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toEqual({ id: "t1", data: { reviewer_id: null } });
139
+ });
140
+
141
+ it("keeps a link the screen's filter pins read-only on edit, and never sends it", async () => {
142
+ const { Wrapper, provider } = setup();
143
+ const { result } = renderHook(() => useNativeResourceView(tasksView, { filter: { owner_id: "ada" } }), { wrapper: Wrapper });
144
+ await waitFor(() => expect(result.current.rows).toHaveLength(1));
145
+ expect(result.current.formFields("create").map((f) => f.key)).toEqual(["title", "reviewer_id"]);
146
+ expect(result.current.formFields("edit").find((f) => f.key === "owner_id")).toMatchObject({ readOnly: true });
147
+ await act(async () => {
148
+ await result.current.save("edit", { ...TASK, owner_id: "grace", title: "Changed" }, TASK, new Set(["owner_id", "title"]));
149
+ });
150
+ expect((provider.update as ReturnType<typeof vi.fn>).mock.calls[0]![1]).toEqual({ id: "t1", data: { title: "Changed" } });
151
+ });
152
+
153
+ it("draws each choice as a radio, checked when it's the link's row", async () => {
154
+ const { Wrapper } = setup();
155
+ render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
156
+ const row = await screen.findByTestId("native-resource-view-row-t1");
157
+ act(() => {
158
+ row.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "edit" }));
159
+ });
160
+ const form = await screen.findByTestId("native-resource-view-form");
161
+ fireEvent.click(await within(form).findByTestId(`${field("owner_id")}-trigger`));
162
+ const ada = await within(form).findByTestId(`${field("owner_id")}-option-ada`);
163
+ const grace = within(form).getByTestId(`${field("owner_id")}-option-grace`);
164
+ expect(ada.getAttribute("role")).toBe("radio");
165
+ expect(ada.getAttribute("aria-checked")).toBe("true");
166
+ expect(grace.getAttribute("aria-checked")).toBe("false");
167
+ });
168
+
169
+ it("announces an error: in the trigger's label and as an alert", async () => {
170
+ const { Wrapper } = setup();
171
+ render(<NativeResourceView view={tasksView} />, { wrapper: Wrapper });
172
+ fireEvent.click(await screen.findByTestId("native-resource-view-create"));
173
+ const form = await screen.findByTestId("native-resource-view-form");
174
+ fireEvent.change(within(form).getByTestId(field("title")).querySelector("input")!, { target: { value: "Ship" } });
175
+ fireEvent.click(within(form).getByTestId("native-resource-view-form-save"));
176
+ const error = await within(form).findByTestId(`${field("owner_id")}-error`);
177
+ expect(error.getAttribute("role")).toBe("alert");
178
+ expect(within(form).getByTestId(`${field("owner_id")}-trigger`).getAttribute("aria-label")).toContain(error.textContent!);
179
+ });
180
+
181
+ it("offers only the rows of a list (in) filter on the link", () => {
182
+ const fields = formFieldsFor(tasksView, "edit", { within: { owner_id: ["ada", "gone"] } });
183
+ const owner = fields.find((f) => f.key === "owner_id")!;
184
+ expect(owner.link!.filters({ orgId: "o1" })).toEqual([
185
+ { field: "org_id", operator: "eq", value: "o1" },
186
+ { field: "active", operator: "eq", value: true },
187
+ { field: "id", operator: "in", value: ["ada", "gone"] },
188
+ ]);
189
+ expect(owner.link!.labelField).toBe("full_name");
190
+ // Other links are as they were.
191
+ expect(fields.find((f) => f.key === "reviewer_id")!.link!.filters({ orgId: "o1" })).toHaveLength(2);
192
+ });
193
+
194
+ it("holds the picker to a screen's list filter", async () => {
195
+ const { Wrapper } = setup();
196
+ const { result } = renderHook(() => useNativeResourceView(tasksView, { filter: { owner_id: ["ada", "grace"] } }), { wrapper: Wrapper });
197
+ await waitFor(() => expect(result.current.rows).toHaveLength(1));
198
+ const owner = result.current.formFields("create").find((f) => f.key === "owner_id")!;
199
+ expect(owner.link!.filters({ orgId: "o1" }).at(-1)).toEqual({ field: "id", operator: "in", value: ["ada", "grace"] });
200
+ });
201
+ });
@@ -0,0 +1,79 @@
1
+ // @feat:native-components
2
+ /**
3
+ * A phone number on the native form sheet, as on the web: `tel` only when the contract declares
4
+ * `widget: "tel"` (never from a column's name), the phone keypad, and autofill only when the view
5
+ * field asks for it.
6
+ */
7
+ import { fireEvent, render, screen } from "@testing-library/react";
8
+ import { QueryClient } from "@tanstack/react-query";
9
+ import type { ReactNode } from "react";
10
+ import { describe, expect, it, vi } from "vitest";
11
+ import { defineResource, GenesisProvider, type DataProvider } from "@marktiderman/genesis-core";
12
+ import { defineView } from "@marktiderman/genesis-core/resource-view";
13
+ import { formFieldsFor, NativeResourceView } from "..";
14
+
15
+ type Person = { id: string; name: string; phone: string | null; mobile: string | null };
16
+
17
+ const people = defineResource<Person>()({
18
+ name: "people",
19
+ key: "id",
20
+ labelField: "name",
21
+ fields: [
22
+ { name: "id", type: "string", hasDefault: true },
23
+ { name: "name", type: "string" },
24
+ { name: "phone", type: "string", nullable: true, widget: "tel" },
25
+ // Named like a phone number, declared as nothing: stays text.
26
+ { name: "mobile", type: "string", nullable: true },
27
+ ],
28
+ });
29
+
30
+ const view = defineView(people, { form: ["name", "phone", "mobile"] });
31
+ const signUpView = defineView(people, { fields: { phone: { autoComplete: "tel", enterKeyHint: "next" } }, form: ["name", "phone"] });
32
+
33
+ function provider(): DataProvider {
34
+ return {
35
+ getList: vi.fn(async () => ({ data: [], total: 0 })) as DataProvider["getList"],
36
+ getOne: vi.fn(async () => ({ data: undefined })) as unknown as DataProvider["getOne"],
37
+ getMany: vi.fn(async () => ({ data: [] })),
38
+ create: vi.fn(async (_r, { data }) => ({ data })) as DataProvider["create"],
39
+ update: vi.fn(async (_r, { data }) => ({ data })) as DataProvider["update"],
40
+ deleteOne: vi.fn(async (_r, { id }) => ({ data: { id } })),
41
+ };
42
+ }
43
+
44
+ /** Opens the create sheet and hands back a lookup for its inputs. */
45
+ async function createSheet(v: typeof view | typeof signUpView) {
46
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
47
+ const Wrap = ({ children }: { children: ReactNode }) => (
48
+ <GenesisProvider provider={provider()} queryClient={queryClient}>
49
+ {children}
50
+ </GenesisProvider>
51
+ );
52
+ render(<NativeResourceView view={v} />, { wrapper: Wrap });
53
+ fireEvent.click(await screen.findByTestId("native-resource-view-create"));
54
+ await screen.findByTestId("native-resource-view-form-field-name");
55
+ return (key: string) => screen.getByTestId(`native-resource-view-form-field-${key}`).querySelector("input")!;
56
+ }
57
+
58
+ describe("native tel fields", () => {
59
+ it("is a tel kind only when the contract declares widget: tel", () => {
60
+ const fields = formFieldsFor(view, "create");
61
+ expect(fields.find((f) => f.key === "phone")?.kind).toBe("tel");
62
+ expect(fields.find((f) => f.key === "mobile")?.kind).toBe("text");
63
+ });
64
+
65
+ it("shows the phone keypad, and asks for no autofill unless the view field does", async () => {
66
+ const input = await createSheet(view);
67
+ expect(input("phone").getAttribute("data-keyboard-type")).toBe("phone-pad");
68
+ expect(input("phone").hasAttribute("data-autocomplete")).toBe(false);
69
+ expect(input("mobile").getAttribute("data-keyboard-type")).toBe("default");
70
+ });
71
+
72
+ it("passes the view field's autoComplete and enterKeyHint through", async () => {
73
+ expect(formFieldsFor(signUpView, "create").find((f) => f.key === "phone")?.autoComplete).toBe("tel");
74
+ const input = await createSheet(signUpView);
75
+ expect(input("phone").getAttribute("data-autocomplete")).toBe("tel");
76
+ expect(input("phone").getAttribute("data-enter-key-hint")).toBe("next");
77
+ expect(input("name").hasAttribute("data-autocomplete")).toBe(false);
78
+ });
79
+ });