@codual/react-native-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +18 -2
  4. package/dist/announce.d.ts +2 -0
  5. package/dist/announce.js +8 -0
  6. package/dist/charts/data.d.ts +32 -0
  7. package/dist/charts/data.js +13 -0
  8. package/dist/charts/labels.d.ts +54 -0
  9. package/dist/charts/labels.js +91 -0
  10. package/dist/charts/machine.d.ts +62 -0
  11. package/dist/charts/machine.js +144 -0
  12. package/dist/charts/points.d.ts +23 -0
  13. package/dist/charts/points.js +46 -0
  14. package/dist/charts/summary.d.ts +29 -0
  15. package/dist/charts/summary.js +45 -0
  16. package/dist/charts/use-chart-interaction.d.ts +62 -0
  17. package/dist/charts/use-chart-interaction.js +79 -0
  18. package/dist/forms/async-checks.d.ts +34 -0
  19. package/dist/forms/async-checks.js +77 -0
  20. package/dist/forms/field-errors.d.ts +8 -0
  21. package/dist/forms/field-errors.js +16 -0
  22. package/dist/forms/form-types.d.ts +43 -0
  23. package/dist/forms/form-types.js +2 -0
  24. package/dist/forms/machine.d.ts +63 -0
  25. package/dist/forms/machine.js +251 -0
  26. package/dist/forms/numbers.d.ts +5 -0
  27. package/dist/forms/numbers.js +83 -0
  28. package/dist/forms/rules.d.ts +47 -0
  29. package/dist/forms/rules.js +72 -0
  30. package/dist/forms/server-errors.d.ts +17 -0
  31. package/dist/forms/server-errors.js +22 -0
  32. package/dist/forms/use-form.d.ts +49 -0
  33. package/dist/forms/use-form.js +61 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +94 -0
  36. package/dist/lists/PagedList.d.ts +47 -0
  37. package/dist/lists/PagedList.js +81 -0
  38. package/dist/lists/controller.d.ts +23 -0
  39. package/dist/lists/controller.js +20 -0
  40. package/dist/lists/inverted-list.d.ts +23 -0
  41. package/dist/lists/inverted-list.js +60 -0
  42. package/dist/lists/machine.d.ts +81 -0
  43. package/dist/lists/machine.js +252 -0
  44. package/dist/lists/newest-end.d.ts +30 -0
  45. package/dist/lists/newest-end.js +58 -0
  46. package/dist/lists/paged-content.d.ts +46 -0
  47. package/dist/lists/paged-content.js +65 -0
  48. package/dist/lists/paged-list-types.d.ts +56 -0
  49. package/dist/lists/paged-list-types.js +2 -0
  50. package/dist/lists/system-footer.d.ts +28 -0
  51. package/dist/lists/system-footer.js +50 -0
  52. package/dist/lists/use-paged-list.d.ts +25 -0
  53. package/dist/lists/use-paged-list.js +34 -0
  54. package/dist/permissions/access.d.ts +30 -0
  55. package/dist/permissions/access.js +2 -0
  56. package/dist/permissions/android-permission.d.ts +52 -0
  57. package/dist/permissions/android-permission.js +143 -0
  58. package/dist/permissions/permission.d.ts +69 -0
  59. package/dist/permissions/permission.js +201 -0
  60. package/dist/permissions/setup.d.ts +25 -0
  61. package/dist/permissions/setup.js +41 -0
  62. package/dist/permissions/status.d.ts +29 -0
  63. package/dist/permissions/status.js +18 -0
  64. package/dist/permissions/use-permission.d.ts +23 -0
  65. package/dist/permissions/use-permission.js +29 -0
  66. package/dist/purchases/Paywall.d.ts +27 -0
  67. package/dist/purchases/Paywall.js +28 -0
  68. package/dist/purchases/paywall-content.d.ts +20 -0
  69. package/dist/purchases/paywall-content.js +34 -0
  70. package/dist/purchases/purchases.d.ts +92 -0
  71. package/dist/purchases/purchases.js +236 -0
  72. package/dist/purchases/status.d.ts +62 -0
  73. package/dist/purchases/status.js +25 -0
  74. package/dist/purchases/store.d.ts +71 -0
  75. package/dist/purchases/store.js +2 -0
  76. package/dist/purchases/system-views.d.ts +49 -0
  77. package/dist/purchases/system-views.js +91 -0
  78. package/dist/purchases/use-purchases.d.ts +3 -0
  79. package/dist/purchases/use-purchases.js +8 -0
  80. package/dist/react-native-iap/iap-purchases.d.ts +24 -0
  81. package/dist/react-native-iap/iap-purchases.js +90 -0
  82. package/dist/react-native-iap/iap-store.d.ts +56 -0
  83. package/dist/react-native-iap/iap-store.js +249 -0
  84. package/dist/react-native-iap/iap-types.d.ts +12 -0
  85. package/dist/react-native-iap/iap-types.js +11 -0
  86. package/dist/react-native-iap/index.d.ts +31 -0
  87. package/dist/react-native-iap/index.js +24 -0
  88. package/dist/react-native-permissions/index.d.ts +24 -0
  89. package/dist/react-native-permissions/index.js +88 -0
  90. package/dist/screen-states/ScreenStates.d.ts +38 -0
  91. package/dist/screen-states/ScreenStates.js +69 -0
  92. package/dist/screen-states/errors.d.ts +9 -0
  93. package/dist/screen-states/errors.js +24 -0
  94. package/dist/screen-states/machine.d.ts +97 -0
  95. package/dist/screen-states/machine.js +172 -0
  96. package/dist/screen-states/system-views.d.ts +40 -0
  97. package/dist/screen-states/system-views.js +66 -0
  98. package/dist/screen-states/use-screen-states.d.ts +23 -0
  99. package/dist/screen-states/use-screen-states.js +41 -0
  100. package/dist/search/SearchResults.d.ts +22 -0
  101. package/dist/search/SearchResults.js +25 -0
  102. package/dist/search/announcements.d.ts +17 -0
  103. package/dist/search/announcements.js +31 -0
  104. package/dist/search/labels.d.ts +15 -0
  105. package/dist/search/labels.js +14 -0
  106. package/dist/search/machine.d.ts +65 -0
  107. package/dist/search/machine.js +241 -0
  108. package/dist/search/recent-search-sync.d.ts +32 -0
  109. package/dist/search/recent-search-sync.js +87 -0
  110. package/dist/search/recent-searches.d.ts +22 -0
  111. package/dist/search/recent-searches.js +40 -0
  112. package/dist/search/system-views.d.ts +11 -0
  113. package/dist/search/system-views.js +16 -0
  114. package/dist/search/types.d.ts +51 -0
  115. package/dist/search/types.js +2 -0
  116. package/dist/search/use-search.d.ts +73 -0
  117. package/dist/search/use-search.js +123 -0
  118. package/dist/selection/config.d.ts +34 -0
  119. package/dist/selection/config.js +13 -0
  120. package/dist/selection/labels.d.ts +19 -0
  121. package/dist/selection/labels.js +23 -0
  122. package/dist/selection/machine.d.ts +80 -0
  123. package/dist/selection/machine.js +274 -0
  124. package/dist/selection/snapshot.d.ts +54 -0
  125. package/dist/selection/snapshot.js +45 -0
  126. package/dist/selection/state.d.ts +25 -0
  127. package/dist/selection/state.js +24 -0
  128. package/dist/selection/system-views.d.ts +11 -0
  129. package/dist/selection/system-views.js +22 -0
  130. package/dist/selection/use-selection.d.ts +73 -0
  131. package/dist/selection/use-selection.js +100 -0
  132. package/dist/sheets/machine.d.ts +101 -0
  133. package/dist/sheets/machine.js +213 -0
  134. package/dist/sheets/use-sheet.d.ts +78 -0
  135. package/dist/sheets/use-sheet.js +103 -0
  136. package/dist/victory-native/index.d.ts +37 -0
  137. package/dist/victory-native/index.js +41 -0
  138. package/package.json +94 -4
  139. package/react-native-iap/package.json +4 -0
  140. package/react-native-permissions/package.json +4 -0
  141. package/victory-native/package.json +4 -0
@@ -0,0 +1,24 @@
1
+ import type * as ReactNativePermissionsModule from "react-native-permissions" with {
2
+ "resolution-mode": "import"
3
+ };
4
+ import type { PermissionAccess } from "../permissions/access";
5
+ import { type AndroidPermissionName, type AndroidPermissionOptions } from "../permissions/android-permission";
6
+ /** The parts of react-native-permissions the adapter uses: pass `import * as permissions from "react-native-permissions"`. */
7
+ export type ReactNativePermissions = Pick<typeof ReactNativePermissionsModule, "PERMISSIONS" | "check" | "request" | "checkNotifications" | "requestNotifications" | "checkLocationAccuracy" | "openSettings">;
8
+ type NotificationOption = NonNullable<Parameters<ReactNativePermissions["requestNotifications"]>[0]>[number];
9
+ export interface ReactNativePermissionsOptions extends AndroidPermissionOptions {
10
+ /** What iOS notifications ask for: alerts, badges and sounds unless the app says. */
11
+ readonly notificationOptions?: readonly NotificationOption[];
12
+ }
13
+ /**
14
+ * A permission on iOS through react-native-permissions (an optional peer dependency, with each permission's native part
15
+ * set up in the Podfile), and on Android through `androidPermission`. Call it once per permission:
16
+ *
17
+ * ```ts
18
+ * import * as permissions from "react-native-permissions";
19
+ * import { createReactNativePermissionsAccess } from "@codual/react-native-ui/react-native-permissions";
20
+ * const camera = createReactNativePermissionsAccess(permissions, "camera");
21
+ * ```
22
+ */
23
+ export declare function createReactNativePermissionsAccess(permissions: ReactNativePermissions, name: AndroidPermissionName, options?: ReactNativePermissionsOptions): PermissionAccess;
24
+ export {};
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createReactNativePermissionsAccess = createReactNativePermissionsAccess;
4
+ const react_native_1 = require("react-native");
5
+ const android_permission_1 = require("../permissions/android-permission");
6
+ const status_1 = require("../permissions/status");
7
+ const IOS_NAMES = {
8
+ camera: "CAMERA",
9
+ microphone: "MICROPHONE",
10
+ contacts: "CONTACTS",
11
+ "location-when-in-use": "LOCATION_WHEN_IN_USE",
12
+ photos: "PHOTO_LIBRARY",
13
+ };
14
+ /**
15
+ * A permission on iOS through react-native-permissions (an optional peer dependency, with each permission's native part
16
+ * set up in the Podfile), and on Android through `androidPermission`. Call it once per permission:
17
+ *
18
+ * ```ts
19
+ * import * as permissions from "react-native-permissions";
20
+ * import { createReactNativePermissionsAccess } from "@codual/react-native-ui/react-native-permissions";
21
+ * const camera = createReactNativePermissionsAccess(permissions, "camera");
22
+ * ```
23
+ */
24
+ function createReactNativePermissionsAccess(permissions, name, options = {}) {
25
+ const { notificationOptions = ["alert", "badge", "sound"], ...androidOptions } = options;
26
+ if (react_native_1.Platform.OS !== "ios")
27
+ return withSettingsPage((0, android_permission_1.androidPermission)(name, androidOptions), permissions, name);
28
+ return name === "notifications"
29
+ ? notificationsAccess(permissions, notificationOptions)
30
+ : iosAccess(permissions, name);
31
+ }
32
+ /** Android's adapter, opening the permission's own page in Settings, which React Native alone can't name. */
33
+ function withSettingsPage(access, permissions, name) {
34
+ const page = name === "notifications" ? "notifications" : "application";
35
+ return {
36
+ id: access.id,
37
+ get canAskForFullAccess() {
38
+ return access.canAskForFullAccess ?? false;
39
+ },
40
+ status: () => access.status(),
41
+ request: () => access.request(),
42
+ openSettings: () => permissions.openSettings(page),
43
+ };
44
+ }
45
+ function iosAccess(permissions, name) {
46
+ const permission = permissions.PERMISSIONS.IOS[IOS_NAMES[name]];
47
+ const read = async (answer) => {
48
+ const status = iosStatus(answer, permission);
49
+ if (name !== "location-when-in-use" || status !== status_1.GRANTED)
50
+ return status;
51
+ return (await permissions.checkLocationAccuracy()) === "reduced" ? status_1.LIMITED : status_1.GRANTED;
52
+ };
53
+ return {
54
+ id: name === "location-when-in-use" ? "location.whenInUse" : name,
55
+ status: async () => read(await permissions.check(permission)),
56
+ request: async () => read(await permissions.request(permission)),
57
+ openSettings: () => permissions.openSettings("application"),
58
+ };
59
+ }
60
+ function notificationsAccess(permissions, notificationOptions) {
61
+ // react-native-permissions answers limited for App Clip (ephemeral) notifications.
62
+ const read = ({ status, settings }) => (status === "granted" && settings.provisional) || status === "limited"
63
+ ? status_1.PROVISIONAL
64
+ : iosStatus(status, "notifications");
65
+ return {
66
+ id: "notifications",
67
+ canAskForFullAccess: true,
68
+ status: async () => read(await permissions.checkNotifications()),
69
+ request: async () => read(await permissions.requestNotifications([...notificationOptions])),
70
+ openSettings: () => permissions.openSettings("notifications"),
71
+ };
72
+ }
73
+ /** react-native-permissions on iOS: "denied" is never asked yet, and "unavailable" covers restricted too. */
74
+ function iosStatus(answer, permission) {
75
+ switch (answer) {
76
+ case "denied":
77
+ return status_1.NOT_DETERMINED;
78
+ case "granted":
79
+ return status_1.GRANTED;
80
+ case "limited":
81
+ return status_1.LIMITED;
82
+ case "blocked":
83
+ return status_1.BLOCKED;
84
+ case "unavailable":
85
+ return (0, status_1.unavailable)(`react-native-permissions reports ${permission} unavailable: set it up in the Podfile (setup_permissions), ` +
86
+ "or the device restricts it.");
87
+ }
88
+ }
@@ -0,0 +1,38 @@
1
+ import { type ReactElement, type ReactNode } from "react";
2
+ import { type RefreshControlProps, type ScrollViewProps } from "react-native";
3
+ import { type Load } from "./machine";
4
+ import { type ScreenStatesLabels } from "./system-views";
5
+ import { type ScreenStatesController, type ScreenStatesOptions } from "./use-screen-states";
6
+ export interface ScreenStatesProps<T> extends ScreenStatesOptions<T>, ScreenStatesViews<T> {
7
+ readonly load: Load<T>;
8
+ }
9
+ /** The app's views for each state; any it leaves out is a plain system one. */
10
+ export interface ScreenStatesViews<T> {
11
+ /** The loaded data. Pass `refreshControl` to your list or scroll view so it can be pulled to refresh. */
12
+ readonly content: (value: T, refreshControl: ReactElement<RefreshControlProps>) => ReactNode;
13
+ readonly loading?: () => ReactNode;
14
+ readonly empty?: () => ReactNode;
15
+ readonly failed?: (error: unknown, retry: () => void) => ReactNode;
16
+ readonly offline?: (retry: () => void) => ReactNode;
17
+ /** A refresh that failed while content was shown, over the content. By default, a system alert. */
18
+ readonly refreshError?: (error: unknown, dismiss: () => void) => ReactNode;
19
+ /** The text of the views you leave out. */
20
+ readonly labels?: Partial<ScreenStatesLabels>;
21
+ }
22
+ /**
23
+ * A screen that loads data, shown through the app's own views: loading, then content, empty, failed or offline.
24
+ * It loads on mount, aborts on unmount, retries from the failed and offline views and refreshes on pull, keeping
25
+ * the current view on screen. A view the app leaves out is a plain system one.
26
+ */
27
+ export declare function ScreenStates<T>(props: ScreenStatesProps<T>): import("react").JSX.Element;
28
+ /** The views of a screen state, for `ScreenStates` and the behaviors built on it. */
29
+ export declare function ScreenStatesView<T>({ views: props, screen, focusWhenLoaded, pullToRefreshProps, }: {
30
+ readonly views: ScreenStatesViews<T>;
31
+ readonly screen: ScreenStatesController<T>;
32
+ /** `stay` leaves the screen reader where it is, for a behavior whose field keeps focus, such as search. */
33
+ readonly focusWhenLoaded?: FocusWhenLoaded;
34
+ /** For the scroll view around the empty, failed and offline views: search's keyboard dismissal, say. */
35
+ readonly pullToRefreshProps?: ScrollViewProps | undefined;
36
+ }): import("react").JSX.Element;
37
+ /** Whether the screen reader moves to the view that replaced the spinner, once loading ends. */
38
+ export type FocusWhenLoaded = "move" | "stay";
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScreenStates = ScreenStates;
4
+ exports.ScreenStatesView = ScreenStatesView;
5
+ const jsx_runtime_1 = require("react/jsx-runtime");
6
+ const react_1 = require("react");
7
+ const react_native_1 = require("react-native");
8
+ const machine_1 = require("./machine");
9
+ const system_views_1 = require("./system-views");
10
+ const use_screen_states_1 = require("./use-screen-states");
11
+ const styles = react_native_1.StyleSheet.create({ screen: { flex: 1 }, fill: { flexGrow: 1 } });
12
+ /**
13
+ * A screen that loads data, shown through the app's own views: loading, then content, empty, failed or offline.
14
+ * It loads on mount, aborts on unmount, retries from the failed and offline views and refreshes on pull, keeping
15
+ * the current view on screen. A view the app leaves out is a plain system one.
16
+ */
17
+ function ScreenStates(props) {
18
+ const { load, isEmpty, isOffline } = props;
19
+ const screen = (0, use_screen_states_1.useScreenStates)(load, { ...(isEmpty && { isEmpty }), ...(isOffline && { isOffline }) });
20
+ return (0, jsx_runtime_1.jsx)(ScreenStatesView, { views: props, screen: screen });
21
+ }
22
+ /** The views of a screen state, for `ScreenStates` and the behaviors built on it. */
23
+ function ScreenStatesView({ views: props, screen, focusWhenLoaded = "move", pullToRefreshProps, }) {
24
+ const labels = { ...system_views_1.defaultScreenStatesLabels, ...props.labels };
25
+ const refreshControl = (0, jsx_runtime_1.jsx)(react_native_1.RefreshControl, { refreshing: screen.isRefreshing, onRefresh: screen.refresh });
26
+ const { refreshError, dismissRefreshError } = screen;
27
+ const view = useFocusWhenLoadingEnds((0, machine_1.isShowingLoading)(screen.state), focusWhenLoaded);
28
+ return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { ref: view, style: styles.screen, children: stateView(props, screen, labels, refreshControl, (view) => ((0, jsx_runtime_1.jsx)(PullToRefresh, { refreshControl: refreshControl, scrollViewProps: pullToRefreshProps, children: view }))) }), refreshError === undefined
29
+ ? null
30
+ : refreshErrorView(props, refreshError.error, dismissRefreshError, labels)] }));
31
+ }
32
+ /** Moves the screen reader to the view that replaced the spinner, once loading ends. */
33
+ function useFocusWhenLoadingEnds(isLoading, focusWhenLoaded) {
34
+ const view = (0, react_1.useRef)(null);
35
+ const wasLoading = (0, react_1.useRef)(isLoading);
36
+ (0, react_1.useEffect)(() => {
37
+ if (focusWhenLoaded === "move" && wasLoading.current && !isLoading && view.current) {
38
+ react_native_1.AccessibilityInfo.sendAccessibilityEvent(view.current, "focus");
39
+ }
40
+ wasLoading.current = isLoading;
41
+ }, [isLoading, focusWhenLoaded]);
42
+ return view;
43
+ }
44
+ /** The app's view for the current state, or the system one. */
45
+ function stateView(props, { state, retry }, labels, refreshControl, pullable) {
46
+ // A slot the app passes is used even when it renders nothing.
47
+ switch (state.status) {
48
+ case "idle":
49
+ case "loading":
50
+ return props.loading ? props.loading() : (0, jsx_runtime_1.jsx)(system_views_1.SystemLoadingView, { labels: labels });
51
+ case "content":
52
+ return props.content(state.value, refreshControl);
53
+ case "empty":
54
+ return pullable(props.empty ? props.empty() : (0, jsx_runtime_1.jsx)(system_views_1.SystemEmptyView, { labels: labels }));
55
+ case "failed":
56
+ return pullable(props.failed ? (props.failed(state.error, retry)) : ((0, jsx_runtime_1.jsx)(system_views_1.SystemFailedView, { error: state.error, retry: retry, labels: labels })));
57
+ case "offline":
58
+ return pullable(props.offline ? props.offline(retry) : (0, jsx_runtime_1.jsx)(system_views_1.SystemOfflineView, { retry: retry, labels: labels }));
59
+ }
60
+ }
61
+ function refreshErrorView(props, error, dismiss, labels) {
62
+ if (props.refreshError)
63
+ return props.refreshError(error, dismiss);
64
+ return (0, jsx_runtime_1.jsx)(system_views_1.SystemRefreshErrorAlert, { error: error, dismiss: dismiss, labels: labels });
65
+ }
66
+ /** A full-size scroll view, so a view that may not scroll can still be pulled to refresh. */
67
+ function PullToRefresh(props) {
68
+ return ((0, jsx_runtime_1.jsx)(react_native_1.ScrollView, { ...props.scrollViewProps, testID: "screen-states-pull-to-refresh", contentContainerStyle: styles.fill, refreshControl: props.refreshControl, children: props.children }));
69
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Whether a load failed for lack of a connection: the `TypeError` that `fetch` throws when no response arrives.
3
+ * `ScreenStates` shows the offline view for these errors unless the app passes its own `isOffline`.
4
+ */
5
+ export declare function isOfflineError(error: unknown): boolean;
6
+ /** Whether a load ended in an `AbortError`, the error an aborted `AbortSignal` makes `fetch` throw. */
7
+ export declare function isAbortError(error: unknown): boolean;
8
+ /** The error's own message, if it has one worth showing: never an abort's. */
9
+ export declare function errorMessage(error: unknown): string | undefined;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOfflineError = isOfflineError;
4
+ exports.isAbortError = isAbortError;
5
+ exports.errorMessage = errorMessage;
6
+ // The message React Native's `fetch` rejects with when no response arrives.
7
+ const NETWORK_REQUEST_FAILED = "Network request failed";
8
+ /**
9
+ * Whether a load failed for lack of a connection: the `TypeError` that `fetch` throws when no response arrives.
10
+ * `ScreenStates` shows the offline view for these errors unless the app passes its own `isOffline`.
11
+ */
12
+ function isOfflineError(error) {
13
+ return error instanceof TypeError && error.message === NETWORK_REQUEST_FAILED;
14
+ }
15
+ /** Whether a load ended in an `AbortError`, the error an aborted `AbortSignal` makes `fetch` throw. */
16
+ function isAbortError(error) {
17
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
18
+ }
19
+ /** The error's own message, if it has one worth showing: never an abort's. */
20
+ function errorMessage(error) {
21
+ if (isAbortError(error))
22
+ return undefined;
23
+ return error instanceof Error && error.message !== "" ? error.message : undefined;
24
+ }
@@ -0,0 +1,97 @@
1
+ /** Which view a screen that loads data shows. `idle`: nothing has loaded and no load runs; it shows loading. */
2
+ export type ScreenState<T> = {
3
+ readonly status: "idle";
4
+ } | {
5
+ readonly status: "loading";
6
+ } | {
7
+ readonly status: "content";
8
+ readonly value: T;
9
+ } | {
10
+ readonly status: "empty";
11
+ } | {
12
+ readonly status: "failed";
13
+ readonly error: unknown;
14
+ } | {
15
+ readonly status: "offline";
16
+ };
17
+ /** Whether the state shows the loading view: nothing loaded yet, or the first load or a retry running. */
18
+ export declare function isShowingLoading(state: ScreenState<unknown>): boolean;
19
+ /** A refresh that failed while content was shown. The content stays; the next successful load clears it. */
20
+ export interface RefreshError {
21
+ readonly error: unknown;
22
+ }
23
+ export interface ScreenStatesSnapshot<T> {
24
+ readonly state: ScreenState<T>;
25
+ /** A pull to refresh is running; the current view stays on screen until it finishes. */
26
+ readonly isRefreshing: boolean;
27
+ readonly refreshError: RefreshError | undefined;
28
+ }
29
+ /** Fetches the data. Abort the work when `signal` aborts: the screen went away and the result is dropped. */
30
+ export type Load<T> = (signal: AbortSignal) => Promise<T>;
31
+ export interface ScreenStatesSource<T> {
32
+ readonly load: Load<T>;
33
+ readonly isEmpty: (value: T) => boolean;
34
+ readonly isOffline: (error: unknown) => boolean;
35
+ }
36
+ /**
37
+ * The state machine behind `useScreenStates`. One load runs at a time, and it belongs to the machine, not to a
38
+ * view; only `disappear()` cancels it. `source` is read when a load starts and ends, so it can change between
39
+ * renders.
40
+ */
41
+ export declare class ScreenStatesMachine<T> {
42
+ private readonly source;
43
+ private snapshot;
44
+ private readonly listeners;
45
+ private running;
46
+ private generation;
47
+ /** Set by `reload()`: the running load is for a new input, so its failure replaces the content. */
48
+ private failureReplacesContent;
49
+ constructor(source: () => ScreenStatesSource<T>);
50
+ readonly subscribe: (listener: () => void) => (() => void);
51
+ readonly getSnapshot: () => ScreenStatesSnapshot<T>;
52
+ /** Starts the first load. Safe to call on every mount: once a load has started or finished, it does nothing. */
53
+ readonly appear: () => void;
54
+ /** Aborts the running load and drops its result. If nothing had loaded, the next appear loads again. */
55
+ readonly disappear: () => void;
56
+ /** Loads again from the failed or offline view, showing loading meanwhile. Does nothing in any other state. */
57
+ readonly retry: () => void;
58
+ /**
59
+ * Loads again while the current view stays on screen, resolving when the load finishes. While the first load or
60
+ * a retry runs, it waits for that load instead of starting another.
61
+ */
62
+ readonly refresh: () => Promise<void>;
63
+ /** Clears the refresh error, once the app has shown it. */
64
+ readonly dismissRefreshError: () => void;
65
+ /**
66
+ * Shows a value the app already has, as if the first load had given it, so appearing loads nothing. For a
67
+ * behavior built on this one, such as a paged list given its first page. Does nothing once a load has started.
68
+ */
69
+ showLoaded(value: T): void;
70
+ /**
71
+ * Replaces the value shown, for a behavior built on this one, such as a paged list adding a page. Does nothing
72
+ * unless content is shown.
73
+ */
74
+ replaceContent(value: T): void;
75
+ /**
76
+ * Replaces what is shown with another value the app already has, as content or the empty view: for a behavior
77
+ * built on this one, such as search filtering changed items in memory. Does nothing while the loading view shows.
78
+ */
79
+ replaceLoaded(value: T): void;
80
+ /** Whether a load is running, for a behavior built on this one. */
81
+ get isLoadRunning(): boolean;
82
+ /**
83
+ * Aborts the running load, drops its result and loads again for a new input, for a behavior built on this one
84
+ * (a chart's range). Content stays on screen meanwhile and anything else shows loading. Unlike a refresh's, its
85
+ * failure replaces the content, which belongs to the old input.
86
+ */
87
+ reload(): void;
88
+ private start;
89
+ private launch;
90
+ private succeed;
91
+ private fail;
92
+ /** Ends the load `id`, unless a newer load or the screen going away has replaced it. */
93
+ private finish;
94
+ private failure;
95
+ private failedState;
96
+ private update;
97
+ }
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScreenStatesMachine = void 0;
4
+ exports.isShowingLoading = isShowingLoading;
5
+ /** Whether the state shows the loading view: nothing loaded yet, or the first load or a retry running. */
6
+ function isShowingLoading(state) {
7
+ return state.status === "idle" || state.status === "loading";
8
+ }
9
+ const INITIAL = {
10
+ state: { status: "idle" },
11
+ isRefreshing: false,
12
+ refreshError: undefined,
13
+ };
14
+ /**
15
+ * The state machine behind `useScreenStates`. One load runs at a time, and it belongs to the machine, not to a
16
+ * view; only `disappear()` cancels it. `source` is read when a load starts and ends, so it can change between
17
+ * renders.
18
+ */
19
+ class ScreenStatesMachine {
20
+ source;
21
+ snapshot = INITIAL;
22
+ listeners = new Set();
23
+ running;
24
+ generation = 0;
25
+ /** Set by `reload()`: the running load is for a new input, so its failure replaces the content. */
26
+ failureReplacesContent = false;
27
+ constructor(source) {
28
+ this.source = source;
29
+ }
30
+ subscribe = (listener) => {
31
+ this.listeners.add(listener);
32
+ return () => this.listeners.delete(listener);
33
+ };
34
+ getSnapshot = () => this.snapshot;
35
+ /** Starts the first load. Safe to call on every mount: once a load has started or finished, it does nothing. */
36
+ appear = () => {
37
+ if (this.snapshot.state.status !== "idle")
38
+ return;
39
+ this.update({ state: { status: "loading" } });
40
+ this.start();
41
+ };
42
+ /** Aborts the running load and drops its result. If nothing had loaded, the next appear loads again. */
43
+ disappear = () => {
44
+ this.running?.controller.abort();
45
+ this.running = undefined;
46
+ this.generation += 1;
47
+ const isLoading = this.snapshot.state.status === "loading";
48
+ this.update({ isRefreshing: false, ...(isLoading ? { state: { status: "idle" } } : {}) });
49
+ };
50
+ /** Loads again from the failed or offline view, showing loading meanwhile. Does nothing in any other state. */
51
+ retry = () => {
52
+ const { status } = this.snapshot.state;
53
+ if (status !== "failed" && status !== "offline")
54
+ return;
55
+ this.update({ state: { status: "loading" } });
56
+ // A refresh from the failed view may already be running; the retry waits for it instead of loading twice.
57
+ if (this.running === undefined)
58
+ this.start();
59
+ };
60
+ /**
61
+ * Loads again while the current view stays on screen, resolving when the load finishes. While the first load or
62
+ * a retry runs, it waits for that load instead of starting another.
63
+ */
64
+ refresh = async () => {
65
+ if (this.snapshot.state.status === "idle")
66
+ return;
67
+ this.update({ isRefreshing: true });
68
+ await (this.running ?? this.start()).done;
69
+ };
70
+ /** Clears the refresh error, once the app has shown it. */
71
+ dismissRefreshError = () => {
72
+ this.update({ refreshError: undefined });
73
+ };
74
+ /**
75
+ * Shows a value the app already has, as if the first load had given it, so appearing loads nothing. For a
76
+ * behavior built on this one, such as a paged list given its first page. Does nothing once a load has started.
77
+ */
78
+ showLoaded(value) {
79
+ if (this.snapshot.state.status !== "idle")
80
+ return;
81
+ const state = this.source().isEmpty(value)
82
+ ? { status: "empty" }
83
+ : { status: "content", value };
84
+ this.update({ state });
85
+ }
86
+ /**
87
+ * Replaces the value shown, for a behavior built on this one, such as a paged list adding a page. Does nothing
88
+ * unless content is shown.
89
+ */
90
+ replaceContent(value) {
91
+ if (this.snapshot.state.status === "content")
92
+ this.update({ state: { status: "content", value } });
93
+ }
94
+ /**
95
+ * Replaces what is shown with another value the app already has, as content or the empty view: for a behavior
96
+ * built on this one, such as search filtering changed items in memory. Does nothing while the loading view shows.
97
+ */
98
+ replaceLoaded(value) {
99
+ if (isShowingLoading(this.snapshot.state))
100
+ return;
101
+ const state = this.source().isEmpty(value)
102
+ ? { status: "empty" }
103
+ : { status: "content", value };
104
+ this.update({ state });
105
+ }
106
+ /** Whether a load is running, for a behavior built on this one. */
107
+ get isLoadRunning() {
108
+ return this.running !== undefined;
109
+ }
110
+ /**
111
+ * Aborts the running load, drops its result and loads again for a new input, for a behavior built on this one
112
+ * (a chart's range). Content stays on screen meanwhile and anything else shows loading. Unlike a refresh's, its
113
+ * failure replaces the content, which belongs to the old input.
114
+ */
115
+ reload() {
116
+ this.running?.controller.abort();
117
+ const isShowingContent = this.snapshot.state.status === "content";
118
+ this.update({ isRefreshing: false, ...(isShowingContent ? {} : { state: { status: "loading" } }) });
119
+ this.failureReplacesContent = true;
120
+ this.launch();
121
+ }
122
+ start() {
123
+ this.failureReplacesContent = false;
124
+ return this.launch();
125
+ }
126
+ launch() {
127
+ this.generation += 1;
128
+ const id = this.generation;
129
+ const controller = new AbortController();
130
+ const { load } = this.source();
131
+ // The executor runs `load` now and turns a synchronous throw into a failed load.
132
+ const done = new Promise((resolve) => resolve(load(controller.signal))).then((value) => this.succeed(value, id), (error) => this.fail(error, id));
133
+ this.running = { controller, done };
134
+ return this.running;
135
+ }
136
+ succeed(value, id) {
137
+ if (!this.finish(id))
138
+ return;
139
+ const state = this.source().isEmpty(value)
140
+ ? { status: "empty" }
141
+ : { status: "content", value };
142
+ this.update({ state, isRefreshing: false, refreshError: undefined });
143
+ }
144
+ fail(error, id) {
145
+ if (!this.finish(id))
146
+ return;
147
+ this.update({ isRefreshing: false, ...this.failure(error) });
148
+ }
149
+ /** Ends the load `id`, unless a newer load or the screen going away has replaced it. */
150
+ finish(id) {
151
+ if (id !== this.generation)
152
+ return false;
153
+ this.running = undefined;
154
+ return true;
155
+ }
156
+ failure(error) {
157
+ // Only this load's own signal cancels it, and the screen going away drops that result before it gets here, so
158
+ // every failure is shown, an abort the app's own load makes included.
159
+ if (this.snapshot.state.status === "content" && !this.failureReplacesContent)
160
+ return { refreshError: { error } };
161
+ return { state: this.failedState(error) };
162
+ }
163
+ failedState(error) {
164
+ return this.source().isOffline(error) ? { status: "offline" } : { status: "failed", error };
165
+ }
166
+ update(change) {
167
+ this.snapshot = { ...this.snapshot, ...change };
168
+ for (const listener of this.listeners)
169
+ listener();
170
+ }
171
+ }
172
+ exports.ScreenStatesMachine = ScreenStatesMachine;
@@ -0,0 +1,40 @@
1
+ /** The text of the views `ScreenStates` shows for the ones an app leaves out. Pass `labels` to translate it. */
2
+ export interface ScreenStatesLabels {
3
+ readonly loading: string;
4
+ readonly empty: string;
5
+ readonly failed: string;
6
+ readonly failedMessage: string;
7
+ readonly offline: string;
8
+ readonly offlineMessage: string;
9
+ readonly tryAgain: string;
10
+ readonly refreshFailed: string;
11
+ readonly ok: string;
12
+ }
13
+ export declare const defaultScreenStatesLabels: ScreenStatesLabels;
14
+ export declare function SystemLoadingView({ labels }: {
15
+ readonly labels: ScreenStatesLabels;
16
+ }): import("react").JSX.Element;
17
+ export declare function SystemEmptyView({ labels }: {
18
+ readonly labels: ScreenStatesLabels;
19
+ }): import("react").JSX.Element;
20
+ export declare function SystemFailedView(props: {
21
+ readonly error: unknown;
22
+ readonly retry: () => void;
23
+ readonly labels: ScreenStatesLabels;
24
+ }): import("react").JSX.Element;
25
+ export declare function SystemOfflineView({ retry, labels, }: {
26
+ readonly retry: () => void;
27
+ readonly labels: ScreenStatesLabels;
28
+ }): import("react").JSX.Element;
29
+ /**
30
+ * Shows a refresh error as a system alert, once per error even when React runs the effect twice (Strict Mode), and
31
+ * dismisses it when the alert closes. Renders nothing. A native alert can't be closed from code, so one still open
32
+ * when the screen goes away stays until the person closes it; dismissing it then changes nothing.
33
+ */
34
+ export declare function SystemRefreshErrorAlert(props: {
35
+ readonly error: unknown;
36
+ readonly dismiss: () => void;
37
+ readonly labels: ScreenStatesLabels;
38
+ }): null;
39
+ /** What an alert says about a failure: no connection, the error's own message, or that something went wrong. */
40
+ export declare function failureMessage(error: unknown, labels: Pick<ScreenStatesLabels, "offlineMessage" | "failedMessage">): string;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultScreenStatesLabels = void 0;
4
+ exports.SystemLoadingView = SystemLoadingView;
5
+ exports.SystemEmptyView = SystemEmptyView;
6
+ exports.SystemFailedView = SystemFailedView;
7
+ exports.SystemOfflineView = SystemOfflineView;
8
+ exports.SystemRefreshErrorAlert = SystemRefreshErrorAlert;
9
+ exports.failureMessage = failureMessage;
10
+ const jsx_runtime_1 = require("react/jsx-runtime");
11
+ const react_1 = require("react");
12
+ const react_native_1 = require("react-native");
13
+ const errors_1 = require("./errors");
14
+ exports.defaultScreenStatesLabels = {
15
+ loading: "Loading",
16
+ empty: "Nothing Here Yet",
17
+ failed: "Couldn't Load",
18
+ failedMessage: "Something went wrong. Try again in a moment.",
19
+ offline: "No Internet Connection",
20
+ offlineMessage: "Check your internet connection, then try again.",
21
+ tryAgain: "Try Again",
22
+ refreshFailed: "Couldn't Refresh",
23
+ ok: "OK",
24
+ };
25
+ // System components only, with no styles of their own.
26
+ function SystemLoadingView({ labels }) {
27
+ return (0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { accessible: true, accessibilityRole: "progressbar", accessibilityLabel: labels.loading });
28
+ }
29
+ function SystemEmptyView({ labels }) {
30
+ return (0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "header", children: labels.empty });
31
+ }
32
+ function MessageView({ title, message, retry, labels }) {
33
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "header", children: title }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { children: message }), (0, jsx_runtime_1.jsx)(react_native_1.Button, { title: labels.tryAgain, onPress: retry })] }));
34
+ }
35
+ function SystemFailedView(props) {
36
+ const { error, retry, labels } = props;
37
+ const message = (0, errors_1.errorMessage)(error) ?? labels.failedMessage;
38
+ return (0, jsx_runtime_1.jsx)(MessageView, { title: labels.failed, message: message, retry: retry, labels: labels });
39
+ }
40
+ function SystemOfflineView({ retry, labels, }) {
41
+ return (0, jsx_runtime_1.jsx)(MessageView, { title: labels.offline, message: labels.offlineMessage, retry: retry, labels: labels });
42
+ }
43
+ /**
44
+ * Shows a refresh error as a system alert, once per error even when React runs the effect twice (Strict Mode), and
45
+ * dismisses it when the alert closes. Renders nothing. A native alert can't be closed from code, so one still open
46
+ * when the screen goes away stays until the person closes it; dismissing it then changes nothing.
47
+ */
48
+ function SystemRefreshErrorAlert(props) {
49
+ const { error, dismiss, labels } = props;
50
+ const message = failureMessage(error, labels);
51
+ const { refreshFailed, ok } = labels;
52
+ const alerted = (0, react_1.useRef)(undefined);
53
+ (0, react_1.useEffect)(() => {
54
+ if (alerted.current !== undefined && alerted.current.error === error)
55
+ return;
56
+ alerted.current = { error };
57
+ react_native_1.Alert.alert(refreshFailed, message, [{ text: ok, onPress: dismiss }], { onDismiss: dismiss });
58
+ }, [error, dismiss, message, refreshFailed, ok]);
59
+ return null;
60
+ }
61
+ /** What an alert says about a failure: no connection, the error's own message, or that something went wrong. */
62
+ function failureMessage(error, labels) {
63
+ if ((0, errors_1.isOfflineError)(error))
64
+ return labels.offlineMessage;
65
+ return (0, errors_1.errorMessage)(error) ?? labels.failedMessage;
66
+ }
@@ -0,0 +1,23 @@
1
+ import { type Load, type ScreenStatesSnapshot } from "./machine";
2
+ export interface ScreenStatesOptions<T> {
3
+ /** Whether a loaded value shows the empty view. By default, an array, `Map` or `Set` with no items. */
4
+ readonly isEmpty?: (value: T) => boolean;
5
+ /**
6
+ * Whether a failure shows the offline view. By default, `fetch`'s "Network request failed"; pass your own to
7
+ * use another client or a NetInfo check: `(error) => !netInfo.isConnected || isOfflineError(error)`.
8
+ */
9
+ readonly isOffline?: (error: unknown) => boolean;
10
+ }
11
+ export interface ScreenStatesController<T> extends ScreenStatesSnapshot<T> {
12
+ readonly retry: () => void;
13
+ readonly refresh: () => Promise<void>;
14
+ readonly dismissRefreshError: () => void;
15
+ }
16
+ /** Whether `value` is a collection with no items. */
17
+ export declare function isEmptyCollection(value: unknown): boolean;
18
+ /**
19
+ * The state of a screen that loads data, for apps that draw the states themselves. Loads on mount, aborts the load
20
+ * on unmount, and always calls the latest `load` and options. Give the component a new `key` to load again for a
21
+ * new input.
22
+ */
23
+ export declare function useScreenStates<T>(load: Load<T>, options?: ScreenStatesOptions<T>): ScreenStatesController<T>;