@marktiderman/genesis-ui-native 3.11.0 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +69 -0
  2. package/dist/{chunk-ZUR4PK77.js → chunk-47CDRP43.js} +45 -166
  3. package/dist/chunk-47CDRP43.js.map +1 -0
  4. package/dist/{chunk-SG7LYX7Z.js → chunk-BQYT6TH2.js} +14 -6
  5. package/dist/chunk-BQYT6TH2.js.map +1 -0
  6. package/dist/{chunk-EAHK7D7N.js → chunk-C2ARUGT7.js} +146 -42
  7. package/dist/chunk-C2ARUGT7.js.map +1 -0
  8. package/dist/{chunk-VEWSY4TZ.js → chunk-D4UU6KIF.js} +236 -21
  9. package/dist/chunk-D4UU6KIF.js.map +1 -0
  10. package/dist/{chunk-GGH3ZQNO.js → chunk-TUDJDIGC.js} +4 -4
  11. package/dist/{chunk-GGH3ZQNO.js.map → chunk-TUDJDIGC.js.map} +1 -1
  12. package/dist/{chunk-PMS2V46D.js → chunk-VHUUOH46.js} +2 -2
  13. package/dist/{chunk-PMS2V46D.js.map → chunk-VHUUOH46.js.map} +1 -1
  14. package/dist/{chunk-IWWXERKQ.js → chunk-X5CPLUPZ.js} +1236 -136
  15. package/dist/chunk-X5CPLUPZ.js.map +1 -0
  16. package/dist/components/index.d.ts +510 -25
  17. package/dist/components/index.js +5 -5
  18. package/dist/data/index.d.ts +167 -33
  19. package/dist/data/index.js +1082 -760
  20. package/dist/data/index.js.map +1 -1
  21. package/dist/hooks/index.d.ts +2 -2
  22. package/dist/hooks/index.js +1 -1
  23. package/dist/icons/lucide.d.ts +1 -1
  24. package/dist/index.d.ts +6 -3
  25. package/dist/index.js +7 -7
  26. package/dist/layouts/index.d.ts +79 -6
  27. package/dist/layouts/index.js +5 -5
  28. package/dist/{native-modules-Bkm1jHO-.d.ts → native-modules-6JnyeGR-.d.ts} +55 -1
  29. package/package.json +70 -4
  30. package/src/components/__tests__/combobox.test.tsx +20 -0
  31. package/src/components/__tests__/number-input.test.tsx +112 -1
  32. package/src/components/__tests__/parity-controls.test.tsx +366 -0
  33. package/src/components/__tests__/parity-display.test.tsx +295 -0
  34. package/src/components/__tests__/twin-props.test.tsx +114 -0
  35. package/src/components/badge.tsx +3 -0
  36. package/src/components/button-group.tsx +50 -0
  37. package/src/components/calendar.tsx +183 -0
  38. package/src/components/carousel.tsx +175 -0
  39. package/src/components/chart.tsx +268 -0
  40. package/src/components/chip-group.tsx +34 -14
  41. package/src/components/choice-card.tsx +56 -19
  42. package/src/components/combobox.tsx +6 -5
  43. package/src/components/empty-state.tsx +40 -0
  44. package/src/components/flatten-children.ts +13 -0
  45. package/src/components/index.ts +49 -1
  46. package/src/components/inline-alert.tsx +3 -1
  47. package/src/components/input-group.tsx +99 -0
  48. package/src/components/input-otp.tsx +124 -0
  49. package/src/components/input.tsx +40 -12
  50. package/src/components/list-item.tsx +20 -4
  51. package/src/components/number-input.tsx +45 -15
  52. package/src/components/radio-group.tsx +5 -0
  53. package/src/components/resource.tsx +227 -0
  54. package/src/components/settings-row.tsx +194 -0
  55. package/src/components/slider.tsx +3 -9
  56. package/src/components/sortable-list.tsx +287 -0
  57. package/src/components/stat-card.tsx +106 -0
  58. package/src/components/stepper.tsx +4 -2
  59. package/src/components/widget-tile.tsx +66 -0
  60. package/src/components/workspace-switcher.tsx +217 -0
  61. package/src/data/NativeCustomView.tsx +117 -0
  62. package/src/data/NativeFormFields.tsx +312 -0
  63. package/src/data/NativeRecordPeek.tsx +130 -0
  64. package/src/data/NativeResourceFormField.tsx +32 -0
  65. package/src/data/__tests__/parity-data.test.tsx +350 -0
  66. package/src/data/index.ts +13 -0
  67. package/src/layouts/__tests__/keyboard-scroll.test.tsx +58 -2
  68. package/src/layouts/__tests__/notifications-page.test.tsx +12 -0
  69. package/src/layouts/index.ts +13 -0
  70. package/src/layouts/keyboard.tsx +22 -2
  71. package/src/layouts/notifications-page.tsx +13 -35
  72. package/src/layouts/pages.tsx +262 -0
  73. package/src/native-modules.tsx +37 -0
  74. package/dist/chunk-EAHK7D7N.js.map +0 -1
  75. package/dist/chunk-IWWXERKQ.js.map +0 -1
  76. package/dist/chunk-SG7LYX7Z.js.map +0 -1
  77. package/dist/chunk-VEWSY4TZ.js.map +0 -1
  78. package/dist/chunk-ZUR4PK77.js.map +0 -1
@@ -1,20 +1,21 @@
1
- import { NativeImage, NativeAvatar, NativeCard, NativeCardContent, NativeSeparator, NativeLabel, NativeSwitch, NativeCheckbox, NativeSelect, NativeSelectTrigger, NativeSelectContent, NativeSelectItem, NativeTextarea, NativeAlert, NativeAlertTitle, NativeAlertDescription, NativeInlineAlert, NativeSegmentedControl, NativeDatePicker, NativeTimePicker, NativeSearchBar, NativeGalleryGrid, NativeCardHeader, NativeCardTitle } from '../chunk-ZUR4PK77.js';
2
- import { showInboxActions, NavBarSaveButton, composeHeaderOptions } from '../chunk-GGH3ZQNO.js';
3
- import { NativeListItem, NativeBadge, NativeText, NativeButton, NativeInput, NativeSheet, NativeSheetScrollView, NativeLoadingState, NativeSectionListHeader, NativeEmptyState, NativeRefreshControl, NativeIcon, NativeSkeleton } from '../chunk-VEWSY4TZ.js';
4
- import { useGenesisModules, useThemeRoles } from '../chunk-PMS2V46D.js';
1
+ import { NativeAvatar, NativeCard, NativeCardContent, NativeSeparator, NativeLabel, NativeProgress, NativeSwitch, NativeCheckbox, NativeSelect, NativeSelectTrigger, NativeSelectContent, NativeSelectItem, NativeTextarea, NativeAlert, NativeAlertTitle, NativeAlertDescription, NativeSegmentedControl, NativeDatePicker, NativeTimePicker, NativeSearchBar, NativeGalleryGrid, NativeCardHeader, NativeCardTitle } from '../chunk-47CDRP43.js';
2
+ import { showInboxActions, NavBarSaveButton, composeHeaderOptions } from '../chunk-TUDJDIGC.js';
3
+ import { NativeListItem, NativeBadge, NativeText, NativeImage, NativeButton, NativeInput, NativeSheet, NativeSheetScrollView, NativeLoadingState, NativeInlineAlert, NativeSectionListHeader, NativeEmptyState, NativeRefreshControl, NativeIcon, NativeSkeleton } from '../chunk-D4UU6KIF.js';
4
+ import { useGenesisModules, useThemeRoles, useReducedMotion } from '../chunk-VHUUOH46.js';
5
5
  import '../chunk-OHZD7KRO.js';
6
6
  import '../chunk-DGUM43GV.js';
7
7
  import { Platform, View, Pressable, Text, Linking, ScrollView, AccessibilityInfo, Alert, SectionList, ActionSheetIOS, FlatList } from 'react-native';
8
8
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
9
9
  import * as React from 'react';
10
- import { createContext, memo, useState, useCallback, useEffect, useMemo, useContext, useRef, useLayoutEffect } from 'react';
10
+ import { createContext, memo, useState, useCallback, useContext, useMemo, useRef, useEffect, useLayoutEffect } from 'react';
11
11
  import { SafeAreaView } from 'react-native-safe-area-context';
12
12
  import { encodeRecordKey, titleCase, useResourceForm, resourceKeys, useDataProvider, useCapabilities as useCapabilities$1, useViewer as useViewer$1, useResource as useResource$1, writeConflict, isDataWriteError, NO_ROWS_MATCHED, DataWriteError } from '@marktiderman/genesis-core';
13
- import { Controller, useForm } from 'react-hook-form';
14
- import { useRelationLabel, useResource, useViewer, useInfiniteResource, useCapabilities, useOptionalViewerScope, scopeClock, useOne, useLinkOptions } from '@marktiderman/genesis-core/hooks';
13
+ import { useFieldArray, useWatch, Controller, useForm } from 'react-hook-form';
14
+ import { useRelationLabel, useViewer, buildArrayItemDefaults, useWizard, useResource, useInfiniteResource, useCapabilities, useOptionalViewerScope, scopeClock, useOne, useLinkOptions } from '@marktiderman/genesis-core/hooks';
15
+ import { fieldArrayLimits, fieldArrayAddLabel, fieldAccept, formatFileSize, wizardStepFields, wizardProgressLabel, customViewStatus, fileProblem } from '@marktiderman/genesis-core/headless';
15
16
  import { personTimeZone, isTimeZone, wallClock } from '@marktiderman/genesis-core/dates';
16
17
  import { isSafeUrl } from '@marktiderman/genesis-core/urls';
17
- import { valueText, sameFormValue, rowPicture, filterParams as filterParams$1 } from '@marktiderman/genesis-core/resource-view';
18
+ import { valueText, sameFormValue, groupRows, rowPicture, filterParams as filterParams$1 } from '@marktiderman/genesis-core/resource-view';
18
19
  import { useQueryClient, useQuery } from '@tanstack/react-query';
19
20
  import { readinessChip } from '@marktiderman/genesis-core/resource';
20
21
 
@@ -231,6 +232,535 @@ function NativeDetailPanel({
231
232
  }
232
233
  ) });
233
234
  }
235
+
236
+ // src/data/resource-view/messages.ts
237
+ var defaultNativeResourceViewMessages = {
238
+ common: {
239
+ empty: "\u2014",
240
+ hiddenLink: "Not available",
241
+ yes: "Yes",
242
+ no: "No",
243
+ cancel: "Cancel",
244
+ save: "Save",
245
+ edit: "Edit",
246
+ close: "Close",
247
+ create: "New {noun}",
248
+ editTitle: "Edit {noun}",
249
+ search: "Search {nounPlural}"
250
+ },
251
+ delete: {
252
+ action: "Delete",
253
+ confirmTitle: "Delete \u201C{name}\u201D?",
254
+ confirmBody: "This can't be undone."
255
+ },
256
+ bin: {
257
+ action: "Move to Bin",
258
+ confirmTitle: "Move \u201C{name}\u201D to the bin?",
259
+ confirmBody: "You can restore it from the bin."
260
+ },
261
+ list: {
262
+ emptyTitle: "No {nounPlural} yet",
263
+ emptyBody: "When there are some, they show up here.",
264
+ noResultsTitle: "No results",
265
+ noResultsBody: "Try a different search.",
266
+ loadingMore: "Loading more",
267
+ loadFailed: "These {nounPlural} couldn't be loaded.",
268
+ retry: "Try again",
269
+ noGroup: "No {label}"
270
+ },
271
+ form: {
272
+ required: "{label} is required.",
273
+ tooLong: "{label} can be at most {max} characters.",
274
+ saveFailed: "This {noun} couldn't be saved. Try again.",
275
+ pickDate: "Add a date",
276
+ pickDateTime: "Add a date and time",
277
+ clear: "Clear {label}",
278
+ loading: "Loading"
279
+ },
280
+ link: {
281
+ placeholder: "Choose\u2026",
282
+ search: "Search",
283
+ none: "None",
284
+ noResults: "No matches",
285
+ loadMore: "Show more",
286
+ loadFailed: "Couldn't load the choices.",
287
+ untitled: "Untitled"
288
+ },
289
+ refusal: {
290
+ deleteFailed: "This {noun} couldn't be deleted. Try again.",
291
+ dismiss: "Dismiss"
292
+ }
293
+ };
294
+ function fill(template, values) {
295
+ return template.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
296
+ }
297
+ var isEmptyValue = (value) => value === null || value === void 0 || value === "";
298
+ var NUMBER = new Intl.NumberFormat();
299
+ var DECIMAL = new Intl.NumberFormat(void 0, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
300
+ var PERCENT = new Intl.NumberFormat(void 0, { style: "percent", maximumFractionDigits: 1 });
301
+ var DAY = new Intl.DateTimeFormat(void 0, { dateStyle: "medium" });
302
+ function numeric(value, format) {
303
+ const n = typeof value === "number" ? value : Number(value);
304
+ return Number.isFinite(n) ? format.format(n) : String(value);
305
+ }
306
+ var DAY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
307
+ function dayToDate(value) {
308
+ const day = typeof value === "string" ? DAY_PATTERN.exec(value) : null;
309
+ if (!day) return null;
310
+ return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
311
+ }
312
+ function dateToDay(date) {
313
+ const pad = (n) => String(n).padStart(2, "0");
314
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
315
+ }
316
+ function formatDay(value, zone = personTimeZone()) {
317
+ const date = dayToDate(value);
318
+ if (date) return DAY.format(date);
319
+ const text2 = String(value);
320
+ const at = /^\d{4}-\d{2}-\d{2}[T ]/.test(text2) ? new Date(text2) : null;
321
+ if (!at || Number.isNaN(at.getTime()) || !isTimeZone(zone)) return text2;
322
+ const wall = wallClock(zone, at);
323
+ return DAY.format(new Date(wall.year, wall.month - 1, wall.day));
324
+ }
325
+ function resolveZone(zone, zones) {
326
+ if (!zone || zone === "viewer") return zones.viewer;
327
+ if (zone === "scope") return zones.scope;
328
+ if (isTimeZone(zone)) return zone;
329
+ throw new RangeError(
330
+ zone === "practice" ? `[genesis-ui-native] timeZone "practice" was renamed "scope" in genesis-core 2; run \`genesis codemod genesis-core-2-scope-names\`` : `[genesis-ui-native] timeZone "${zone}" isn't "viewer", "scope" or a time zone this runtime knows`
331
+ );
332
+ }
333
+ var WALL = new Intl.DateTimeFormat(void 0, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
334
+ function formatInstant(value, zone) {
335
+ const at = new Date(String(value));
336
+ if (Number.isNaN(at.getTime()) || !isTimeZone(zone)) return String(value);
337
+ const wall = wallClock(zone, at);
338
+ return WALL.format(new Date(Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second)));
339
+ }
340
+ function openableUrl(value) {
341
+ if (!isSafeUrl(value)) return null;
342
+ const url = value.trim();
343
+ return /^(https?:|mailto:|tel:)/i.test(url) ? url : null;
344
+ }
345
+ function displayText(hint, value, messages, timeZone = personTimeZone()) {
346
+ if (isEmptyValue(value)) return messages.common.empty;
347
+ switch (hint) {
348
+ case "number":
349
+ return numeric(value, NUMBER);
350
+ case "currency":
351
+ return numeric(value, DECIMAL);
352
+ case "percent":
353
+ return numeric(value, PERCENT);
354
+ case "boolean":
355
+ return value === true || value === "true" ? messages.common.yes : messages.common.no;
356
+ case "badge":
357
+ return titleCase(String(value));
358
+ case "date":
359
+ return formatDay(value, timeZone);
360
+ case "datetime":
361
+ return formatInstant(value, timeZone);
362
+ case "url": {
363
+ const url = openableUrl(value);
364
+ return url ? url.replace(/^https?:\/\//i, "") : String(value);
365
+ }
366
+ case "json":
367
+ return typeof value === "string" ? value : JSON.stringify(value);
368
+ default:
369
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
370
+ }
371
+ }
372
+ var BADGE_VARIANT = {
373
+ success: "success",
374
+ warning: "warning",
375
+ danger: "destructive",
376
+ info: "info",
377
+ muted: "muted"
378
+ };
379
+ function badgeVariant(tone) {
380
+ return BADGE_VARIANT[tone ?? "muted"];
381
+ }
382
+ function LinkText({ url, label }) {
383
+ return /* @__PURE__ */ jsx(
384
+ Text,
385
+ {
386
+ accessibilityRole: "link",
387
+ className: "text-base text-primary-text underline",
388
+ onPress: () => void Linking.openURL(url),
389
+ children: label
390
+ }
391
+ );
392
+ }
393
+ var text = (hint) => (value, { messages, column, zones }) => /* @__PURE__ */ jsx(NativeText, { preset: "body", children: displayText(hint, value, messages, resolveZone(column.timeZone, zones)) });
394
+ function RelationText({ value, context }) {
395
+ const { column, messages } = context;
396
+ const reference = column.field?.references;
397
+ const label = useRelationLabel(reference, value, column.labelField ? { labelField: column.labelField } : {});
398
+ const shown = !reference ? String(value) : label === void 0 ? messages.common.empty : label ?? column.missingLabel ?? messages.common.hiddenLink ?? defaultNativeResourceViewMessages.common.hiddenLink;
399
+ return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: shown });
400
+ }
401
+ var nativeDisplayRenderers = {
402
+ text: text("text"),
403
+ longText: (value) => /* @__PURE__ */ jsx(NativeText, { preset: "body", numberOfLines: 3, children: String(value) }),
404
+ number: text("number"),
405
+ currency: text("currency"),
406
+ percent: text("percent"),
407
+ boolean: text("boolean"),
408
+ badge: (value, { column }) => /* @__PURE__ */ jsx(NativeBadge, { variant: badgeVariant(column.tones?.[String(value)]), children: valueText(column.labels, value) }),
409
+ date: text("date"),
410
+ datetime: text("datetime"),
411
+ // The linked row's words, batched across the list (one query per linked resource), else its id.
412
+ relation: (value, context) => /* @__PURE__ */ jsx(RelationText, { value, context }),
413
+ url: (value, { messages }) => {
414
+ const url = openableUrl(value);
415
+ return url && /^https?:/i.test(url) ? /* @__PURE__ */ jsx(LinkText, { url, label: displayText("url", value, messages) }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: String(value) });
416
+ },
417
+ email: (value) => {
418
+ const address = String(value).trim();
419
+ const url = /^[^\s@?&#/]+@[^\s@?&#/]+$/.test(address) ? openableUrl(`mailto:${address}`) : null;
420
+ return url ? /* @__PURE__ */ jsx(LinkText, { url, label: address }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: address });
421
+ },
422
+ image: (value) => {
423
+ const url = openableUrl(value);
424
+ return url && /^https?:/i.test(url) ? /* @__PURE__ */ jsx(NativeImage, { src: url, width: 64, height: 64, className: "rounded-md" }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: String(value) });
425
+ },
426
+ json: (value) => /* @__PURE__ */ jsx(NativeText, { preset: "caption", numberOfLines: 2, children: typeof value === "string" ? value : JSON.stringify(value) })
427
+ };
428
+ var DisplayRenderersContext = createContext(nativeDisplayRenderers);
429
+ var MessagesContext = createContext(defaultNativeResourceViewMessages);
430
+ var TimeZonesContext = createContext(null);
431
+ var DisplayTimeZonesProvider = TimeZonesContext.Provider;
432
+ function useDisplayTimeZones() {
433
+ const zones = useContext(TimeZonesContext);
434
+ return useMemo(() => zones ?? { viewer: personTimeZone(), scope: personTimeZone() }, [zones]);
435
+ }
436
+ function DisplayRenderersProvider({
437
+ renderers,
438
+ children
439
+ }) {
440
+ const parent = useContext(DisplayRenderersContext);
441
+ const value = useMemo(() => ({ ...parent, ...renderers }), [parent, renderers]);
442
+ return /* @__PURE__ */ jsx(DisplayRenderersContext.Provider, { value, children });
443
+ }
444
+ var NativeResourceViewMessagesProvider = MessagesContext.Provider;
445
+ function useNativeResourceViewMessages() {
446
+ return useContext(MessagesContext);
447
+ }
448
+ function useDisplayCell() {
449
+ const renderers = useContext(DisplayRenderersContext);
450
+ const messages = useNativeResourceViewMessages();
451
+ const zones = useDisplayTimeZones();
452
+ const viewer = useViewer();
453
+ return useMemo(
454
+ () => (column, row) => {
455
+ if (column.when && !column.when(row, viewer)) return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: messages.common.empty });
456
+ const value = column.value(row);
457
+ if (isEmptyValue(value)) return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: messages.common.empty });
458
+ return renderers[column.display](value, { row, column, messages, zones });
459
+ },
460
+ [renderers, messages, zones, viewer]
461
+ );
462
+ }
463
+ var SEARCH_DEBOUNCE_MS = 300;
464
+ function NativeLinkPicker({ field, value, onChange, values, error, testID }) {
465
+ const messages = useNativeResourceViewMessages();
466
+ const words = { ...defaultNativeResourceViewMessages.link, ...messages.link };
467
+ const link = field.link;
468
+ const viewer = useViewer();
469
+ const [open, setOpen] = useState(false);
470
+ const [query, setQuery] = useState("");
471
+ const [search, setSearch] = useState("");
472
+ useEffect(() => {
473
+ const timer = setTimeout(() => setSearch(query), SEARCH_DEBOUNCE_MS);
474
+ return () => clearTimeout(timer);
475
+ }, [query]);
476
+ const filtersKey = JSON.stringify(link.filters(viewer.scope, values));
477
+ const filters = useMemo(() => JSON.parse(filtersKey), [filtersKey]);
478
+ const labelField = field.labelField ?? link.labelField;
479
+ const list = useLinkOptions(
480
+ { resource: link.resource, field: link.field, labelField, searchFields: link.searchFields, orderBy: link.orderBy },
481
+ { filters, search, enabled: open, untitled: words.untitled }
482
+ );
483
+ const loaded = isEmptyValue(value) ? void 0 : list.options.find((o) => String(o.value) === String(value));
484
+ const looked = useRelationLabel({ resource: link.resource, field: link.field }, value, {
485
+ ...list.labelField ?? labelField ? { labelField: list.labelField ?? labelField } : {},
486
+ enabled: !isEmptyValue(value) && !loaded
487
+ });
488
+ const chosen = isEmptyValue(value) ? null : loaded?.label ?? (looked === void 0 ? void 0 : looked ?? field.missingLabel ?? messages.common.hiddenLink ?? defaultNativeResourceViewMessages.common.hiddenLink);
489
+ const shown = chosen === void 0 ? messages.common.empty : chosen ?? words.placeholder;
490
+ const pick = (next) => {
491
+ onChange(next);
492
+ setOpen(false);
493
+ setQuery("");
494
+ };
495
+ return /* @__PURE__ */ jsxs(View, { testID, style: { gap: 6 }, children: [
496
+ /* @__PURE__ */ jsx(NativeLabel, { children: field.label }),
497
+ /* @__PURE__ */ jsxs(
498
+ Pressable,
499
+ {
500
+ testID: `${testID}-trigger`,
501
+ accessibilityRole: "button",
502
+ accessibilityLabel: error ? `${field.label}, ${shown}, ${error}` : `${field.label}, ${shown}`,
503
+ accessibilityState: { expanded: open },
504
+ onPress: () => setOpen((was) => !was),
505
+ className: "min-h-[44px] flex-row items-center justify-between rounded-md border border-input bg-background px-3",
506
+ children: [
507
+ /* @__PURE__ */ jsx(Text, { className: chosen ? "text-base text-foreground" : "text-base text-muted-foreground", numberOfLines: 1, children: shown }),
508
+ /* @__PURE__ */ jsx(Text, { className: "text-muted-foreground", accessible: false, children: open ? "\u25B4" : "\u25BE" })
509
+ ]
510
+ }
511
+ ),
512
+ open ? /* @__PURE__ */ jsxs(View, { testID: `${testID}-list`, style: { gap: 4 }, accessibilityRole: "radiogroup", accessibilityLabel: field.label, children: [
513
+ list.searchable ? /* @__PURE__ */ jsx(
514
+ NativeSearchBar,
515
+ {
516
+ testID: `${testID}-search`,
517
+ value: query,
518
+ onChange: setQuery,
519
+ placeholder: words.search,
520
+ showCancel: false
521
+ }
522
+ ) : null,
523
+ !field.required && query === "" ? /* @__PURE__ */ jsx(
524
+ Option,
525
+ {
526
+ testID: `${testID}-none`,
527
+ label: words.none,
528
+ muted: true,
529
+ selected: isEmptyValue(value),
530
+ onPress: () => pick(null)
531
+ }
532
+ ) : null,
533
+ list.isLoading ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-muted-foreground", testID: `${testID}-loading`, children: messages.form.loading }) : list.isError ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-destructive", accessibilityRole: "alert", children: words.loadFailed }) : list.options.length === 0 ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-muted-foreground", testID: `${testID}-empty`, children: words.noResults }) : list.options.map((option) => /* @__PURE__ */ jsx(
534
+ Option,
535
+ {
536
+ testID: `${testID}-option-${String(option.value)}`,
537
+ label: option.label,
538
+ selected: !isEmptyValue(value) && String(value) === String(option.value),
539
+ onPress: () => pick(option.value)
540
+ },
541
+ String(option.value)
542
+ )),
543
+ list.hasMore ? /* @__PURE__ */ jsx(
544
+ NativeButton,
545
+ {
546
+ variant: "ghost",
547
+ size: "sm",
548
+ testID: `${testID}-more`,
549
+ disabled: list.isLoadingMore,
550
+ onPress: list.loadMore,
551
+ children: list.isLoadingMore ? messages.list.loadingMore : words.loadMore
552
+ }
553
+ ) : null
554
+ ] }) : null,
555
+ error ? (
556
+ // A live region on Android; the alert role on iOS and the web.
557
+ /* @__PURE__ */ jsx(View, { accessibilityLiveRegion: "polite", children: /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-destructive", testID: `${testID}-error`, accessibilityRole: "alert", children: error }) })
558
+ ) : null
559
+ ] });
560
+ }
561
+ function Option({
562
+ label,
563
+ selected,
564
+ muted = false,
565
+ onPress,
566
+ testID
567
+ }) {
568
+ return /* @__PURE__ */ jsxs(
569
+ Pressable,
570
+ {
571
+ testID,
572
+ accessibilityRole: "radio",
573
+ accessibilityLabel: label,
574
+ accessibilityState: { checked: selected },
575
+ onPress,
576
+ className: "min-h-[44px] flex-row items-center justify-between px-3",
577
+ children: [
578
+ /* @__PURE__ */ jsx(Text, { className: muted ? "text-base text-muted-foreground" : "text-base text-foreground", children: label }),
579
+ selected ? /* @__PURE__ */ jsx(Text, { className: "text-base text-primary-text", accessible: false, children: "\u2713" }) : null
580
+ ]
581
+ }
582
+ );
583
+ }
584
+ function NativeFieldArrayRenderer({ field, control, action, watchedValues, labels = {} }) {
585
+ const { fields: items, append, remove } = useFieldArray({ control, name: field.key });
586
+ const subFields = field.arrayFields ?? [];
587
+ const label = field.label ?? titleCase(field.key);
588
+ const { canAdd, canRemove } = fieldArrayLimits(items.length, field);
589
+ const fill2 = (template, n) => template.replace("{n}", String(n));
590
+ return /* @__PURE__ */ jsxs(View, { testID: `field-array-${field.key}`, className: "gap-2", children: [
591
+ /* @__PURE__ */ jsx(NativeLabel, { children: field.required ? `${label} *` : label }),
592
+ field.description ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: field.description }) : null,
593
+ items.map((item, index) => /* @__PURE__ */ jsxs(NativeCard, { className: "gap-3 p-4", testID: `field-array-${field.key}-${index}`, children: [
594
+ /* @__PURE__ */ jsxs(View, { className: "flex-row items-center justify-between", children: [
595
+ /* @__PURE__ */ jsx(Text, { className: "text-xs font-medium text-muted-foreground", children: fill2(labels.item ?? "Item {n}", index + 1) }),
596
+ /* @__PURE__ */ jsx(
597
+ NativeButton,
598
+ {
599
+ variant: "ghost",
600
+ size: "sm",
601
+ disabled: !canRemove,
602
+ onPress: () => remove(index),
603
+ accessibilityLabel: fill2(labels.remove ?? "Remove item {n}", index + 1),
604
+ testID: `field-array-${field.key}-${index}-remove`,
605
+ textClassName: "text-destructive",
606
+ children: labels.removeButton ?? "Remove"
607
+ }
608
+ )
609
+ ] }),
610
+ subFields.map((sub) => /* @__PURE__ */ jsx(
611
+ NativeResourceFormFieldRenderer,
612
+ {
613
+ field: { ...sub, key: `${field.key}.${index}.${sub.key}` },
614
+ control,
615
+ action,
616
+ watchedValues
617
+ },
618
+ sub.key
619
+ ))
620
+ ] }, item.id)),
621
+ /* @__PURE__ */ jsx(NativeButton, { variant: "outline", size: "sm", disabled: !canAdd, onPress: () => append(buildArrayItemDefaults(subFields)), testID: `field-array-${field.key}-add`, className: "self-start", children: labels.add ?? fieldArrayAddLabel(label, field.arrayItemLabel) })
622
+ ] });
623
+ }
624
+ function NativeFileUploadField({ field, value, onChange, disabled, pickFiles, labels = {}, error, testID = `file-upload-${field.key}` }) {
625
+ const { filePicker } = useGenesisModules();
626
+ const pick = pickFiles ?? filePicker;
627
+ const multiple = field.multiple ?? false;
628
+ const accept = fieldAccept(field);
629
+ const files = value ? Array.isArray(value) ? value : [value] : [];
630
+ const [problems, setProblems] = useState([]);
631
+ const picking = useRef(false);
632
+ const [busy, setBusy] = useState(false);
633
+ const label = field.label ?? titleCase(field.key);
634
+ const choose = async () => {
635
+ if (!pick || picking.current) return;
636
+ picking.current = true;
637
+ setBusy(true);
638
+ let picked;
639
+ try {
640
+ picked = await pick({ multiple, accept });
641
+ } catch {
642
+ setProblems([labels.pickFailed ?? "Couldn't open the picker. Check that the app may use your photos and files, then try again."]);
643
+ return;
644
+ } finally {
645
+ picking.current = false;
646
+ setBusy(false);
647
+ }
648
+ if (!picked.length) return;
649
+ const bad = picked.map((f) => fileProblem(f, { accept, maxSize: field.maxSize })).filter((p) => p !== null);
650
+ const good = picked.filter((f) => fileProblem(f, { accept, maxSize: field.maxSize }) === null);
651
+ setProblems(bad);
652
+ if (!good.length) return;
653
+ onChange(multiple ? [...files, ...good] : good[0]);
654
+ };
655
+ const removeAt = (index) => {
656
+ const next = files.filter((_, i) => i !== index);
657
+ onChange(next.length === 0 ? null : multiple ? next : next[0]);
658
+ };
659
+ return /* @__PURE__ */ jsxs(View, { testID, className: "gap-2", children: [
660
+ /* @__PURE__ */ jsx(NativeLabel, { children: field.required ? `${label} *` : label }),
661
+ files.map((file, i) => /* @__PURE__ */ jsxs(View, { testID: `${testID}-file-${i}`, className: "flex-row items-center gap-3 rounded-md border border-border p-2", children: [
662
+ file.type?.startsWith("image/") ? /* @__PURE__ */ jsx(NativeImage, { src: file.uri, width: 40, height: 40, className: "rounded" }) : null,
663
+ /* @__PURE__ */ jsxs(View, { className: "min-w-0 flex-1", children: [
664
+ /* @__PURE__ */ jsx(Text, { numberOfLines: 1, className: "text-sm text-foreground", children: file.name }),
665
+ file.size != null ? /* @__PURE__ */ jsx(Text, { className: "text-xs text-muted-foreground", children: formatFileSize(file.size) }) : null
666
+ ] }),
667
+ /* @__PURE__ */ jsx(
668
+ Pressable,
669
+ {
670
+ testID: `${testID}-remove-${i}`,
671
+ accessibilityRole: "button",
672
+ accessibilityLabel: `${labels.remove ?? "Remove"} ${file.name}`,
673
+ disabled,
674
+ onPress: () => removeAt(i),
675
+ hitSlop: 8,
676
+ className: "min-h-[44px] min-w-[44px] items-center justify-center",
677
+ children: /* @__PURE__ */ jsx(Text, { className: "text-base text-muted-foreground", children: "\u2715" })
678
+ }
679
+ )
680
+ ] }, `${file.uri}-${i}`)),
681
+ multiple || files.length === 0 ? /* @__PURE__ */ jsx(
682
+ NativeButton,
683
+ {
684
+ variant: "outline",
685
+ disabled: disabled || !pick || busy,
686
+ onPress: () => void choose(),
687
+ testID: `${testID}-choose`,
688
+ accessibilityHint: field.description,
689
+ className: "self-start",
690
+ children: files.length && multiple ? labels.chooseMore ?? "Add more" : labels.choose ?? (field.type === "image" ? "Choose a photo" : "Choose a file")
691
+ }
692
+ ) : null,
693
+ !pick ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: labels.noPicker ?? "No file picker is set up (GenesisModules.filePicker)." }) : null,
694
+ [...problems, ...error ? [error] : []].map((p) => /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-destructive", accessibilityRole: "alert", children: p }, p))
695
+ ] });
696
+ }
697
+ function NativeRelationField({ field, value, onChange, values = {}, error, testID = `relation-${field.key}` }) {
698
+ const relation = field.relation;
699
+ const label = field.label ?? titleCase(field.key);
700
+ const native = {
701
+ key: field.key,
702
+ label,
703
+ kind: "link",
704
+ display: "text",
705
+ required: field.required ?? false,
706
+ readOnly: false,
707
+ section: null,
708
+ sectionTitle: null,
709
+ ...relation.missingLabel ? { missingLabel: relation.missingLabel } : {},
710
+ link: {
711
+ resource: relation.resource,
712
+ field: relation.valueField ?? "id",
713
+ labelField: relation.labelField,
714
+ ...relation.searchFields ? { searchFields: relation.searchFields } : {},
715
+ ...relation.orderBy ? { orderBy: { field: relation.orderBy.field, direction: relation.orderBy.direction ?? "asc", nulls: relation.orderBy.nulls } } : {},
716
+ filters: (_scope, formValues) => {
717
+ const f = relation.filters;
718
+ return typeof f === "function" ? f(formValues ?? {}) : f ?? [];
719
+ }
720
+ }
721
+ };
722
+ return /* @__PURE__ */ jsx(
723
+ NativeLinkPicker,
724
+ {
725
+ field: native,
726
+ value,
727
+ values,
728
+ error,
729
+ testID,
730
+ onChange: (next) => onChange(relation.keys === "row" ? next : next === null ? "" : String(next))
731
+ }
732
+ );
733
+ }
734
+ function NativeWizardForm({ steps, form, fields, onSubmit, isSaving, action, onInvalid, renderField, labels = {}, testID = "wizard-form" }) {
735
+ const wizard = useWizard(steps, form);
736
+ const watched = useWatch({ control: form.control });
737
+ const stepFields = wizardStepFields(fields, wizard.currentStepDef.fields, watched);
738
+ const progress = wizardProgressLabel(wizard);
739
+ const next = async () => {
740
+ if (wizard.isLast) await form.handleSubmit(onSubmit, onInvalid)();
741
+ else await wizard.next();
742
+ };
743
+ return /* @__PURE__ */ jsxs(View, { testID, className: "gap-6", children: [
744
+ /* @__PURE__ */ jsxs(View, { className: "gap-2", children: [
745
+ /* @__PURE__ */ jsxs(View, { className: "flex-row items-center justify-between", children: [
746
+ /* @__PURE__ */ jsx(Text, { className: "text-sm text-muted-foreground", children: progress.step }),
747
+ /* @__PURE__ */ jsx(Text, { className: "text-sm text-muted-foreground", children: progress.percent })
748
+ ] }),
749
+ /* @__PURE__ */ jsx(NativeProgress, { value: wizard.progress * 100, testID: `${testID}-progress` })
750
+ ] }),
751
+ /* @__PURE__ */ jsxs(View, { className: "gap-1", children: [
752
+ /* @__PURE__ */ jsx(Text, { accessibilityRole: "header", className: "text-lg font-semibold text-foreground", children: wizard.currentStepDef.title }),
753
+ wizard.currentStepDef.description ? /* @__PURE__ */ jsx(Text, { className: "text-sm text-muted-foreground", children: wizard.currentStepDef.description }) : null
754
+ ] }),
755
+ /* @__PURE__ */ jsx(View, { className: "gap-4", children: stepFields.map(
756
+ (f) => renderField ? /* @__PURE__ */ jsx(View, { children: renderField(f, form.control, action, watched) }, f.key) : /* @__PURE__ */ jsx(NativeResourceFormFieldRenderer, { field: f, control: form.control, action, watchedValues: watched }, f.key)
757
+ ) }, wizard.currentStep),
758
+ /* @__PURE__ */ jsxs(View, { className: "flex-row justify-between pt-2", children: [
759
+ /* @__PURE__ */ jsx(NativeButton, { variant: "outline", onPress: wizard.back, disabled: wizard.isFirst || isSaving, testID: `${testID}-back`, children: labels.back ?? "Back" }),
760
+ /* @__PURE__ */ jsx(NativeButton, { onPress: () => void next(), disabled: isSaving, loading: isSaving, testID: `${testID}-next`, children: wizard.isLast ? action === "create" ? labels.create ?? "Create" : labels.save ?? "Save" : labels.next ?? "Next" })
761
+ ] })
762
+ ] });
763
+ }
234
764
  var KEYBOARD_TYPE_MAP = {
235
765
  email: "email-address",
236
766
  url: "url",
@@ -259,6 +789,9 @@ function NativeResourceFormFieldRenderer({
259
789
  if (field.hidden || fieldType === "hidden") {
260
790
  return null;
261
791
  }
792
+ if (fieldType === "array" && field.arrayFields) {
793
+ return /* @__PURE__ */ jsx(NativeFieldArrayRenderer, { field, control, action, watchedValues });
794
+ }
262
795
  return /* @__PURE__ */ jsx(
263
796
  Controller,
264
797
  {
@@ -266,6 +799,30 @@ function NativeResourceFormFieldRenderer({
266
799
  control,
267
800
  render: ({ field: f, fieldState }) => {
268
801
  const errorMessage = fieldState.error?.message;
802
+ if (fieldType === "relation" && field.relation) {
803
+ return /* @__PURE__ */ jsx(
804
+ NativeRelationField,
805
+ {
806
+ field,
807
+ value: f.value,
808
+ onChange: f.onChange,
809
+ values: watchedValues ?? {},
810
+ ...errorMessage ? { error: errorMessage } : {}
811
+ }
812
+ );
813
+ }
814
+ if (fieldType === "file" || fieldType === "image") {
815
+ return /* @__PURE__ */ jsx(
816
+ NativeFileUploadField,
817
+ {
818
+ field,
819
+ value: f.value ?? null,
820
+ onChange: f.onChange,
821
+ disabled: isDisabled,
822
+ ...errorMessage ? { error: errorMessage } : {}
823
+ }
824
+ );
825
+ }
269
826
  if (fieldType === "switch") {
270
827
  return /* @__PURE__ */ jsxs(View, { className: "gap-1.5", children: [
271
828
  /* @__PURE__ */ jsxs(
@@ -478,665 +1035,437 @@ function NativeConflictSheet({
478
1035
  onOpenChange: (open) => !open && !keeping && onDismiss(),
479
1036
  fitContent: true,
480
1037
  testID,
481
- children: /* @__PURE__ */ jsx(NativeSheetScrollView, { children: /* @__PURE__ */ jsxs(View, { style: { gap: 12, paddingHorizontal: 16, paddingVertical: 12 }, children: [
482
- /* @__PURE__ */ jsx(NativeText, { preset: "h4", accessibilityRole: "header", children: title }),
483
- /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground", children: fields.length > 0 ? w.description : w.same }),
484
- conflict ? fields.map((field) => /* @__PURE__ */ jsxs(View, { style: { gap: 4 }, testID: `${testID}-field-${field}`, children: [
485
- /* @__PURE__ */ jsx(NativeText, { preset: "label", children: label(field) }),
486
- /* @__PURE__ */ jsxs(View, { accessible: true, ...format ? {} : { accessibilityLabel: `${w.theirs}: ${text2(field, conflict.theirs[field], has(field))}` }, children: [
487
- /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: w.theirs }),
488
- show(field, conflict.theirs[field], has(field))
489
- ] }),
490
- /* @__PURE__ */ jsxs(View, { accessible: true, ...format ? {} : { accessibilityLabel: `${w.mine}: ${text2(field, conflict.mine[field])}` }, children: [
491
- /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: w.mine }),
492
- show(field, conflict.mine[field])
493
- ] })
494
- ] }, field)) : null,
495
- failed ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-destructive", accessibilityRole: "alert", testID: `${testID}-failed`, children: failed }) : null,
496
- /* @__PURE__ */ jsxs(View, { style: { gap: 8, paddingTop: 4 }, children: [
497
- canKeep ? /* @__PURE__ */ jsx(NativeButton, { size: "lg", onPress: () => void keep(), loading: keeping, disabled: keeping, testID: `${testID}-keep-mine`, children: w.keepMine }) : null,
498
- /* @__PURE__ */ jsx(NativeButton, { size: "lg", variant: "outline", onPress: onTakeTheirs, disabled: keeping, testID: `${testID}-take-theirs`, children: w.takeTheirs })
499
- ] })
500
- ] }) })
501
- }
502
- );
503
- }
504
- function NativeResourceForm({
505
- resource,
506
- action,
507
- fields,
508
- item,
509
- listData,
510
- title,
511
- layout = "screen",
512
- onSuccess,
513
- onError,
514
- renderForm
515
- }) {
516
- const options = {
517
- resource,
518
- action,
519
- initialData: item,
520
- fields,
521
- listData,
522
- onSuccess,
523
- onError,
524
- prefillFromUrl: false,
525
- validationMode: "onSubmit"
526
- };
527
- const { form, resolvedFields, onSubmit, isSaving, conflict, keepMine, takeTheirs, dismissConflict } = useResourceForm(options);
528
- const conflictSheet = /* @__PURE__ */ jsx(
529
- NativeConflictSheet,
530
- {
531
- conflict,
532
- label: (field) => resolvedFields.find((f) => f.key === field)?.label ?? titleCase(field),
533
- onKeepMine: keepMine,
534
- onTakeTheirs: takeTheirs,
535
- onDismiss: dismissConflict,
536
- testID: "native-resource-form-conflict"
537
- }
538
- );
539
- const resolvedTitle = title ?? (action === "create" ? `Create ${titleCase(resource)}` : `Edit ${titleCase(resource)}`);
540
- const submitLabel = action === "create" ? "Create" : "Save";
541
- const values = form.watch();
542
- const rootError = form.formState.errors.root?.message;
543
- const { groups, firstFieldKey } = React.useMemo(() => {
544
- const visible = resolvedFields.filter(
545
- (field) => field.visible == null || field.visible(values) !== false
546
- );
547
- const result = [];
548
- for (const field of visible) {
549
- const lastGroup = result[result.length - 1];
550
- if (lastGroup && lastGroup.group === field.group) {
551
- lastGroup.fields.push(field);
552
- } else {
553
- result.push({ group: field.group, fields: [field] });
554
- }
555
- }
556
- const first = visible.find((f) => !f.hidden && f.type !== "hidden");
557
- return { groups: result, firstFieldKey: first?.key ?? null };
558
- }, [resolvedFields, values]);
559
- const formContent = renderForm ? renderForm(form, resolvedFields) : /* @__PURE__ */ jsxs(View, { style: { gap: 16 }, children: [
560
- rootError ? /* @__PURE__ */ jsxs(NativeAlert, { variant: "destructive", children: [
561
- /* @__PURE__ */ jsx(NativeAlertTitle, { variant: "destructive", children: "Error" }),
562
- /* @__PURE__ */ jsx(NativeAlertDescription, { variant: "destructive", children: rootError })
563
- ] }) : null,
564
- groups.map((group, groupIndex) => /* @__PURE__ */ jsxs(View, { style: { gap: 12 }, children: [
565
- group.group ? /* @__PURE__ */ jsxs(View, { style: { gap: 8 }, children: [
566
- groupIndex > 0 ? /* @__PURE__ */ jsx(NativeSeparator, {}) : null,
567
- /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground", children: group.group })
568
- ] }) : groupIndex > 0 ? /* @__PURE__ */ jsx(NativeSeparator, {}) : null,
569
- group.fields.map((field) => /* @__PURE__ */ jsx(
570
- NativeResourceFormFieldRenderer,
571
- {
572
- field,
573
- control: form.control,
574
- action,
575
- autoFocus: field.key === firstFieldKey,
576
- watchedValues: values
577
- },
578
- field.key
579
- ))
580
- ] }, group.group ?? `__ungrouped_${groupIndex}`)),
581
- /* @__PURE__ */ jsx(NativeButton, { onPress: onSubmit, disabled: isSaving, loading: isSaving, children: isSaving ? "Saving..." : submitLabel })
582
- ] });
583
- if (layout === "inline") {
584
- return /* @__PURE__ */ jsxs(View, { style: { gap: 16 }, children: [
585
- /* @__PURE__ */ jsx(NativeText, { preset: "h3", children: resolvedTitle }),
586
- formContent,
587
- conflictSheet
588
- ] });
589
- }
590
- return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["bottom"], style: { flex: 1 }, children: [
591
- /* @__PURE__ */ jsxs(
592
- ScrollView,
593
- {
594
- contentContainerStyle: { padding: 16, gap: 16 },
595
- showsVerticalScrollIndicator: false,
596
- children: [
597
- /* @__PURE__ */ jsx(NativeText, { preset: "h3", children: resolvedTitle }),
598
- formContent
599
- ]
600
- }
601
- ),
602
- conflictSheet
603
- ] });
604
- }
605
- function resolveField(f, index) {
606
- if (typeof f === "string") {
607
- return {
608
- key: f,
609
- position: index === 0 ? "title" : "meta"
610
- };
611
- }
612
- return f;
613
- }
614
- function autoDetectFields(item) {
615
- const keys = Object.keys(item).filter((k) => k !== "id");
616
- return keys.map((key, i) => ({
617
- key,
618
- position: i === 0 ? "title" : "meta"
619
- }));
620
- }
621
- function DefaultCardRenderer({
622
- item,
623
- fields,
624
- onPress
625
- }) {
626
- const titleField = fields.find((f) => f.position === "title");
627
- const badgeField = fields.find((f) => f.position === "badge");
628
- const subtitleField = fields.find((f) => f.position === "subtitle");
629
- const metaFields = fields.filter((f) => f.position === "meta");
630
- const renderValue = (field) => {
631
- const value = item[field.key];
632
- if (field.render) {
633
- return field.render(value, item);
634
- }
635
- if (value === null || value === void 0) return null;
636
- return String(value);
637
- };
638
- const titleContent = titleField ? renderValue(titleField) : null;
639
- const badgeContent = badgeField ? renderValue(badgeField) : null;
640
- const subtitleContent = subtitleField ? renderValue(subtitleField) : null;
641
- return /* @__PURE__ */ jsx(
642
- Pressable,
643
- {
644
- onPress: onPress ? () => onPress(item) : void 0,
645
- style: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 }),
646
- children: /* @__PURE__ */ jsxs(NativeCard, { className: "mx-4 mb-3", children: [
647
- /* @__PURE__ */ jsxs(NativeCardHeader, { className: "pb-2", children: [
648
- /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" }, children: [
649
- titleContent !== null ? /* @__PURE__ */ jsx(NativeCardTitle, { className: "flex-1 text-base", children: titleContent }) : null,
650
- badgeContent !== null ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground ml-2", children: badgeContent }) : null
1038
+ children: /* @__PURE__ */ jsx(NativeSheetScrollView, { children: /* @__PURE__ */ jsxs(View, { style: { gap: 12, paddingHorizontal: 16, paddingVertical: 12 }, children: [
1039
+ /* @__PURE__ */ jsx(NativeText, { preset: "h4", accessibilityRole: "header", children: title }),
1040
+ /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground", children: fields.length > 0 ? w.description : w.same }),
1041
+ conflict ? fields.map((field) => /* @__PURE__ */ jsxs(View, { style: { gap: 4 }, testID: `${testID}-field-${field}`, children: [
1042
+ /* @__PURE__ */ jsx(NativeText, { preset: "label", children: label(field) }),
1043
+ /* @__PURE__ */ jsxs(View, { accessible: true, ...format ? {} : { accessibilityLabel: `${w.theirs}: ${text2(field, conflict.theirs[field], has(field))}` }, children: [
1044
+ /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: w.theirs }),
1045
+ show(field, conflict.theirs[field], has(field))
651
1046
  ] }),
652
- subtitleContent !== null ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground mt-0.5", children: subtitleContent }) : null
653
- ] }),
654
- metaFields.length > 0 ? /* @__PURE__ */ jsx(NativeCardContent, { className: "pt-0", children: /* @__PURE__ */ jsx(View, { style: { flexDirection: "row", flexWrap: "wrap", gap: 8 }, children: metaFields.map((field) => {
655
- const val = renderValue(field);
656
- if (val === null) return null;
657
- return /* @__PURE__ */ jsxs(NativeText, { preset: "caption", className: "text-muted-foreground", children: [
658
- field.label ? `${field.label}: ` : "",
659
- val
660
- ] }, field.key);
661
- }) }) }) : null
662
- ] })
1047
+ /* @__PURE__ */ jsxs(View, { accessible: true, ...format ? {} : { accessibilityLabel: `${w.mine}: ${text2(field, conflict.mine[field])}` }, children: [
1048
+ /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-muted-foreground", children: w.mine }),
1049
+ show(field, conflict.mine[field])
1050
+ ] })
1051
+ ] }, field)) : null,
1052
+ failed ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-destructive", accessibilityRole: "alert", testID: `${testID}-failed`, children: failed }) : null,
1053
+ /* @__PURE__ */ jsxs(View, { style: { gap: 8, paddingTop: 4 }, children: [
1054
+ canKeep ? /* @__PURE__ */ jsx(NativeButton, { size: "lg", onPress: () => void keep(), loading: keeping, disabled: keeping, testID: `${testID}-keep-mine`, children: w.keepMine }) : null,
1055
+ /* @__PURE__ */ jsx(NativeButton, { size: "lg", variant: "outline", onPress: onTakeTheirs, disabled: keeping, testID: `${testID}-take-theirs`, children: w.takeTheirs })
1056
+ ] })
1057
+ ] }) })
663
1058
  }
664
1059
  );
665
1060
  }
666
- function NativeResourcePage({
1061
+ function NativeResourceForm({
667
1062
  resource,
668
- resourceOptions,
1063
+ action,
1064
+ fields,
1065
+ item,
1066
+ listData,
669
1067
  title,
670
- subtitle,
671
- cardFields,
672
- renderItem,
673
- searchFields,
674
- searchPlaceholder,
675
- statusFilter,
676
- onItemPress,
677
- titleField,
678
- onCreatePress,
679
- createLabel = "New",
680
- headerRight,
681
- emptyState,
682
- offlineState
1068
+ layout = "screen",
1069
+ onSuccess,
1070
+ onError,
1071
+ renderForm
683
1072
  }) {
684
- const { list: FlashList } = useGenesisModules();
685
- const [search, setSearchLocal] = useState("");
686
- const [selectedStatuses, setSelectedStatuses] = useState([]);
687
- const statusFilterConfig = useMemo(() => {
688
- if (!statusFilter) return null;
689
- if (typeof statusFilter === "string") {
690
- return { field: statusFilter, options: void 0 };
691
- }
692
- return { field: statusFilter.field, options: statusFilter.options };
693
- }, [statusFilter]);
694
- const mergedOptions = useMemo(
695
- () => ({
696
- ...resourceOptions,
697
- searchFields: searchFields ?? resourceOptions?.searchFields
698
- }),
699
- // eslint-disable-next-line react-hooks/exhaustive-deps
700
- [resourceOptions, searchFields]
701
- );
702
- const { list, setSearch, setFilters } = useResource(resource, mergedOptions);
703
- useEffect(() => {
704
- setSearch(search);
705
- }, [search, setSearch]);
706
- useEffect(() => {
707
- if (!statusFilterConfig) return;
708
- if (selectedStatuses.length === 0) {
709
- setFilters([]);
710
- } else if (selectedStatuses.length === 1) {
711
- setFilters([
712
- {
713
- field: statusFilterConfig.field,
714
- operator: "eq",
715
- value: selectedStatuses[0]
716
- }
717
- ]);
718
- } else {
719
- setFilters([
720
- {
721
- field: statusFilterConfig.field,
722
- operator: "in",
723
- value: selectedStatuses
724
- }
725
- ]);
726
- }
727
- }, [selectedStatuses, statusFilterConfig, setFilters]);
728
- const items = list.data?.data ?? [];
729
- const isLoading = list.isLoading;
730
- const hasError = list.isError;
731
- const isOfflineEmpty = list.isPaused && list.data === void 0;
732
- const resolvedFields = useMemo(() => {
733
- if (titleField && cardFields) {
734
- const resolved = cardFields.map((f, i) => resolveField(f, i));
735
- return resolved.map(
736
- (f) => f.key === titleField ? { ...f, position: "title" } : f
737
- );
738
- }
739
- if (cardFields && cardFields.length > 0) {
740
- return cardFields.map((f, i) => resolveField(f, i));
741
- }
742
- if (items.length > 0) {
743
- const detected = autoDetectFields(items[0]);
744
- if (titleField) {
745
- return detected.map(
746
- (f) => f.key === titleField ? { ...f, position: "title" } : f
747
- );
748
- }
749
- return detected;
750
- }
751
- return [];
752
- }, [cardFields, titleField, items]);
753
- const statusOptions = useMemo(() => {
754
- if (!statusFilterConfig) return [];
755
- if (statusFilterConfig.options) return statusFilterConfig.options;
756
- const values = /* @__PURE__ */ new Set();
757
- for (const item of items) {
758
- const v = item[statusFilterConfig.field];
759
- if (typeof v === "string") values.add(v);
760
- }
761
- return Array.from(values).sort();
762
- }, [statusFilterConfig, items]);
763
- const effectiveHeaderRight = useMemo(() => {
764
- if (onCreatePress) {
765
- return /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", alignItems: "center", gap: 8 }, children: [
766
- headerRight,
767
- /* @__PURE__ */ jsx(NativeButton, { size: "sm", onPress: onCreatePress, children: createLabel })
768
- ] });
769
- }
770
- return headerRight ?? null;
771
- }, [onCreatePress, createLabel, headerRight]);
772
- const [refreshing, setRefreshing] = useState(false);
773
- const refetch = list.refetch;
774
- const handleRefresh = useCallback(async () => {
775
- setRefreshing(true);
776
- try {
777
- await refetch();
778
- } catch (err) {
779
- console.error(`[NativeResourcePage] Pull-to-refresh failed:`, err);
780
- } finally {
781
- setRefreshing(false);
1073
+ const options = {
1074
+ resource,
1075
+ action,
1076
+ initialData: item,
1077
+ fields,
1078
+ listData,
1079
+ onSuccess,
1080
+ onError,
1081
+ prefillFromUrl: false,
1082
+ validationMode: "onSubmit"
1083
+ };
1084
+ const { form, resolvedFields, onSubmit, isSaving, conflict, keepMine, takeTheirs, dismissConflict } = useResourceForm(options);
1085
+ const conflictSheet = /* @__PURE__ */ jsx(
1086
+ NativeConflictSheet,
1087
+ {
1088
+ conflict,
1089
+ label: (field) => resolvedFields.find((f) => f.key === field)?.label ?? titleCase(field),
1090
+ onKeepMine: keepMine,
1091
+ onTakeTheirs: takeTheirs,
1092
+ onDismiss: dismissConflict,
1093
+ testID: "native-resource-form-conflict"
782
1094
  }
783
- }, [refetch]);
784
- const hasActiveFilters = search.length > 0 || selectedStatuses.length > 0;
785
- const handleClearFilters = useCallback(() => {
786
- setSearchLocal("");
787
- setSelectedStatuses([]);
788
- }, []);
789
- const keyExtractor = useCallback(
790
- (item) => String(item.id),
791
- []
792
- );
793
- const renderFlatListItem = useCallback(
794
- ({ item }) => {
795
- if (renderItem) {
796
- return /* @__PURE__ */ jsx(Fragment, { children: renderItem(item) });
797
- }
798
- return /* @__PURE__ */ jsx(
799
- DefaultCardRenderer,
800
- {
801
- item,
802
- fields: resolvedFields,
803
- onPress: onItemPress
804
- }
805
- );
806
- },
807
- [renderItem, resolvedFields, onItemPress]
808
- );
809
- const ListHeaderComponent = useMemo(
810
- () => /* @__PURE__ */ jsx(View, { className: "px-4 pb-3", children: /* @__PURE__ */ jsx(
811
- NativeDataFilters,
812
- {
813
- search,
814
- onSearchChange: setSearchLocal,
815
- searchPlaceholder,
816
- statusChips: statusOptions.length > 0 ? {
817
- options: statusOptions,
818
- selected: selectedStatuses,
819
- onChange: setSelectedStatuses
820
- } : void 0
821
- }
822
- ) }),
823
- [search, searchPlaceholder, statusOptions, selectedStatuses]
824
1095
  );
825
- const ListEmptyComponent = useMemo(
826
- () => isLoading ? null : isOfflineEmpty ? (
827
- // In the list, under its header, so search and filters stay usable offline: clearing a
828
- // search brings back the saved rows.
829
- /* @__PURE__ */ jsx(View, { testID: "native-resource-offline", className: "flex-1 items-center justify-center px-4 py-12 gap-4", children: offlineState ?? /* @__PURE__ */ jsx(NativeText, { preset: "body", className: "text-muted-foreground text-center", children: "You're offline. This list loads when you're back online." }) })
830
- ) : /* @__PURE__ */ jsx(Fragment, { children: emptyState ?? /* @__PURE__ */ jsx(
831
- NativeEmptyState2,
832
- {
833
- hasFilters: hasActiveFilters,
834
- onClearFilters: hasActiveFilters ? handleClearFilters : void 0
1096
+ const resolvedTitle = title ?? (action === "create" ? `Create ${titleCase(resource)}` : `Edit ${titleCase(resource)}`);
1097
+ const submitLabel = action === "create" ? "Create" : "Save";
1098
+ const values = form.watch();
1099
+ const rootError = form.formState.errors.root?.message;
1100
+ const { groups, firstFieldKey } = React.useMemo(() => {
1101
+ const visible = resolvedFields.filter(
1102
+ (field) => field.visible == null || field.visible(values) !== false
1103
+ );
1104
+ const result = [];
1105
+ for (const field of visible) {
1106
+ const lastGroup = result[result.length - 1];
1107
+ if (lastGroup && lastGroup.group === field.group) {
1108
+ lastGroup.fields.push(field);
1109
+ } else {
1110
+ result.push({ group: field.group, fields: [field] });
835
1111
  }
836
- ) }),
837
- [isLoading, isOfflineEmpty, offlineState, emptyState, hasActiveFilters, handleClearFilters]
838
- );
839
- const renderPageContent = () => {
840
- if (isLoading) {
841
- return /* @__PURE__ */ jsxs(View, { className: "px-4 pt-4 gap-3", children: [
842
- /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-10 rounded-lg" }),
843
- /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" }),
844
- /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" }),
845
- /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" })
846
- ] });
847
- }
848
- if (hasError) {
849
- return /* @__PURE__ */ jsxs(View, { className: "flex-1 items-center justify-center px-4 py-12 gap-4", children: [
850
- /* @__PURE__ */ jsx(NativeText, { preset: "body", className: "text-destructive text-center", children: list.error?.message ?? "Something went wrong." }),
851
- /* @__PURE__ */ jsx(NativeButton, { variant: "outline", size: "sm", onPress: () => list.refetch(), children: "Try Again" })
852
- ] });
853
1112
  }
854
- if (FlashList) {
855
- return /* @__PURE__ */ jsx(
856
- FlashList,
1113
+ const first = visible.find((f) => !f.hidden && f.type !== "hidden");
1114
+ return { groups: result, firstFieldKey: first?.key ?? null };
1115
+ }, [resolvedFields, values]);
1116
+ const formContent = renderForm ? renderForm(form, resolvedFields) : /* @__PURE__ */ jsxs(View, { style: { gap: 16 }, children: [
1117
+ rootError ? /* @__PURE__ */ jsxs(NativeAlert, { variant: "destructive", children: [
1118
+ /* @__PURE__ */ jsx(NativeAlertTitle, { variant: "destructive", children: "Error" }),
1119
+ /* @__PURE__ */ jsx(NativeAlertDescription, { variant: "destructive", children: rootError })
1120
+ ] }) : null,
1121
+ groups.map((group, groupIndex) => /* @__PURE__ */ jsxs(View, { style: { gap: 12 }, children: [
1122
+ group.group ? /* @__PURE__ */ jsxs(View, { style: { gap: 8 }, children: [
1123
+ groupIndex > 0 ? /* @__PURE__ */ jsx(NativeSeparator, {}) : null,
1124
+ /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground", children: group.group })
1125
+ ] }) : groupIndex > 0 ? /* @__PURE__ */ jsx(NativeSeparator, {}) : null,
1126
+ group.fields.map((field) => /* @__PURE__ */ jsx(
1127
+ NativeResourceFormFieldRenderer,
857
1128
  {
858
- testID: "native-resource-page-list",
859
- data: items,
860
- keyExtractor,
861
- renderItem: renderFlatListItem,
862
- ListHeaderComponent,
863
- ListEmptyComponent,
864
- contentContainerStyle: { paddingBottom: 24 },
865
- refreshing: refreshing && !list.isPaused,
866
- onRefresh: handleRefresh
867
- }
868
- );
869
- }
870
- return /* @__PURE__ */ jsx(
871
- FlatList,
872
- {
873
- testID: "native-resource-page-list",
874
- data: items,
875
- keyExtractor,
876
- renderItem: renderFlatListItem,
877
- ListHeaderComponent,
878
- ListEmptyComponent,
879
- contentContainerStyle: { flexGrow: 1, paddingBottom: 24 },
880
- refreshing: refreshing && !list.isPaused,
881
- onRefresh: handleRefresh
882
- }
883
- );
884
- };
885
- return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["left", "right"], className: "flex-1 bg-background", children: [
886
- /* @__PURE__ */ jsx(View, { className: "px-4 pt-4 pb-2", children: /* @__PURE__ */ jsxs(
887
- View,
888
- {
889
- style: {
890
- flexDirection: "row",
891
- alignItems: "center",
892
- justifyContent: "space-between"
1129
+ field,
1130
+ control: form.control,
1131
+ action,
1132
+ autoFocus: field.key === firstFieldKey,
1133
+ watchedValues: values
893
1134
  },
1135
+ field.key
1136
+ ))
1137
+ ] }, group.group ?? `__ungrouped_${groupIndex}`)),
1138
+ /* @__PURE__ */ jsx(NativeButton, { onPress: onSubmit, disabled: isSaving, loading: isSaving, children: isSaving ? "Saving..." : submitLabel })
1139
+ ] });
1140
+ if (layout === "inline") {
1141
+ return /* @__PURE__ */ jsxs(View, { style: { gap: 16 }, children: [
1142
+ /* @__PURE__ */ jsx(NativeText, { preset: "h3", children: resolvedTitle }),
1143
+ formContent,
1144
+ conflictSheet
1145
+ ] });
1146
+ }
1147
+ return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["bottom"], style: { flex: 1 }, children: [
1148
+ /* @__PURE__ */ jsxs(
1149
+ ScrollView,
1150
+ {
1151
+ contentContainerStyle: { padding: 16, gap: 16 },
1152
+ showsVerticalScrollIndicator: false,
894
1153
  children: [
895
- /* @__PURE__ */ jsxs(View, { className: "flex-1", children: [
896
- /* @__PURE__ */ jsx(NativeText, { preset: "h2", children: title }),
897
- subtitle ? /* @__PURE__ */ jsx(
898
- NativeText,
899
- {
900
- preset: "body-sm",
901
- className: "text-muted-foreground mt-0.5",
902
- children: subtitle
903
- }
904
- ) : null
905
- ] }),
906
- effectiveHeaderRight ? /* @__PURE__ */ jsx(View, { className: "ml-3", children: effectiveHeaderRight }) : null
1154
+ /* @__PURE__ */ jsx(NativeText, { preset: "h3", children: resolvedTitle }),
1155
+ formContent
907
1156
  ]
908
1157
  }
909
- ) }),
910
- /* @__PURE__ */ jsx(View, { className: "flex-1", children: renderPageContent() })
1158
+ ),
1159
+ conflictSheet
911
1160
  ] });
912
1161
  }
913
-
914
- // src/data/resource-view/messages.ts
915
- var defaultNativeResourceViewMessages = {
916
- common: {
917
- empty: "\u2014",
918
- hiddenLink: "Not available",
919
- yes: "Yes",
920
- no: "No",
921
- cancel: "Cancel",
922
- save: "Save",
923
- edit: "Edit",
924
- close: "Close",
925
- create: "New {noun}",
926
- editTitle: "Edit {noun}",
927
- search: "Search {nounPlural}"
928
- },
929
- delete: {
930
- action: "Delete",
931
- confirmTitle: "Delete \u201C{name}\u201D?",
932
- confirmBody: "This can't be undone."
933
- },
934
- bin: {
935
- action: "Move to Bin",
936
- confirmTitle: "Move \u201C{name}\u201D to the bin?",
937
- confirmBody: "You can restore it from the bin."
938
- },
939
- list: {
940
- emptyTitle: "No {nounPlural} yet",
941
- emptyBody: "When there are some, they show up here.",
942
- noResultsTitle: "No results",
943
- noResultsBody: "Try a different search.",
944
- loadingMore: "Loading more",
945
- loadFailed: "These {nounPlural} couldn't be loaded.",
946
- retry: "Try again",
947
- noGroup: "No {label}"
948
- },
949
- form: {
950
- required: "{label} is required.",
951
- tooLong: "{label} can be at most {max} characters.",
952
- saveFailed: "This {noun} couldn't be saved. Try again.",
953
- pickDate: "Add a date",
954
- pickDateTime: "Add a date and time",
955
- clear: "Clear {label}",
956
- loading: "Loading"
957
- },
958
- link: {
959
- placeholder: "Choose\u2026",
960
- search: "Search",
961
- none: "None",
962
- noResults: "No matches",
963
- loadMore: "Show more",
964
- loadFailed: "Couldn't load the choices.",
965
- untitled: "Untitled"
966
- },
967
- refusal: {
968
- deleteFailed: "This {noun} couldn't be deleted. Try again.",
969
- dismiss: "Dismiss"
970
- }
971
- };
972
- function fill(template, values) {
973
- return template.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
974
- }
975
- var isEmptyValue = (value) => value === null || value === void 0 || value === "";
976
- var NUMBER = new Intl.NumberFormat();
977
- var DECIMAL = new Intl.NumberFormat(void 0, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
978
- var PERCENT = new Intl.NumberFormat(void 0, { style: "percent", maximumFractionDigits: 1 });
979
- var DAY = new Intl.DateTimeFormat(void 0, { dateStyle: "medium" });
980
- function numeric(value, format) {
981
- const n = typeof value === "number" ? value : Number(value);
982
- return Number.isFinite(n) ? format.format(n) : String(value);
983
- }
984
- var DAY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
985
- function dayToDate(value) {
986
- const day = typeof value === "string" ? DAY_PATTERN.exec(value) : null;
987
- if (!day) return null;
988
- return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
989
- }
990
- function dateToDay(date) {
991
- const pad = (n) => String(n).padStart(2, "0");
992
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
993
- }
994
- function formatDay(value, zone = personTimeZone()) {
995
- const date = dayToDate(value);
996
- if (date) return DAY.format(date);
997
- const text2 = String(value);
998
- const at = /^\d{4}-\d{2}-\d{2}[T ]/.test(text2) ? new Date(text2) : null;
999
- if (!at || Number.isNaN(at.getTime()) || !isTimeZone(zone)) return text2;
1000
- const wall = wallClock(zone, at);
1001
- return DAY.format(new Date(wall.year, wall.month - 1, wall.day));
1002
- }
1003
- function resolveZone(zone, zones) {
1004
- if (!zone || zone === "viewer") return zones.viewer;
1005
- if (zone === "scope") return zones.scope;
1006
- if (isTimeZone(zone)) return zone;
1007
- throw new RangeError(
1008
- zone === "practice" ? `[genesis-ui-native] timeZone "practice" was renamed "scope" in genesis-core 2; run \`genesis codemod genesis-core-2-scope-names\`` : `[genesis-ui-native] timeZone "${zone}" isn't "viewer", "scope" or a time zone this runtime knows`
1009
- );
1010
- }
1011
- var WALL = new Intl.DateTimeFormat(void 0, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
1012
- function formatInstant(value, zone) {
1013
- const at = new Date(String(value));
1014
- if (Number.isNaN(at.getTime()) || !isTimeZone(zone)) return String(value);
1015
- const wall = wallClock(zone, at);
1016
- return WALL.format(new Date(Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second)));
1017
- }
1018
- function openableUrl(value) {
1019
- if (!isSafeUrl(value)) return null;
1020
- const url = value.trim();
1021
- return /^(https?:|mailto:|tel:)/i.test(url) ? url : null;
1022
- }
1023
- function displayText(hint, value, messages, timeZone = personTimeZone()) {
1024
- if (isEmptyValue(value)) return messages.common.empty;
1025
- switch (hint) {
1026
- case "number":
1027
- return numeric(value, NUMBER);
1028
- case "currency":
1029
- return numeric(value, DECIMAL);
1030
- case "percent":
1031
- return numeric(value, PERCENT);
1032
- case "boolean":
1033
- return value === true || value === "true" ? messages.common.yes : messages.common.no;
1034
- case "badge":
1035
- return titleCase(String(value));
1036
- case "date":
1037
- return formatDay(value, timeZone);
1038
- case "datetime":
1039
- return formatInstant(value, timeZone);
1040
- case "url": {
1041
- const url = openableUrl(value);
1042
- return url ? url.replace(/^https?:\/\//i, "") : String(value);
1043
- }
1044
- case "json":
1045
- return typeof value === "string" ? value : JSON.stringify(value);
1046
- default:
1047
- return typeof value === "object" ? JSON.stringify(value) : String(value);
1162
+ function resolveField(f, index) {
1163
+ if (typeof f === "string") {
1164
+ return {
1165
+ key: f,
1166
+ position: index === 0 ? "title" : "meta"
1167
+ };
1048
1168
  }
1169
+ return f;
1049
1170
  }
1050
- var BADGE_VARIANT = {
1051
- success: "success",
1052
- warning: "warning",
1053
- danger: "destructive",
1054
- info: "info",
1055
- muted: "muted"
1056
- };
1057
- function badgeVariant(tone) {
1058
- return BADGE_VARIANT[tone ?? "muted"];
1171
+ function autoDetectFields(item) {
1172
+ const keys = Object.keys(item).filter((k) => k !== "id");
1173
+ return keys.map((key, i) => ({
1174
+ key,
1175
+ position: i === 0 ? "title" : "meta"
1176
+ }));
1059
1177
  }
1060
- function LinkText({ url, label }) {
1178
+ function DefaultCardRenderer({
1179
+ item,
1180
+ fields,
1181
+ onPress
1182
+ }) {
1183
+ const titleField = fields.find((f) => f.position === "title");
1184
+ const badgeField = fields.find((f) => f.position === "badge");
1185
+ const subtitleField = fields.find((f) => f.position === "subtitle");
1186
+ const metaFields = fields.filter((f) => f.position === "meta");
1187
+ const renderValue = (field) => {
1188
+ const value = item[field.key];
1189
+ if (field.render) {
1190
+ return field.render(value, item);
1191
+ }
1192
+ if (value === null || value === void 0) return null;
1193
+ return String(value);
1194
+ };
1195
+ const titleContent = titleField ? renderValue(titleField) : null;
1196
+ const badgeContent = badgeField ? renderValue(badgeField) : null;
1197
+ const subtitleContent = subtitleField ? renderValue(subtitleField) : null;
1061
1198
  return /* @__PURE__ */ jsx(
1062
- Text,
1199
+ Pressable,
1063
1200
  {
1064
- accessibilityRole: "link",
1065
- className: "text-base text-primary-text underline",
1066
- onPress: () => void Linking.openURL(url),
1067
- children: label
1201
+ onPress: onPress ? () => onPress(item) : void 0,
1202
+ style: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 }),
1203
+ children: /* @__PURE__ */ jsxs(NativeCard, { className: "mx-4 mb-3", children: [
1204
+ /* @__PURE__ */ jsxs(NativeCardHeader, { className: "pb-2", children: [
1205
+ /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" }, children: [
1206
+ titleContent !== null ? /* @__PURE__ */ jsx(NativeCardTitle, { className: "flex-1 text-base", children: titleContent }) : null,
1207
+ badgeContent !== null ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground ml-2", children: badgeContent }) : null
1208
+ ] }),
1209
+ subtitleContent !== null ? /* @__PURE__ */ jsx(NativeText, { preset: "body-sm", className: "text-muted-foreground mt-0.5", children: subtitleContent }) : null
1210
+ ] }),
1211
+ metaFields.length > 0 ? /* @__PURE__ */ jsx(NativeCardContent, { className: "pt-0", children: /* @__PURE__ */ jsx(View, { style: { flexDirection: "row", flexWrap: "wrap", gap: 8 }, children: metaFields.map((field) => {
1212
+ const val = renderValue(field);
1213
+ if (val === null) return null;
1214
+ return /* @__PURE__ */ jsxs(NativeText, { preset: "caption", className: "text-muted-foreground", children: [
1215
+ field.label ? `${field.label}: ` : "",
1216
+ val
1217
+ ] }, field.key);
1218
+ }) }) }) : null
1219
+ ] })
1068
1220
  }
1069
1221
  );
1070
1222
  }
1071
- var text = (hint) => (value, { messages, column, zones }) => /* @__PURE__ */ jsx(NativeText, { preset: "body", children: displayText(hint, value, messages, resolveZone(column.timeZone, zones)) });
1072
- function RelationText({ value, context }) {
1073
- const { column, messages } = context;
1074
- const reference = column.field?.references;
1075
- const label = useRelationLabel(reference, value, column.labelField ? { labelField: column.labelField } : {});
1076
- const shown = !reference ? String(value) : label === void 0 ? messages.common.empty : label ?? column.missingLabel ?? messages.common.hiddenLink ?? defaultNativeResourceViewMessages.common.hiddenLink;
1077
- return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: shown });
1078
- }
1079
- var nativeDisplayRenderers = {
1080
- text: text("text"),
1081
- longText: (value) => /* @__PURE__ */ jsx(NativeText, { preset: "body", numberOfLines: 3, children: String(value) }),
1082
- number: text("number"),
1083
- currency: text("currency"),
1084
- percent: text("percent"),
1085
- boolean: text("boolean"),
1086
- badge: (value, { column }) => /* @__PURE__ */ jsx(NativeBadge, { variant: badgeVariant(column.tones?.[String(value)]), children: valueText(column.labels, value) }),
1087
- date: text("date"),
1088
- datetime: text("datetime"),
1089
- // The linked row's words, batched across the list (one query per linked resource), else its id.
1090
- relation: (value, context) => /* @__PURE__ */ jsx(RelationText, { value, context }),
1091
- url: (value, { messages }) => {
1092
- const url = openableUrl(value);
1093
- return url && /^https?:/i.test(url) ? /* @__PURE__ */ jsx(LinkText, { url, label: displayText("url", value, messages) }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: String(value) });
1094
- },
1095
- email: (value) => {
1096
- const address = String(value).trim();
1097
- const url = /^[^\s@?&#/]+@[^\s@?&#/]+$/.test(address) ? openableUrl(`mailto:${address}`) : null;
1098
- return url ? /* @__PURE__ */ jsx(LinkText, { url, label: address }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: address });
1099
- },
1100
- image: (value) => {
1101
- const url = openableUrl(value);
1102
- return url && /^https?:/i.test(url) ? /* @__PURE__ */ jsx(NativeImage, { src: url, width: 64, height: 64, className: "rounded-md" }) : /* @__PURE__ */ jsx(NativeText, { preset: "body", children: String(value) });
1103
- },
1104
- json: (value) => /* @__PURE__ */ jsx(NativeText, { preset: "caption", numberOfLines: 2, children: typeof value === "string" ? value : JSON.stringify(value) })
1105
- };
1106
- var DisplayRenderersContext = createContext(nativeDisplayRenderers);
1107
- var MessagesContext = createContext(defaultNativeResourceViewMessages);
1108
- var TimeZonesContext = createContext(null);
1109
- var DisplayTimeZonesProvider = TimeZonesContext.Provider;
1110
- function useDisplayTimeZones() {
1111
- const zones = useContext(TimeZonesContext);
1112
- return useMemo(() => zones ?? { viewer: personTimeZone(), scope: personTimeZone() }, [zones]);
1113
- }
1114
- function DisplayRenderersProvider({
1115
- renderers,
1116
- children
1223
+ function NativeResourcePage({
1224
+ resource,
1225
+ resourceOptions,
1226
+ title,
1227
+ subtitle,
1228
+ cardFields,
1229
+ renderItem,
1230
+ searchFields,
1231
+ searchPlaceholder,
1232
+ statusFilter,
1233
+ onItemPress,
1234
+ titleField,
1235
+ onCreatePress,
1236
+ createLabel = "New",
1237
+ headerRight,
1238
+ emptyState,
1239
+ offlineState
1117
1240
  }) {
1118
- const parent = useContext(DisplayRenderersContext);
1119
- const value = useMemo(() => ({ ...parent, ...renderers }), [parent, renderers]);
1120
- return /* @__PURE__ */ jsx(DisplayRenderersContext.Provider, { value, children });
1121
- }
1122
- var NativeResourceViewMessagesProvider = MessagesContext.Provider;
1123
- function useNativeResourceViewMessages() {
1124
- return useContext(MessagesContext);
1125
- }
1126
- function useDisplayCell() {
1127
- const renderers = useContext(DisplayRenderersContext);
1128
- const messages = useNativeResourceViewMessages();
1129
- const zones = useDisplayTimeZones();
1130
- const viewer = useViewer();
1131
- return useMemo(
1132
- () => (column, row) => {
1133
- if (column.when && !column.when(row, viewer)) return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: messages.common.empty });
1134
- const value = column.value(row);
1135
- if (isEmptyValue(value)) return /* @__PURE__ */ jsx(NativeText, { preset: "body", children: messages.common.empty });
1136
- return renderers[column.display](value, { row, column, messages, zones });
1241
+ const { list: FlashList } = useGenesisModules();
1242
+ const [search, setSearchLocal] = useState("");
1243
+ const [selectedStatuses, setSelectedStatuses] = useState([]);
1244
+ const statusFilterConfig = useMemo(() => {
1245
+ if (!statusFilter) return null;
1246
+ if (typeof statusFilter === "string") {
1247
+ return { field: statusFilter, options: void 0 };
1248
+ }
1249
+ return { field: statusFilter.field, options: statusFilter.options };
1250
+ }, [statusFilter]);
1251
+ const mergedOptions = useMemo(
1252
+ () => ({
1253
+ ...resourceOptions,
1254
+ searchFields: searchFields ?? resourceOptions?.searchFields
1255
+ }),
1256
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1257
+ [resourceOptions, searchFields]
1258
+ );
1259
+ const { list, setSearch, setFilters } = useResource(resource, mergedOptions);
1260
+ useEffect(() => {
1261
+ setSearch(search);
1262
+ }, [search, setSearch]);
1263
+ useEffect(() => {
1264
+ if (!statusFilterConfig) return;
1265
+ if (selectedStatuses.length === 0) {
1266
+ setFilters([]);
1267
+ } else if (selectedStatuses.length === 1) {
1268
+ setFilters([
1269
+ {
1270
+ field: statusFilterConfig.field,
1271
+ operator: "eq",
1272
+ value: selectedStatuses[0]
1273
+ }
1274
+ ]);
1275
+ } else {
1276
+ setFilters([
1277
+ {
1278
+ field: statusFilterConfig.field,
1279
+ operator: "in",
1280
+ value: selectedStatuses
1281
+ }
1282
+ ]);
1283
+ }
1284
+ }, [selectedStatuses, statusFilterConfig, setFilters]);
1285
+ const items = list.data?.data ?? [];
1286
+ const isLoading = list.isLoading;
1287
+ const hasError = list.isError;
1288
+ const isOfflineEmpty = list.isPaused && list.data === void 0;
1289
+ const resolvedFields = useMemo(() => {
1290
+ if (titleField && cardFields) {
1291
+ const resolved = cardFields.map((f, i) => resolveField(f, i));
1292
+ return resolved.map(
1293
+ (f) => f.key === titleField ? { ...f, position: "title" } : f
1294
+ );
1295
+ }
1296
+ if (cardFields && cardFields.length > 0) {
1297
+ return cardFields.map((f, i) => resolveField(f, i));
1298
+ }
1299
+ if (items.length > 0) {
1300
+ const detected = autoDetectFields(items[0]);
1301
+ if (titleField) {
1302
+ return detected.map(
1303
+ (f) => f.key === titleField ? { ...f, position: "title" } : f
1304
+ );
1305
+ }
1306
+ return detected;
1307
+ }
1308
+ return [];
1309
+ }, [cardFields, titleField, items]);
1310
+ const statusOptions = useMemo(() => {
1311
+ if (!statusFilterConfig) return [];
1312
+ if (statusFilterConfig.options) return statusFilterConfig.options;
1313
+ const values = /* @__PURE__ */ new Set();
1314
+ for (const item of items) {
1315
+ const v = item[statusFilterConfig.field];
1316
+ if (typeof v === "string") values.add(v);
1317
+ }
1318
+ return Array.from(values).sort();
1319
+ }, [statusFilterConfig, items]);
1320
+ const effectiveHeaderRight = useMemo(() => {
1321
+ if (onCreatePress) {
1322
+ return /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", alignItems: "center", gap: 8 }, children: [
1323
+ headerRight,
1324
+ /* @__PURE__ */ jsx(NativeButton, { size: "sm", onPress: onCreatePress, children: createLabel })
1325
+ ] });
1326
+ }
1327
+ return headerRight ?? null;
1328
+ }, [onCreatePress, createLabel, headerRight]);
1329
+ const [refreshing, setRefreshing] = useState(false);
1330
+ const refetch = list.refetch;
1331
+ const handleRefresh = useCallback(async () => {
1332
+ setRefreshing(true);
1333
+ try {
1334
+ await refetch();
1335
+ } catch (err) {
1336
+ console.error(`[NativeResourcePage] Pull-to-refresh failed:`, err);
1337
+ } finally {
1338
+ setRefreshing(false);
1339
+ }
1340
+ }, [refetch]);
1341
+ const hasActiveFilters = search.length > 0 || selectedStatuses.length > 0;
1342
+ const handleClearFilters = useCallback(() => {
1343
+ setSearchLocal("");
1344
+ setSelectedStatuses([]);
1345
+ }, []);
1346
+ const keyExtractor = useCallback(
1347
+ (item) => String(item.id),
1348
+ []
1349
+ );
1350
+ const renderFlatListItem = useCallback(
1351
+ ({ item }) => {
1352
+ if (renderItem) {
1353
+ return /* @__PURE__ */ jsx(Fragment, { children: renderItem(item) });
1354
+ }
1355
+ return /* @__PURE__ */ jsx(
1356
+ DefaultCardRenderer,
1357
+ {
1358
+ item,
1359
+ fields: resolvedFields,
1360
+ onPress: onItemPress
1361
+ }
1362
+ );
1137
1363
  },
1138
- [renderers, messages, zones, viewer]
1364
+ [renderItem, resolvedFields, onItemPress]
1365
+ );
1366
+ const ListHeaderComponent = useMemo(
1367
+ () => /* @__PURE__ */ jsx(View, { className: "px-4 pb-3", children: /* @__PURE__ */ jsx(
1368
+ NativeDataFilters,
1369
+ {
1370
+ search,
1371
+ onSearchChange: setSearchLocal,
1372
+ searchPlaceholder,
1373
+ statusChips: statusOptions.length > 0 ? {
1374
+ options: statusOptions,
1375
+ selected: selectedStatuses,
1376
+ onChange: setSelectedStatuses
1377
+ } : void 0
1378
+ }
1379
+ ) }),
1380
+ [search, searchPlaceholder, statusOptions, selectedStatuses]
1381
+ );
1382
+ const ListEmptyComponent = useMemo(
1383
+ () => isLoading ? null : isOfflineEmpty ? (
1384
+ // In the list, under its header, so search and filters stay usable offline: clearing a
1385
+ // search brings back the saved rows.
1386
+ /* @__PURE__ */ jsx(View, { testID: "native-resource-offline", className: "flex-1 items-center justify-center px-4 py-12 gap-4", children: offlineState ?? /* @__PURE__ */ jsx(NativeText, { preset: "body", className: "text-muted-foreground text-center", children: "You're offline. This list loads when you're back online." }) })
1387
+ ) : /* @__PURE__ */ jsx(Fragment, { children: emptyState ?? /* @__PURE__ */ jsx(
1388
+ NativeEmptyState2,
1389
+ {
1390
+ hasFilters: hasActiveFilters,
1391
+ onClearFilters: hasActiveFilters ? handleClearFilters : void 0
1392
+ }
1393
+ ) }),
1394
+ [isLoading, isOfflineEmpty, offlineState, emptyState, hasActiveFilters, handleClearFilters]
1139
1395
  );
1396
+ const renderPageContent = () => {
1397
+ if (isLoading) {
1398
+ return /* @__PURE__ */ jsxs(View, { className: "px-4 pt-4 gap-3", children: [
1399
+ /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-10 rounded-lg" }),
1400
+ /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" }),
1401
+ /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" }),
1402
+ /* @__PURE__ */ jsx(NativeSkeleton, { className: "w-full h-20 rounded-lg" })
1403
+ ] });
1404
+ }
1405
+ if (hasError) {
1406
+ return /* @__PURE__ */ jsxs(View, { className: "flex-1 items-center justify-center px-4 py-12 gap-4", children: [
1407
+ /* @__PURE__ */ jsx(NativeText, { preset: "body", className: "text-destructive text-center", children: list.error?.message ?? "Something went wrong." }),
1408
+ /* @__PURE__ */ jsx(NativeButton, { variant: "outline", size: "sm", onPress: () => list.refetch(), children: "Try Again" })
1409
+ ] });
1410
+ }
1411
+ if (FlashList) {
1412
+ return /* @__PURE__ */ jsx(
1413
+ FlashList,
1414
+ {
1415
+ testID: "native-resource-page-list",
1416
+ data: items,
1417
+ keyExtractor,
1418
+ renderItem: renderFlatListItem,
1419
+ ListHeaderComponent,
1420
+ ListEmptyComponent,
1421
+ contentContainerStyle: { paddingBottom: 24 },
1422
+ refreshing: refreshing && !list.isPaused,
1423
+ onRefresh: handleRefresh
1424
+ }
1425
+ );
1426
+ }
1427
+ return /* @__PURE__ */ jsx(
1428
+ FlatList,
1429
+ {
1430
+ testID: "native-resource-page-list",
1431
+ data: items,
1432
+ keyExtractor,
1433
+ renderItem: renderFlatListItem,
1434
+ ListHeaderComponent,
1435
+ ListEmptyComponent,
1436
+ contentContainerStyle: { flexGrow: 1, paddingBottom: 24 },
1437
+ refreshing: refreshing && !list.isPaused,
1438
+ onRefresh: handleRefresh
1439
+ }
1440
+ );
1441
+ };
1442
+ return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["left", "right"], className: "flex-1 bg-background", children: [
1443
+ /* @__PURE__ */ jsx(View, { className: "px-4 pt-4 pb-2", children: /* @__PURE__ */ jsxs(
1444
+ View,
1445
+ {
1446
+ style: {
1447
+ flexDirection: "row",
1448
+ alignItems: "center",
1449
+ justifyContent: "space-between"
1450
+ },
1451
+ children: [
1452
+ /* @__PURE__ */ jsxs(View, { className: "flex-1", children: [
1453
+ /* @__PURE__ */ jsx(NativeText, { preset: "h2", children: title }),
1454
+ subtitle ? /* @__PURE__ */ jsx(
1455
+ NativeText,
1456
+ {
1457
+ preset: "body-sm",
1458
+ className: "text-muted-foreground mt-0.5",
1459
+ children: subtitle
1460
+ }
1461
+ ) : null
1462
+ ] }),
1463
+ effectiveHeaderRight ? /* @__PURE__ */ jsx(View, { className: "ml-3", children: effectiveHeaderRight }) : null
1464
+ ]
1465
+ }
1466
+ ) }),
1467
+ /* @__PURE__ */ jsx(View, { className: "flex-1", children: renderPageContent() })
1468
+ ] });
1140
1469
  }
1141
1470
  function nativePicture(summary) {
1142
1471
  const picture = rowPicture(summary);
@@ -1325,127 +1654,6 @@ function refusalFields(error) {
1325
1654
  }
1326
1655
  return {};
1327
1656
  }
1328
- var SEARCH_DEBOUNCE_MS = 300;
1329
- function NativeLinkPicker({ field, value, onChange, values, error, testID }) {
1330
- const messages = useNativeResourceViewMessages();
1331
- const words = { ...defaultNativeResourceViewMessages.link, ...messages.link };
1332
- const link = field.link;
1333
- const viewer = useViewer();
1334
- const [open, setOpen] = useState(false);
1335
- const [query, setQuery] = useState("");
1336
- const [search, setSearch] = useState("");
1337
- useEffect(() => {
1338
- const timer = setTimeout(() => setSearch(query), SEARCH_DEBOUNCE_MS);
1339
- return () => clearTimeout(timer);
1340
- }, [query]);
1341
- const filtersKey = JSON.stringify(link.filters(viewer.scope, values));
1342
- const filters = useMemo(() => JSON.parse(filtersKey), [filtersKey]);
1343
- const labelField = field.labelField ?? link.labelField;
1344
- const list = useLinkOptions(
1345
- { resource: link.resource, field: link.field, labelField, searchFields: link.searchFields, orderBy: link.orderBy },
1346
- { filters, search, enabled: open, untitled: words.untitled }
1347
- );
1348
- const loaded = isEmptyValue(value) ? void 0 : list.options.find((o) => String(o.value) === String(value));
1349
- const looked = useRelationLabel({ resource: link.resource, field: link.field }, value, {
1350
- ...list.labelField ?? labelField ? { labelField: list.labelField ?? labelField } : {},
1351
- enabled: !isEmptyValue(value) && !loaded
1352
- });
1353
- const chosen = isEmptyValue(value) ? null : loaded?.label ?? (looked === void 0 ? void 0 : looked ?? field.missingLabel ?? messages.common.hiddenLink ?? defaultNativeResourceViewMessages.common.hiddenLink);
1354
- const shown = chosen === void 0 ? messages.common.empty : chosen ?? words.placeholder;
1355
- const pick = (next) => {
1356
- onChange(next);
1357
- setOpen(false);
1358
- setQuery("");
1359
- };
1360
- return /* @__PURE__ */ jsxs(View, { testID, style: { gap: 6 }, children: [
1361
- /* @__PURE__ */ jsx(NativeLabel, { children: field.label }),
1362
- /* @__PURE__ */ jsxs(
1363
- Pressable,
1364
- {
1365
- testID: `${testID}-trigger`,
1366
- accessibilityRole: "button",
1367
- accessibilityLabel: error ? `${field.label}, ${shown}, ${error}` : `${field.label}, ${shown}`,
1368
- accessibilityState: { expanded: open },
1369
- onPress: () => setOpen((was) => !was),
1370
- className: "min-h-[44px] flex-row items-center justify-between rounded-md border border-input bg-background px-3",
1371
- children: [
1372
- /* @__PURE__ */ jsx(Text, { className: chosen ? "text-base text-foreground" : "text-base text-muted-foreground", numberOfLines: 1, children: shown }),
1373
- /* @__PURE__ */ jsx(Text, { className: "text-muted-foreground", accessible: false, children: open ? "\u25B4" : "\u25BE" })
1374
- ]
1375
- }
1376
- ),
1377
- open ? /* @__PURE__ */ jsxs(View, { testID: `${testID}-list`, style: { gap: 4 }, accessibilityRole: "radiogroup", accessibilityLabel: field.label, children: [
1378
- list.searchable ? /* @__PURE__ */ jsx(
1379
- NativeSearchBar,
1380
- {
1381
- testID: `${testID}-search`,
1382
- value: query,
1383
- onChange: setQuery,
1384
- placeholder: words.search,
1385
- showCancel: false
1386
- }
1387
- ) : null,
1388
- !field.required && query === "" ? /* @__PURE__ */ jsx(
1389
- Option,
1390
- {
1391
- testID: `${testID}-none`,
1392
- label: words.none,
1393
- muted: true,
1394
- selected: isEmptyValue(value),
1395
- onPress: () => pick(null)
1396
- }
1397
- ) : null,
1398
- list.isLoading ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-muted-foreground", testID: `${testID}-loading`, children: messages.form.loading }) : list.isError ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-destructive", accessibilityRole: "alert", children: words.loadFailed }) : list.options.length === 0 ? /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "px-3 py-2 text-muted-foreground", testID: `${testID}-empty`, children: words.noResults }) : list.options.map((option) => /* @__PURE__ */ jsx(
1399
- Option,
1400
- {
1401
- testID: `${testID}-option-${String(option.value)}`,
1402
- label: option.label,
1403
- selected: !isEmptyValue(value) && String(value) === String(option.value),
1404
- onPress: () => pick(option.value)
1405
- },
1406
- String(option.value)
1407
- )),
1408
- list.hasMore ? /* @__PURE__ */ jsx(
1409
- NativeButton,
1410
- {
1411
- variant: "ghost",
1412
- size: "sm",
1413
- testID: `${testID}-more`,
1414
- disabled: list.isLoadingMore,
1415
- onPress: list.loadMore,
1416
- children: list.isLoadingMore ? messages.list.loadingMore : words.loadMore
1417
- }
1418
- ) : null
1419
- ] }) : null,
1420
- error ? (
1421
- // A live region on Android; the alert role on iOS and the web.
1422
- /* @__PURE__ */ jsx(View, { accessibilityLiveRegion: "polite", children: /* @__PURE__ */ jsx(NativeText, { preset: "caption", className: "text-destructive", testID: `${testID}-error`, accessibilityRole: "alert", children: error }) })
1423
- ) : null
1424
- ] });
1425
- }
1426
- function Option({
1427
- label,
1428
- selected,
1429
- muted = false,
1430
- onPress,
1431
- testID
1432
- }) {
1433
- return /* @__PURE__ */ jsxs(
1434
- Pressable,
1435
- {
1436
- testID,
1437
- accessibilityRole: "radio",
1438
- accessibilityLabel: label,
1439
- accessibilityState: { checked: selected },
1440
- onPress,
1441
- className: "min-h-[44px] flex-row items-center justify-between px-3",
1442
- children: [
1443
- /* @__PURE__ */ jsx(Text, { className: muted ? "text-base text-muted-foreground" : "text-base text-foreground", children: label }),
1444
- selected ? /* @__PURE__ */ jsx(Text, { className: "text-base text-primary-text", accessible: false, children: "\u2713" }) : null
1445
- ]
1446
- }
1447
- );
1448
- }
1449
1657
  var FIELD_TYPE = {
1450
1658
  text: "text",
1451
1659
  email: "email",
@@ -2867,7 +3075,121 @@ function Cell({ last, children }) {
2867
3075
  !last ? /* @__PURE__ */ jsx(View, { style: { height: 0.5, marginLeft: 16, backgroundColor: colors.separator } }) : null
2868
3076
  ] });
2869
3077
  }
3078
+ function useNativeCustomView(view, options = {}) {
3079
+ const list = useNativeResourceView(view, options);
3080
+ const reducedMotion = useReducedMotion();
3081
+ const status = customViewStatus({ error: list.error, loading: list.loading, empty: list.rows.length === 0 });
3082
+ return {
3083
+ view,
3084
+ type: "list",
3085
+ status,
3086
+ error: list.error,
3087
+ retry: () => void list.refresh(),
3088
+ rows: list.rows,
3089
+ groups: (rows, o) => groupRows(view, rows ?? list.rows, o),
3090
+ list,
3091
+ reducedMotion
3092
+ };
3093
+ }
3094
+ function NativeCustomView({ view, children, loading, empty, error, testID = "custom-view", ...options }) {
3095
+ const state = useNativeCustomView(view, options);
3096
+ const messages = useNativeResourceViewMessages();
3097
+ const copy = view.definition.copy?.empty;
3098
+ const showChildren = state.status === "ready" || state.status === "empty" && empty === false;
3099
+ return /* @__PURE__ */ jsx(View, { testID, accessibilityState: { busy: state.status === "loading" || state.list.refreshing }, className: "flex-1", children: showChildren ? children(state) : state.status === "loading" ? loading ?? /* @__PURE__ */ jsxs(View, { testID: `${testID}-loading`, accessibilityRole: "progressbar", accessibilityLabel: messages.form.loading, className: "gap-2 p-4", children: [
3100
+ /* @__PURE__ */ jsx(NativeSkeleton, { height: 40, className: "w-full" }),
3101
+ /* @__PURE__ */ jsx(NativeSkeleton, { height: 40, className: "w-full" }),
3102
+ /* @__PURE__ */ jsx(NativeSkeleton, { height: 40, className: "w-2/3" })
3103
+ ] }) : state.status === "error" ? typeof error === "function" ? error(state.error ?? "", state.retry) : error ?? /* @__PURE__ */ jsx(
3104
+ NativeEmptyState,
3105
+ {
3106
+ testID: `${testID}-error`,
3107
+ variant: "error",
3108
+ title: state.error ?? void 0,
3109
+ primaryAction: /* @__PURE__ */ jsx(NativeButton, { variant: "outline", size: "sm", onPress: state.retry, testID: `${testID}-retry`, children: messages.list.retry })
3110
+ }
3111
+ ) : empty ?? /* @__PURE__ */ jsx(
3112
+ NativeEmptyState,
3113
+ {
3114
+ testID: `${testID}-empty`,
3115
+ title: copy?.title ?? fill(messages.list.emptyTitle, { nounPlural: view.nounPlural }),
3116
+ body: copy?.body ?? messages.list.emptyBody
3117
+ }
3118
+ ) });
3119
+ }
3120
+ function NativeRecordPeek({
3121
+ row,
3122
+ open,
3123
+ onClose,
3124
+ onEdit,
3125
+ onDelete,
3126
+ can,
3127
+ header,
3128
+ snapPoints = ["60%", "92%"],
3129
+ labels = {},
3130
+ testID = "record-peek",
3131
+ ...rest
3132
+ }) {
3133
+ const messages = useNativeResourceViewMessages();
3134
+ const view = rest.view.view;
3135
+ const viewer = useViewer();
3136
+ const softDelete = useCapabilities(view.resource).data?.softDelete === true;
3137
+ const [deleting, setDeleting] = useState(false);
3138
+ const shown = open && row !== null;
3139
+ const title = row ? view.summary(row).title : "";
3140
+ const canEdit = row && onEdit ? allowed(view, "update", row, can, viewer) : false;
3141
+ const canDelete = row && onDelete ? allowed(view, "delete", row, can, viewer) : false;
3142
+ const words = softDelete ? messages.bin : messages.delete;
3143
+ const deleteLabel = labels.delete ?? words.action;
3144
+ const editLabel = labels.edit ?? messages.common.edit;
3145
+ const runDelete = async (r) => {
3146
+ setDeleting(true);
3147
+ try {
3148
+ await onDelete?.(r);
3149
+ onClose();
3150
+ } catch (error) {
3151
+ Alert.alert(deleteLabel, refusalMessage(error, fill(messages.refusal.deleteFailed, { noun: view.noun })));
3152
+ } finally {
3153
+ setDeleting(false);
3154
+ }
3155
+ };
3156
+ const confirmDelete = (r) => Alert.alert(labels.deleteTitle ?? fill(words.confirmTitle, { name: title }), labels.deleteBody ?? words.confirmBody, [
3157
+ { text: labels.cancel ?? messages.common.cancel, style: "cancel" },
3158
+ { text: deleteLabel, style: "destructive", onPress: () => void runDelete(r) }
3159
+ ]);
3160
+ return /* @__PURE__ */ jsx(NativeSheet, { open: shown, onOpenChange: (next) => next ? void 0 : onClose(), snapPoints, testID, children: row ? /* @__PURE__ */ jsxs(View, { style: { flex: 1, paddingBottom: 16 }, children: [
3161
+ /* @__PURE__ */ jsxs(View, { className: "flex-row items-center justify-between gap-2 px-4 pb-2", children: [
3162
+ /* @__PURE__ */ jsx(Text, { accessibilityRole: "header", numberOfLines: 2, className: "flex-1 text-lg font-semibold text-foreground", children: title }),
3163
+ canEdit !== false ? /* @__PURE__ */ jsx(
3164
+ NativeButton,
3165
+ {
3166
+ size: "sm",
3167
+ variant: "outline",
3168
+ testID: `${testID}-edit`,
3169
+ accessibilityHint: canEdit === true ? void 0 : canEdit,
3170
+ onPress: () => canEdit === true ? onEdit(row) : Alert.alert(editLabel, canEdit),
3171
+ children: editLabel
3172
+ }
3173
+ ) : null,
3174
+ canDelete !== false ? /* @__PURE__ */ jsx(
3175
+ NativeButton,
3176
+ {
3177
+ size: "sm",
3178
+ variant: "ghost",
3179
+ textClassName: "text-destructive",
3180
+ testID: `${testID}-delete`,
3181
+ disabled: deleting,
3182
+ accessibilityHint: canDelete === true ? void 0 : canDelete,
3183
+ onPress: () => canDelete === true ? confirmDelete(row) : Alert.alert(deleteLabel, canDelete),
3184
+ children: deleteLabel
3185
+ }
3186
+ ) : null
3187
+ ] }),
3188
+ header,
3189
+ /* @__PURE__ */ jsx(NativeRecordView, { ...rest, row, testID: `${testID}-page` })
3190
+ ] }) : null });
3191
+ }
2870
3192
 
2871
- export { DEFAULT_MAX_PAGES, DisplayRenderersProvider, DisplayTimeZonesProvider, NativeConflictSheet, NativeDataFilters, NativeDataPageShell, NativeDetailPanel, NativeEmptyState2 as NativeEmptyState, NativeRecordView, NativeRecordViewMenu, NativeResourceForm, NativeResourceFormFieldRenderer, NativeResourceFormSheet, NativeResourcePage, NativeResourceView, NativeResourceViewMessagesProvider, NativeResourceWorkspace, NativeResourceWorkspaceMenu, SEARCH_DEBOUNCE_MS2 as SEARCH_DEBOUNCE_MS, SEGMENTED_SECTIONS_MAX, allowed, dateToDay, dayToDate, defaultNativeRecordViewMessages, defaultNativeResourceViewMessages, defaultNativeResourceWorkspaceMessages, displayText, formFieldsFor, formatDay, formatInstant, getNativeRecordViewStackOptions, getNativeResourceWorkspaceStackOptions, nativeDisplayRenderers, openableUrl, parseSettingNumber, resolveZone, rowItem, screenValues, sectionsFor, serverSort, serverSorts, swipeActionsFor, useDisplayCell, useDisplayTimeZones, useNativeResourceView, useNativeResourceViewMessages, validateValues, writableValues };
3193
+ export { DEFAULT_MAX_PAGES, DisplayRenderersProvider, DisplayTimeZonesProvider, NativeConflictSheet, NativeCustomView, NativeDataFilters, NativeDataPageShell, NativeDetailPanel, NativeEmptyState2 as NativeEmptyState, NativeFieldArrayRenderer, NativeFileUploadField, NativeRecordPeek, NativeRecordView, NativeRecordViewMenu, NativeRelationField, NativeResourceForm, NativeResourceFormFieldRenderer, NativeResourceFormSheet, NativeResourcePage, NativeResourceView, NativeResourceViewMessagesProvider, NativeResourceWorkspace, NativeResourceWorkspaceMenu, NativeWizardForm, SEARCH_DEBOUNCE_MS2 as SEARCH_DEBOUNCE_MS, SEGMENTED_SECTIONS_MAX, allowed, dateToDay, dayToDate, defaultNativeRecordViewMessages, defaultNativeResourceViewMessages, defaultNativeResourceWorkspaceMessages, displayText, formFieldsFor, formatDay, formatInstant, getNativeRecordViewStackOptions, getNativeResourceWorkspaceStackOptions, nativeDisplayRenderers, openableUrl, parseSettingNumber, resolveZone, rowItem, screenValues, sectionsFor, serverSort, serverSorts, swipeActionsFor, useDisplayCell, useDisplayTimeZones, useNativeCustomView, useNativeResourceView, useNativeResourceViewMessages, validateValues, writableValues };
2872
3194
  //# sourceMappingURL=index.js.map
2873
3195
  //# sourceMappingURL=index.js.map