@indietabletop/appkit 3.2.0-1 → 3.2.0-3

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 (84) hide show
  1. package/lib/ExternalLink.tsx +10 -0
  2. package/lib/FormSubmitButton.tsx +48 -0
  3. package/lib/FullscreenDismissBlocker.tsx +23 -0
  4. package/lib/IndieTabletopClubLogo.tsx +44 -0
  5. package/lib/IndieTabletopClubSymbol.tsx +37 -0
  6. package/lib/Letterhead.tsx +33 -0
  7. package/lib/LetterheadFooter.tsx +36 -0
  8. package/lib/LoadingIndicator.tsx +39 -0
  9. package/lib/ServiceWorkerHandler.tsx +53 -0
  10. package/lib/animations.css.ts +17 -0
  11. package/lib/append-copy-to-text.ts +35 -0
  12. package/lib/async-op.ts +246 -0
  13. package/{dist/caught-value.js → lib/caught-value.ts} +10 -8
  14. package/lib/class-names.ts +8 -0
  15. package/lib/client.ts +288 -0
  16. package/lib/common.css.ts +46 -0
  17. package/lib/globals.css.ts +42 -0
  18. package/{dist/index.d.ts → lib/index.ts} +6 -0
  19. package/lib/internal.css.ts +26 -0
  20. package/lib/media.ts +50 -0
  21. package/lib/structs.ts +17 -0
  22. package/{dist/types.d.ts → lib/types.ts} +11 -6
  23. package/lib/use-async-op.ts +16 -0
  24. package/lib/use-document-background-color.ts +16 -0
  25. package/lib/use-form.ts +73 -0
  26. package/{dist/use-is-installed.js → lib/use-is-installed.ts} +7 -3
  27. package/lib/use-media-query.ts +21 -0
  28. package/lib/use-reverting-state.ts +32 -0
  29. package/lib/use-scroll-restoration.ts +99 -0
  30. package/package.json +5 -6
  31. package/dist/ExternalLink.d.ts +0 -3
  32. package/dist/ExternalLink.js +0 -4
  33. package/dist/FormSubmitButton.d.ts +0 -7
  34. package/dist/FormSubmitButton.js +0 -16
  35. package/dist/FullscreenDismissBlocker.d.ts +0 -5
  36. package/dist/FullscreenDismissBlocker.js +0 -19
  37. package/dist/IndieTabletopClubLogo.d.ts +0 -7
  38. package/dist/IndieTabletopClubLogo.js +0 -6
  39. package/dist/IndieTabletopClubSymbol.d.ts +0 -7
  40. package/dist/IndieTabletopClubSymbol.js +0 -5
  41. package/dist/Letterhead.d.ts +0 -6
  42. package/dist/Letterhead.js +0 -14
  43. package/dist/LetterheadFooter.d.ts +0 -1
  44. package/dist/LetterheadFooter.js +0 -17
  45. package/dist/LoadingIndicator.d.ts +0 -3
  46. package/dist/LoadingIndicator.js +0 -17
  47. package/dist/ServiceWorkerHandler.d.ts +0 -11
  48. package/dist/ServiceWorkerHandler.js +0 -42
  49. package/dist/animations.css.d.ts +0 -3
  50. package/dist/animations.css.js +0 -14
  51. package/dist/append-copy-to-text.d.ts +0 -10
  52. package/dist/append-copy-to-text.js +0 -29
  53. package/dist/async-op.d.ts +0 -87
  54. package/dist/async-op.js +0 -223
  55. package/dist/caught-value.d.ts +0 -15
  56. package/dist/class-names.d.ts +0 -4
  57. package/dist/class-names.js +0 -6
  58. package/dist/client.d.ts +0 -117
  59. package/dist/client.js +0 -201
  60. package/dist/common.css.d.ts +0 -5
  61. package/dist/common.css.js +0 -38
  62. package/dist/globals.css.d.ts +0 -1
  63. package/dist/globals.css.js +0 -35
  64. package/dist/index.js +0 -25
  65. package/dist/internal.css.d.ts +0 -4
  66. package/dist/internal.css.js +0 -21
  67. package/dist/media.d.ts +0 -39
  68. package/dist/media.js +0 -49
  69. package/dist/structs.d.ts +0 -20
  70. package/dist/structs.js +0 -15
  71. package/dist/types.js +0 -1
  72. package/dist/use-async-op.d.ts +0 -6
  73. package/dist/use-async-op.js +0 -12
  74. package/dist/use-document-background-color.d.ts +0 -4
  75. package/dist/use-document-background-color.js +0 -14
  76. package/dist/use-form.d.ts +0 -29
  77. package/dist/use-form.js +0 -33
  78. package/dist/use-is-installed.d.ts +0 -8
  79. package/dist/use-media-query.d.ts +0 -1
  80. package/dist/use-media-query.js +0 -15
  81. package/dist/use-reverting-state.d.ts +0 -5
  82. package/dist/use-reverting-state.js +0 -26
  83. package/dist/use-scroll-restoration.d.ts +0 -25
  84. package/dist/use-scroll-restoration.js +0 -67
package/lib/client.ts ADDED
@@ -0,0 +1,288 @@
1
+ import { type Infer, mask, object, string, Struct } from "superstruct";
2
+ import { Failure, Success } from "./async-op.js";
3
+ import { currentUser, sessionInfo } from "./structs.js";
4
+ import type { CurrentUser, FailurePayload, SessionInfo } from "./types.js";
5
+
6
+ export class IndieTabletopClient {
7
+ origin: string;
8
+ private onCurrentUser?: (currentUser: CurrentUser) => void;
9
+ private onSessionInfo?: (sessionInfo: SessionInfo) => void;
10
+ private onSessionExpired?: () => void;
11
+ private refreshTokenPromise?: Promise<
12
+ Success<{ sessionInfo: SessionInfo }> | Failure<FailurePayload>
13
+ >;
14
+
15
+ constructor(props: {
16
+ apiOrigin: string;
17
+
18
+ /**
19
+ * Runs every time the current user is fetched from the API. Typically, this
20
+ * happens during login, signup, and when the current user is fetched.
21
+ */
22
+ onCurrentUser?: (currentUser: CurrentUser) => void;
23
+
24
+ /**
25
+ * Runs ever time new session info is fetched from the API. Typically, this
26
+ * happends during login, signup, and when tokens are refreshed.
27
+ */
28
+ onSessionInfo?: (sessionInfo: SessionInfo) => void;
29
+
30
+ /**
31
+ * Runs when token refresh is attempted, but fails due to 401 error.
32
+ */
33
+ onSessionExpired?: () => void;
34
+ }) {
35
+ this.origin = props.apiOrigin;
36
+ this.onCurrentUser = props.onCurrentUser;
37
+ this.onSessionInfo = props.onSessionInfo;
38
+ this.onSessionExpired = props.onSessionExpired;
39
+ }
40
+
41
+ protected async fetch<T, S>(
42
+ path: string,
43
+ struct: Struct<T, S>,
44
+ init?: RequestInit & { json?: object },
45
+ ): Promise<Success<Infer<Struct<T, S>>> | Failure<FailurePayload>> {
46
+ // If json was provided, we stringify it. Otherwise we use body.
47
+ const body = init?.json ? JSON.stringify(init.json) : init?.body;
48
+
49
+ // If json was provided, we make sure that content type is correctly set.
50
+ const headers = init?.json
51
+ ? { ...init?.headers, "Content-Type": "application/json" }
52
+ : init?.headers;
53
+
54
+ try {
55
+ const res = await fetch(`${this.origin}${path}`, {
56
+ // Defaults
57
+ credentials: "include",
58
+
59
+ // Overrides
60
+ ...init,
61
+ body,
62
+ headers,
63
+ });
64
+
65
+ if (!res.ok) {
66
+ console.error(res);
67
+ return new Failure({ type: "API_ERROR", code: res.status });
68
+ }
69
+
70
+ try {
71
+ const data = mask(await res.json(), struct);
72
+ return new Success(data);
73
+ } catch (error) {
74
+ console.error(error);
75
+
76
+ return new Failure({ type: "VALIDATION_ERROR" });
77
+ }
78
+ } catch (error) {
79
+ console.error(error);
80
+
81
+ if (error instanceof Error) {
82
+ return new Failure({ type: "NETWORK_ERROR" });
83
+ }
84
+
85
+ return new Failure({ type: "UNKNOWN_ERROR" });
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Fetches data and retries 401 failures after attempting to refresh tokens.
91
+ */
92
+ protected async fetchWithAuth<T, S>(
93
+ path: string,
94
+ struct: Struct<T, S>,
95
+ init?: RequestInit & { json?: object },
96
+ ): Promise<Success<Infer<Struct<T, S>>> | Failure<FailurePayload>> {
97
+ const op = await this.fetch(path, struct, init);
98
+
99
+ if (op.isSuccess) {
100
+ return op;
101
+ }
102
+
103
+ if (op.failure.type === "API_ERROR" && op.failure.code === 401) {
104
+ console.info("API request failed with error 401. Refreshing tokens.");
105
+
106
+ const refreshOp = await this.refreshTokens();
107
+
108
+ if (refreshOp.isSuccess) {
109
+ console.info("Tokens refreshed. Retrying request.");
110
+ return await this.fetch(path, struct, init);
111
+ } else {
112
+ console.info("Could not refresh tokens.");
113
+ }
114
+ }
115
+
116
+ return op;
117
+ }
118
+
119
+ async login(payload: { email: string; password: string }) {
120
+ const result = await this.fetch(
121
+ "/v1/sessions",
122
+ object({
123
+ currentUser: currentUser(),
124
+ sessionInfo: sessionInfo(),
125
+ }),
126
+ {
127
+ method: "POST",
128
+ json: { email: payload.email, plaintextPassword: payload.password },
129
+ },
130
+ );
131
+
132
+ if (result.isSuccess) {
133
+ this.onCurrentUser?.(result.value.currentUser);
134
+ this.onSessionInfo?.(result.value.sessionInfo);
135
+ }
136
+
137
+ return result;
138
+ }
139
+
140
+ async logout() {
141
+ return await this.fetch("/v1/sessions", object({ message: string() }), {
142
+ method: "DELETE",
143
+ });
144
+ }
145
+
146
+ async join(payload: {
147
+ email: string;
148
+ password: string;
149
+ acceptedTos: boolean;
150
+ subscribedToNewsletter: boolean;
151
+ }) {
152
+ const res = await this.fetch(
153
+ "/v1/users",
154
+ object({
155
+ currentUser: currentUser(),
156
+ sessionInfo: sessionInfo(),
157
+ tokenId: string(),
158
+ }),
159
+ {
160
+ method: "POST",
161
+ json: {
162
+ email: payload.email,
163
+ plaintextPassword: payload.password,
164
+ acceptedTos: payload.acceptedTos,
165
+ subscribedToNewsletter: payload.subscribedToNewsletter,
166
+ },
167
+ },
168
+ );
169
+
170
+ if (res.isSuccess) {
171
+ this.onCurrentUser?.(res.value.currentUser);
172
+ this.onSessionInfo?.(res.value.sessionInfo);
173
+ }
174
+
175
+ return res;
176
+ }
177
+
178
+ /**
179
+ * Triggers token refresh process.
180
+ *
181
+ * Note that we do not want to perform multiple concurrent token refresh
182
+ * actions, as that will result in unnecessary 401s. For this reason, a
183
+ * reference to t
184
+ */
185
+ async refreshTokens() {
186
+ // If there is an ongoing token refresh in progress return that. This should
187
+ // only deal the response payload, none of the side-effects and cleanup,
188
+ // which will be handled by the initial invocation.
189
+ const ongoingRequest = this.refreshTokenPromise;
190
+
191
+ if (ongoingRequest) {
192
+ console.info("Token refresh ongoing. Reusing existing promise.");
193
+ return await ongoingRequest;
194
+ }
195
+
196
+ // Cache the promise on an instance property to share a reference from
197
+ // other potential invocations.
198
+ this.refreshTokenPromise = this.fetch(
199
+ "/v1/sessions/access-tokens",
200
+ object({ sessionInfo: sessionInfo() }),
201
+ { method: "POST" },
202
+ );
203
+
204
+ const result = await this.refreshTokenPromise;
205
+
206
+ if (result.isSuccess) {
207
+ this.onSessionInfo?.(result.value.sessionInfo);
208
+ }
209
+
210
+ if (
211
+ result.isFailure &&
212
+ result.failure.type === "API_ERROR" &&
213
+ result.failure.code === 401
214
+ ) {
215
+ this.onSessionExpired?.();
216
+ }
217
+
218
+ // Make sure to reset the shared reference so that subsequent invocations
219
+ // once again initiate token refresh.
220
+ delete this.refreshTokenPromise;
221
+
222
+ return result;
223
+ }
224
+
225
+ async requestPasswordReset(payload: { email: string }) {
226
+ return await this.fetch(
227
+ `/v1/password-reset-tokens`,
228
+ object({ message: string(), tokenId: string() }),
229
+ { method: "POST", json: payload },
230
+ );
231
+ }
232
+
233
+ async checkPasswordResetCode(payload: { tokenId: string; code: string }) {
234
+ const queryParams = new URLSearchParams({ plaintextCode: payload.code });
235
+ return await this.fetch(
236
+ `/v1/password-reset-tokens/${payload.tokenId}?${queryParams}`,
237
+ object({ message: string() }),
238
+ { method: "GET" },
239
+ );
240
+ }
241
+
242
+ async setNewPassword(payload: {
243
+ tokenId: string;
244
+ code: string;
245
+ password: string;
246
+ }) {
247
+ const queryParams = new URLSearchParams({ plaintextCode: payload.code });
248
+ return await this.fetch(
249
+ `/v1/password-reset-tokens/${payload.tokenId}?${queryParams}`,
250
+ object({ message: string() }),
251
+ { method: "PUT", json: { plaintextPassword: payload.password } },
252
+ );
253
+ }
254
+
255
+ async requestUserVerification() {
256
+ return await this.fetch(
257
+ `/v1/user-verification-tokens`,
258
+ object({ message: string(), tokenId: string() }),
259
+ { method: "POST" },
260
+ );
261
+ }
262
+
263
+ async verifyUser(payload: { tokenId: string; code: string }) {
264
+ const queryParams = new URLSearchParams({ plaintextCode: payload.code });
265
+ const req = await this.fetch(
266
+ `/v1/user-verification-tokens/${payload.tokenId}?${queryParams}`,
267
+ object({ message: string() }),
268
+ { method: "PUT" },
269
+ );
270
+
271
+ if (req.isSuccess) {
272
+ await this.refreshTokens();
273
+ await this.getCurrentUser();
274
+ }
275
+
276
+ return req;
277
+ }
278
+
279
+ async getCurrentUser() {
280
+ const result = await this.fetchWithAuth(`/v1/users/me`, currentUser());
281
+
282
+ if (result.isSuccess) {
283
+ this.onCurrentUser?.(result.value);
284
+ }
285
+
286
+ return result;
287
+ }
288
+ }
@@ -0,0 +1,46 @@
1
+ import { style } from "@vanilla-extract/css";
2
+ import { Hover, MinWidth } from "./media.ts";
3
+
4
+ export const itcSymbol = style({
5
+ inlineSize: "2.5rem",
6
+ blockSize: "2.5rem",
7
+ margin: "0rem auto 0.75rem",
8
+
9
+ "@media": {
10
+ [MinWidth.MEDIUM]: {
11
+ marginBlock: "-1rem 1.5rem",
12
+ },
13
+ },
14
+ });
15
+
16
+ export const manofa = style({
17
+ fontFamily: `"manofa", sans-serif`,
18
+ });
19
+
20
+ export const minion = style({
21
+ fontFamily: `"minion-pro", serif`,
22
+ });
23
+
24
+ export const itcCard = style([
25
+ minion,
26
+ {
27
+ backgroundColor: "white",
28
+ },
29
+ ]);
30
+
31
+ export const interactiveText = style({
32
+ display: "inline",
33
+ textDecoration: "underline",
34
+ textDecorationColor: "hsl(from currentcolor h s l / 0.3)",
35
+ textUnderlineOffset: "0.15em",
36
+
37
+ "@media": {
38
+ [Hover.HOVER]: {
39
+ transition: "text-decoration-color 200ms",
40
+
41
+ ":hover": {
42
+ textDecorationColor: "hsl(from currentcolor h s l / 1)",
43
+ },
44
+ },
45
+ },
46
+ });
@@ -0,0 +1,42 @@
1
+ import { globalStyle } from "@vanilla-extract/css";
2
+
3
+ globalStyle(":root", {
4
+ fontSynthesis: "none",
5
+ textRendering: "optimizeLegibility",
6
+ WebkitFontSmoothing: "antialiased",
7
+ MozOsxFontSmoothing: "grayscale",
8
+ });
9
+
10
+ globalStyle("*", {
11
+ boxSizing: "border-box",
12
+ });
13
+
14
+ globalStyle("img, picture, svg", {
15
+ display: "block",
16
+ });
17
+
18
+ globalStyle("a", {
19
+ display: "block",
20
+ color: "inherit",
21
+ textDecoration: "none",
22
+ });
23
+
24
+ globalStyle("input, textarea", {
25
+ fontFamily: "inherit",
26
+ });
27
+
28
+ globalStyle("button", {
29
+ display: "block",
30
+ fontSize: "inherit",
31
+ fontFamily: "inherit",
32
+ backgroundColor: "transparent",
33
+ border: "none",
34
+ color: "inherit",
35
+ cursor: "pointer",
36
+ padding: 0,
37
+ });
38
+
39
+ globalStyle("body, h1, h2, h3, h4, h5, h6, p, ul, li, ol", {
40
+ margin: 0,
41
+ padding: 0,
42
+ });
@@ -1,10 +1,14 @@
1
+ // Components
1
2
  export * from "./ExternalLink.tsx";
2
3
  export * from "./FormSubmitButton.tsx";
3
4
  export * from "./FullscreenDismissBlocker.tsx";
4
5
  export * from "./IndieTabletopClubSymbol.tsx";
6
+ export * from "./Letterhead.tsx";
5
7
  export * from "./LetterheadFooter.tsx";
6
8
  export * from "./LoadingIndicator.tsx";
7
9
  export * from "./ServiceWorkerHandler.tsx";
10
+
11
+ // Hooks
8
12
  export * from "./use-async-op.ts";
9
13
  export * from "./use-document-background-color.ts";
10
14
  export * from "./use-form.ts";
@@ -12,6 +16,8 @@ export * from "./use-is-installed.ts";
12
16
  export * from "./use-media-query.ts";
13
17
  export * from "./use-reverting-state.ts";
14
18
  export * from "./use-scroll-restoration.ts";
19
+
20
+ // Utils
15
21
  export * from "./append-copy-to-text.ts";
16
22
  export * from "./async-op.ts";
17
23
  export * from "./caught-value.ts";
@@ -0,0 +1,26 @@
1
+ import { createVar, style } from "@vanilla-extract/css";
2
+ import { bounce } from "./animations.css.ts";
3
+ import { minion } from "./common.css.ts";
4
+
5
+ export const animationDelay = createVar();
6
+
7
+ export const dot = style({
8
+ fill: "currentcolor",
9
+ opacity: 0.8,
10
+ animation: `${bounce} 2s ${animationDelay} infinite`,
11
+ });
12
+
13
+ export const padding = createVar();
14
+
15
+ export const letterhead = style([
16
+ minion,
17
+ {
18
+ vars: { [padding]: "clamp(1rem, 8vw, 4rem)" },
19
+
20
+ backgroundColor: "white",
21
+ padding: `max(1rem, calc(${padding} - .5rem)) ${padding} ${padding}`,
22
+ borderRadius: "1rem",
23
+ marginInline: "auto",
24
+ maxInlineSize: "36rem",
25
+ },
26
+ ]);
package/lib/media.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
3
+ */
4
+
5
+ export enum PrefersColorScheme {
6
+ LIGHT = "(prefers-color-scheme: light)",
7
+ DARK = "(prefers-color-scheme: dark)",
8
+ }
9
+ /**
10
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
11
+ */
12
+
13
+ export enum PrefersReducedMotion {
14
+ NO_PREFERENCE = "(prefers-reduced-motion: no-preference)",
15
+ REDUCE = "(prefers-reduced-motion: reduce)",
16
+ }
17
+
18
+ export enum Hover {
19
+ NONE = "(hover: none)",
20
+
21
+ // Some Samsung phones incorrectly report that they have "hover" even though they
22
+ // do not. Adding the pointer query correctly filters these phones out.
23
+ HOVER = "(hover: hover) and (pointer: fine)",
24
+ }
25
+
26
+ export enum MediaType {
27
+ PRINT = "print",
28
+ SCREEN = "screen",
29
+ }
30
+
31
+ export enum MinHeight {
32
+ TALL = "(min-height: 40em)",
33
+ }
34
+
35
+ export enum MinWidth {
36
+ SMALL = "(min-width: 28em)",
37
+ MEDIUM = "(min-width: 50em)",
38
+ WIDE = "(min-width: 66em)",
39
+ X_WIDE = "(min-width: 80em)",
40
+ XX_WIDE = "(min-width: 140em)",
41
+ }
42
+
43
+ export enum DisplayMode {
44
+ STANDALONE = "(display-mode: standalone)",
45
+ }
46
+
47
+ export enum Pointer {
48
+ COARSE = "(pointer: coarse)",
49
+ FINE = "(pointer: fine)",
50
+ }
package/lib/structs.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { boolean, enums, number, object, optional, string } from "superstruct";
2
+
3
+ export function currentUser() {
4
+ return object({
5
+ id: string(),
6
+ email: string(),
7
+ isVerified: boolean(),
8
+ prefersScrollbarVisibility: optional(enums(["ALWAYS"])),
9
+ });
10
+ }
11
+
12
+ export function sessionInfo() {
13
+ return object({
14
+ expiresTs: number(),
15
+ createdTs: number(),
16
+ });
17
+ }
@@ -1,10 +1,15 @@
1
1
  import type { Infer } from "superstruct";
2
2
  import { currentUser, sessionInfo } from "./structs.js";
3
+
3
4
  export type CurrentUser = Infer<ReturnType<typeof currentUser>>;
5
+
4
6
  export type SessionInfo = Infer<ReturnType<typeof sessionInfo>>;
5
- export type FailurePayload = {
6
- type: "API_ERROR";
7
- code: number;
8
- } | {
9
- type: "NETWORK_ERROR" | "UNKNOWN_ERROR" | "VALIDATION_ERROR";
10
- };
7
+
8
+ export type FailurePayload =
9
+ | {
10
+ type: "API_ERROR";
11
+ code: number;
12
+ }
13
+ | {
14
+ type: "NETWORK_ERROR" | "UNKNOWN_ERROR" | "VALIDATION_ERROR";
15
+ };
@@ -0,0 +1,16 @@
1
+ import { useCallback, useState } from "react";
2
+ import { type AsyncOp, Failure, Pending, Success } from "./async-op.js";
3
+
4
+ export function useAsyncOp<T, E>() {
5
+ const [op, setOp] = useState<AsyncOp<T, E>>(new Pending());
6
+
7
+ const setSuccess = useCallback((value: T) => {
8
+ setOp(new Success(value));
9
+ }, []);
10
+
11
+ const setFailure = useCallback((failure: E) => {
12
+ setOp(new Failure(failure));
13
+ }, []);
14
+
15
+ return { op, setSuccess, setFailure };
16
+ }
@@ -0,0 +1,16 @@
1
+ import { useEffect } from "react";
2
+
3
+ /**
4
+ * Sets document background color, reverting it to previous color on unmount.
5
+ */
6
+ export function useDocumentBackgroundColor(bodyColor: string) {
7
+ useEffect(() => {
8
+ const style = window.document.documentElement.style;
9
+ const originalColor = style.backgroundColor;
10
+ style.backgroundColor = bodyColor;
11
+
12
+ return () => {
13
+ style.backgroundColor = originalColor;
14
+ };
15
+ });
16
+ }
@@ -0,0 +1,73 @@
1
+ import { type FormStoreState, useFormStore } from "@ariakit/react";
2
+ import { useState } from "react";
3
+ import { Failure, Success } from "./async-op.ts";
4
+
5
+ type Validator<T> = (value: T) => string | null;
6
+
7
+ type MaybePromise<T> = T | Promise<T>;
8
+
9
+ export function useForm<T extends object, R>(props: {
10
+ defaultValues: T;
11
+ validate?: { [K in keyof T]?: Validator<T[K]> };
12
+
13
+ /**
14
+ * Handles form submission login.
15
+ *
16
+ * This function should return a Success or Failure. Failures should always contain a string
17
+ * which will be used as the form error message.
18
+ */
19
+ onSubmit: (
20
+ state: FormStoreState<T>,
21
+ ) => MaybePromise<Success<R> | Failure<string>>;
22
+
23
+ /**
24
+ * If submission was successful (i.e. onSubmit returned a Success), will be run to perform any
25
+ * side-effect necessary.
26
+ *
27
+ * Typically this is used for navigation on mutating some local state.
28
+ */
29
+ onSuccess?: (value: R, state: FormStoreState<T>) => MaybePromise<void>;
30
+ }) {
31
+ const submitName = "submit";
32
+
33
+ const [op, setOp] = useState<Awaited<
34
+ ReturnType<typeof props.onSubmit>
35
+ > | null>(null);
36
+
37
+ const form = useFormStore({
38
+ defaultValues: props.defaultValues,
39
+ });
40
+
41
+ form.useSubmit(async (state) => {
42
+ const submitOp = await props.onSubmit(state);
43
+
44
+ if (submitOp.isFailure) {
45
+ form.setError(submitName, submitOp.failure);
46
+ }
47
+
48
+ if (submitOp.isSuccess) {
49
+ await props.onSuccess?.(submitOp.value, state);
50
+ }
51
+
52
+ setOp(submitOp);
53
+ });
54
+
55
+ form.useValidate((state) => {
56
+ if (props.validate) {
57
+ const entries = Object.entries(props.validate) as Array<
58
+ [keyof T & string, Validator<T[keyof T]>]
59
+ >;
60
+
61
+ for (const [key, validate] of entries) {
62
+ const value = state.values[key];
63
+ const message = validate(value);
64
+
65
+ if (message) {
66
+ form.setError(key, message);
67
+ }
68
+ }
69
+ }
70
+ });
71
+
72
+ return { form, submitName, op };
73
+ }
@@ -1,4 +1,5 @@
1
1
  import { useMemo } from "react";
2
+
2
3
  /**
3
4
  * Checks whether the app is installed.
4
5
  *
@@ -7,7 +8,10 @@ import { useMemo } from "react";
7
8
  * or running within a browser.
8
9
  */
9
10
  export function useIsInstalled() {
10
- // The only way to get into the Standalone display mode is to install
11
- // the app, so this is a good way to check installation status.
12
- return useMemo(() => window.matchMedia("(display-mode: standalone)").matches, []);
11
+ // The only way to get into the Standalone display mode is to install
12
+ // the app, so this is a good way to check installation status.
13
+ return useMemo(
14
+ () => window.matchMedia("(display-mode: standalone)").matches,
15
+ [],
16
+ );
13
17
  }
@@ -0,0 +1,21 @@
1
+ import { useState, useEffect } from "react";
2
+
3
+ export function useMediaQuery(query: string) {
4
+ const [isMatch, setMatch] = useState(window.matchMedia(query).matches);
5
+
6
+ useEffect(() => {
7
+ const mql = window.matchMedia(query);
8
+
9
+ const handleChange = ({ matches }: MediaQueryListEvent): void => {
10
+ setMatch(matches);
11
+ };
12
+
13
+ mql.addEventListener("change", handleChange);
14
+
15
+ return () => {
16
+ mql.removeEventListener("change", handleChange);
17
+ };
18
+ }, [query]);
19
+
20
+ return isMatch;
21
+ }