@jayalfredprufrock/mobx-toolbox 0.7.1 → 0.8.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.
- package/README.md +55 -18
- package/dist/form.mjs +2 -2
- package/dist/form.mjs.map +1 -1
- package/dist/{lazy-observable-DXAOlMUT.mjs → lazy-observable-8dTdgRqO.mjs} +22 -2
- package/dist/lazy-observable-8dTdgRqO.mjs.map +1 -0
- package/dist/lazy-observable-CSsG7nEB.d.mts.map +1 -1
- package/dist/lazy-observable.mjs +1 -1
- package/dist/model.mjs +1 -1
- package/dist/react-util.d.mts +14 -3
- package/dist/react-util.d.mts.map +1 -1
- package/dist/react-util.mjs +3 -24
- package/dist/react-util.mjs.map +1 -1
- package/dist/table.d.mts +619 -0
- package/dist/table.d.mts.map +1 -0
- package/dist/table.mjs +1318 -0
- package/dist/table.mjs.map +1 -0
- package/dist/useResize-BhJdvtef.mjs +38 -0
- package/dist/useResize-BhJdvtef.mjs.map +1 -0
- package/package.json +2 -1
- package/dist/lazy-observable-DXAOlMUT.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# mobx-toolbox
|
|
2
2
|
|
|
3
|
-
A collection of MobX + React utilities: lazy-loading observables, model/store factories, a client-side router, form state management, dialog management, and general-purpose React hooks.
|
|
3
|
+
A collection of MobX + React utilities: lazy-loading observables, model/store factories, a client-side router, form state management, dialog management, a headless virtualized table, and general-purpose React hooks.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -8,19 +8,25 @@ A collection of MobX + React utilities: lazy-loading observables, model/store fa
|
|
|
8
8
|
pnpm add @jayalfredprufrock/mobx-toolbox mobx mobx-react-lite
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Peer dependencies
|
|
12
|
-
|
|
13
|
-
| Package | Required for |
|
|
14
|
-
| -------------------------- | ------------------------------------------------------------------- |
|
|
15
|
-
| `mobx` + `mobx-react-lite` | all modules |
|
|
16
|
-
| `typebox` | `form`, `model` |
|
|
17
|
-
| `history` | `router` |
|
|
18
|
-
| `react` | `dialog`, `form`, `lazy-observable`, `react-util`, `router`, `util` |
|
|
11
|
+
Peer dependencies are per-module — see the **Requires** column below. `typebox` and `history` are declared optional, so they are only pulled in if you reach for `form`/`model` or `router`.
|
|
19
12
|
|
|
20
13
|
---
|
|
21
14
|
|
|
22
15
|
## Modules
|
|
23
16
|
|
|
17
|
+
Each module is its own entry point — import from `@jayalfredprufrock/mobx-toolbox/<module>` so you only pull in what you use.
|
|
18
|
+
|
|
19
|
+
| Module | Summary | Requires |
|
|
20
|
+
| ------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------- |
|
|
21
|
+
| [`dialog`](#dialog) | Dialog/modal stack with state transitions for enter/exit animations | `mobx`, `mobx-react-lite`, `react` |
|
|
22
|
+
| [`form`](#form) | Schema-driven form state with TypeBox validation and submit lifecycle | `mobx`, `mobx-react-lite`, `react`, `typebox` |
|
|
23
|
+
| [`lazy-observable`](#lazy-observable) | Observables that fetch on first observation and reset when unobserved | `mobx`, `mobx-react-lite`, `react` |
|
|
24
|
+
| [`model`](#model) | Observable model classes and collection stores from TypeBox schemas | `mobx`, `typebox` |
|
|
25
|
+
| [`react-util`](#react-util) | General-purpose React hooks: async state, debouncing, resize, mount lifecycle | `react` |
|
|
26
|
+
| [`router`](#router) | Client-side router with symbol-keyed guards, loaders and layouts | `mobx`, `mobx-react-lite`, `react`, `history` |
|
|
27
|
+
| [`table`](#table) | Headless, virtualized data table | `mobx`, `mobx-react-lite`, `react` |
|
|
28
|
+
| [`util`](#util) | Small MobX + React utilities — `mutable`, `useAutorun` | `mobx`, `react` |
|
|
29
|
+
|
|
24
30
|
### [`dialog`](src/dialog/README.md)
|
|
25
31
|
|
|
26
32
|
MobX-powered dialog/modal stack with state-transition support for enter/exit animations.
|
|
@@ -115,6 +121,24 @@ await userStore.all.value[0].delete(); // removes from store too
|
|
|
115
121
|
|
|
116
122
|
---
|
|
117
123
|
|
|
124
|
+
### [`react-util`](src/react-util/README.md)
|
|
125
|
+
|
|
126
|
+
General-purpose React hooks: async state management, debouncing, resize observation, and mount lifecycle helpers.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { useAsync, useDebouncedCallback } from "@jayalfredprufrock/mobx-toolbox/react-util";
|
|
130
|
+
|
|
131
|
+
// Runs on mount; re-runs when deps change; handles loading/error/value
|
|
132
|
+
const state = useAsync(async (signal) => fetchUser(id), [id]);
|
|
133
|
+
|
|
134
|
+
// Stable debounced callback, safe to call after unmount
|
|
135
|
+
const save = useDebouncedCallback((value) => persist(value), []);
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
→ [Full docs](src/react-util/README.md)
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
118
142
|
### [`router`](src/router/README.md)
|
|
119
143
|
|
|
120
144
|
MobX-based client-side router for React. Routes are plain objects; symbol-keyed metadata controls guards, loaders, and layouts.
|
|
@@ -150,21 +174,34 @@ function App() {
|
|
|
150
174
|
|
|
151
175
|
---
|
|
152
176
|
|
|
153
|
-
### [`
|
|
177
|
+
### [`table`](src/table/README.md)
|
|
154
178
|
|
|
155
|
-
|
|
179
|
+
Headless, virtualized data table. The model owns columns, widths, sorting, selection, expansion and the render window; the components own only structure and ARIA.
|
|
156
180
|
|
|
157
|
-
```
|
|
158
|
-
import {
|
|
181
|
+
```tsx
|
|
182
|
+
import { useTable, Table } from "@jayalfredprufrock/mobx-toolbox/table";
|
|
159
183
|
|
|
160
|
-
|
|
161
|
-
const
|
|
184
|
+
function UserTable({ users }) {
|
|
185
|
+
const table = useTable({ rows: users, columns: ["name", "email", { selection: true }] });
|
|
162
186
|
|
|
163
|
-
|
|
164
|
-
|
|
187
|
+
return (
|
|
188
|
+
<Table.Root table={table}>
|
|
189
|
+
<Table.Header>
|
|
190
|
+
{(column) => <Table.ColumnHeader column={column}>{column.title}</Table.ColumnHeader>}
|
|
191
|
+
</Table.Header>
|
|
192
|
+
<Table.Body>
|
|
193
|
+
{(row) => (
|
|
194
|
+
<Table.Row row={row}>
|
|
195
|
+
{(column) => <Table.Cell column={column}>{String(column.getValue(row))}</Table.Cell>}
|
|
196
|
+
</Table.Row>
|
|
197
|
+
)}
|
|
198
|
+
</Table.Body>
|
|
199
|
+
</Table.Root>
|
|
200
|
+
);
|
|
201
|
+
}
|
|
165
202
|
```
|
|
166
203
|
|
|
167
|
-
→ [Full docs](src/
|
|
204
|
+
→ [Full docs](src/table/README.md)
|
|
168
205
|
|
|
169
206
|
---
|
|
170
207
|
|
package/dist/form.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Observer } from "mobx-react-lite";
|
|
2
2
|
import { createContext, forwardRef, useContext, useRef } from "react";
|
|
3
3
|
import { makeAutoObservable, toJS } from "mobx";
|
|
4
|
-
import { Fragment, jsx } from "react/jsx-runtime";
|
|
4
|
+
import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
|
|
5
5
|
import * as Format from "typebox/format";
|
|
6
6
|
import * as Value from "typebox/value";
|
|
7
7
|
import Schema, { Validator } from "typebox/schema";
|
|
@@ -44,7 +44,7 @@ function FormWhen({ form, field, value, children }) {
|
|
|
44
44
|
return /* @__PURE__ */ jsx(Observer, { children: () => {
|
|
45
45
|
const fields = form.rawFields;
|
|
46
46
|
if (fields[field]?.value !== value) return null;
|
|
47
|
-
return /* @__PURE__ */ jsx(Fragment, { children: children(fields) });
|
|
47
|
+
return /* @__PURE__ */ jsx(Fragment$1, { children: children(fields) });
|
|
48
48
|
} });
|
|
49
49
|
}
|
|
50
50
|
|
package/dist/form.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form.mjs","names":[],"sources":["../src/form/form.context.ts","../src/form/components/form.tsx","../src/form/components/form-when.tsx","../src/form/form-field.model.ts","../src/form/form.model.ts","../src/form/use-form.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport type { FormModel } from \"./form.model\";\n\nexport const formContext = createContext<FormModel | undefined>(undefined);\nexport const useFormContext = () => {\n const context = useContext(formContext);\n if (!context) {\n throw new Error(\n \"Form context not available. Make sure you are within the <Form> component or providing the form context manually.\",\n );\n }\n return context;\n};\n\nexport const FormProvider = formContext.Provider;\n\nexport const useFormContextIfAvailable = () => useContext(formContext);\n","import { forwardRef } from \"react\";\nimport { FormProvider } from \"../form.context\";\nimport type { FormModel } from \"../form.model\";\n\nexport interface MobxFormProps extends Omit<\n React.HTMLProps<HTMLFormElement>,\n \"form\" | \"action\" | \"method\"\n> {\n form: FormModel<any>;\n}\n\nexport const MobxForm = forwardRef(function MobxForm(\n { form, children, ...formProps }: MobxFormProps,\n ref,\n) {\n return (\n <FormProvider value={form}>\n <form noValidate {...formProps} ref={ref} {...form.props()}>\n {children}\n </form>\n </FormProvider>\n );\n});\n","import type { TUnion } from \"typebox\";\nimport { Observer } from \"mobx-react-lite\";\nimport type { FormModel } from \"../form.model\";\nimport type { FormFieldModel } from \"../form-field.model\";\nimport type {\n DiscriminatorKeys,\n DiscriminatorValue,\n FormFields,\n MatchVariant,\n} from \"../form.types\";\n\nexport interface FormWhenProps<T extends TUnion, D extends DiscriminatorKeys<T>, V extends string> {\n form: FormModel<T>;\n /** The discriminator field name. */\n field: D;\n /** Render the children only while the discriminator field equals this value. */\n value: V & DiscriminatorValue<T, D>;\n /** Receives the matching variant's fields. The form itself is already in scope. */\n children: (fields: FormFields<MatchVariant<T, D, V>>) => React.ReactNode;\n}\n\n/**\n * Renders its children only when the form's discriminator field currently holds\n * `value`, passing the fields narrowed to that variant. Stack one per variant to\n * lay out a discriminated-union form without manual conditionals or casts.\n */\nexport function FormWhen<T extends TUnion, D extends DiscriminatorKeys<T>, V extends string>({\n form,\n field,\n value,\n children,\n}: FormWhenProps<T, D, V>) {\n return (\n <Observer>\n {() => {\n const fields = form.rawFields as Record<string, FormFieldModel>;\n if (fields[field as string]?.value !== value) return null;\n return <>{children(fields as unknown as FormFields<MatchVariant<T, D, V>>)}</>;\n }}\n </Observer>\n );\n}\n","import Schema, { Validator } from \"typebox/schema\";\nimport * as Value from \"typebox/value\";\nimport * as T from \"typebox\";\nimport { makeAutoObservable, toJS } from \"mobx\";\nimport type { FormFieldConfig } from \"./form.types\";\n\n// TODO: should infer required prop\n// TODO: should also allow for \"id\", defaulting to name\n// TODO: probably shouldn't assume value is of correct type, maybe unknown?\n\nexport class FormFieldModel<T extends T.TSchema = T.TSchema> {\n readonly name: string;\n readonly schema: T;\n readonly config: FormFieldConfig<T>;\n readonly validator: Validator<T>;\n\n value: T.Static<T> | undefined;\n touched = false;\n\n get valid(): boolean {\n if (this.value === undefined && T.IsOptional(this.schema)) return true;\n return this.validator.Check(this.value);\n }\n\n get errorMessage(): string {\n if (this.valid || !this.touched) return \"\";\n // TODO: revisit this, now that .Errors returns success/fail\n const [_, errors] = this.validator.Errors(this.value);\n const error = errors.at(0);\n\n if (!error) return \"\";\n\n if (!T.IsOptional(this.schema) && (this.value === undefined || this.value === \"\")) {\n return \"This field is required.\";\n }\n\n if (\"errorMessage\" in this.schema) {\n if (typeof this.schema.errorMessage === \"string\") {\n return this.schema.errorMessage;\n } else if (typeof this.schema.errorMessage === \"function\") {\n return this.schema.errorMessage(this.value, this.schema);\n }\n }\n\n if (T.IsString(this.schema) && \"format\" in this.schema) {\n return `Please enter a valid ${String(this.schema.format)}`;\n }\n\n return error.message;\n }\n\n constructor(config: FormFieldConfig<T>) {\n this.config = config;\n this.name = config.name;\n this.schema = config.schema;\n this.validator = Schema.Compile(this.schema);\n this.value = this.convertValue(config.initialValue);\n\n makeAutoObservable(this, {\n name: false,\n schema: false,\n config: false,\n validator: false,\n });\n }\n\n setValue(value?: T.Static<T>) {\n // TODO: does this still make sense? If value is invalid,\n // then type will be wrong...revisit this\n this.value = this.convertValue(value);\n }\n\n private convertValue(value: unknown): T.Static<T> | undefined {\n // Value.Convert fabricates zero-values for undefined primitives (\"\" / 0 / false).\n // Only \"\" and false faithfully represent an empty control; a fabricated 0 reads\n // as real input (e.g. an epoch-0 date), so everything else stays undefined.\n if (value === undefined && !T.IsString(this.schema) && !T.IsBoolean(this.schema)) {\n return undefined;\n }\n return Value.Convert(this.schema, value) as T.Static<T>;\n }\n\n setTouched(touched: boolean) {\n this.touched = touched;\n }\n\n reset() {\n this.setTouched(false);\n this.setValue(this.config.initialValue);\n }\n\n // TODO: this any type is dangerous, need to figure out a good way\n // to make this work OTTB for most form controls, while allowing\n // some kind of escape hatch for special cases\n props(): any {\n return {\n name: this.name,\n onChange: (v?: T.Static<T>) => this.setValue(v),\n value: this.value,\n onBlur: () => {\n this.setTouched(true);\n },\n };\n }\n\n toJSON(): T.Static<T> | undefined {\n return toJS(this.value);\n }\n}\n","import * as Format from \"typebox/format\";\nimport * as Value from \"typebox/value\";\nimport Schema, { type Validator } from \"typebox/schema\";\nimport { IsUnion, Union, type Static, type TObject, type TSchema } from \"typebox\";\nimport { makeAutoObservable } from \"mobx\";\nimport type { FormConfig, FormFields, FormSchema, RawFormFields } from \"./form.types\";\nimport { FormFieldModel } from \"./form-field.model\";\n\n// should these be here?\nFormat.Set(\"password\", () => true);\nFormat.Set(\"phone\", () => true);\n\n// Flatten a schema's fields into a single property map. For a discriminated\n// union this merges the properties of every variant, unioning the schemas of\n// any field that appears in more than one variant (which naturally turns the\n// discriminator into a union of its literals).\nfunction resolveProperties(schema: FormSchema): Record<string, TSchema> {\n if (!IsUnion(schema)) return schema.properties;\n\n const groups: Record<string, TSchema[]> = {};\n for (const variant of schema.anyOf) {\n for (const [key, propSchema] of Object.entries((variant as TObject).properties)) {\n (groups[key] ??= []).push(propSchema as TSchema);\n }\n }\n\n const merged: Record<string, TSchema> = {};\n for (const [key, schemas] of Object.entries(groups)) {\n const distinct = [...new Map(schemas.map((s) => [JSON.stringify(s), s])).values()];\n merged[key] = distinct.length === 1 ? distinct[0]! : Union(distinct);\n }\n return merged;\n}\n\n// consider using enumerable to allow spreading of\n// field model instead of calling props() unless we need\n// to pass data to props...\n\n// TODO:\n// handleSubmit should catch a special MobxFormError\n// that can set field-level errors from an API response\n\nexport class FormModel<T extends FormSchema = TObject> {\n /** Shared fields only (for unions); every field for a plain object schema. */\n readonly fields: FormFields<T>;\n /** Every field across all variants — escape hatch for reaching variant fields. */\n readonly rawFields: RawFormFields<T>;\n readonly config: FormConfig<T>;\n readonly schema: T;\n readonly validator: Validator<T>;\n\n // TODO: maybe refactor into a \"state\" property?\n submitting = false;\n submitted = false;\n\n // TODO: what should this type be? should it be generic?\n submitError: any;\n\n constructor(schema: T, config: FormConfig<T>) {\n this.schema = schema;\n this.config = config;\n this.validator = Schema.Compile(schema);\n\n makeAutoObservable(this, {\n fields: false,\n rawFields: false,\n schema: false,\n config: false,\n validator: false,\n });\n\n const initialValues = config?.initialValues as Record<string, unknown> | undefined;\n const fields = Object.entries(resolveProperties(schema)).reduce(\n (fields, [fieldName, fieldSchema]) => {\n fields[fieldName] = new FormFieldModel({\n name: fieldName,\n schema: fieldSchema,\n initialValue: initialValues?.[fieldName],\n });\n return fields;\n },\n {} as Record<string, FormFieldModel<TSchema>>,\n );\n\n // `fields` and `rawFields` are the same object; the types differ so that a\n // union form only surfaces shared fields by default.\n this.rawFields = fields as unknown as RawFormFields<T>;\n this.fields = fields as unknown as FormFields<T>;\n }\n\n get valid(): boolean {\n // A union form can't be validated field-by-field — fields belonging to the\n // inactive variant would fail — so validate the assembled object instead.\n if (IsUnion(this.schema)) {\n return this.validator.Check(this.toJSON());\n }\n return Object.values(this.fields).every((field) => field.valid);\n }\n\n props(): any {\n return {\n onSubmit: (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n\n this.setSubmitError(undefined);\n\n if (!this.validate()) {\n return;\n }\n\n this.setSubmitting(true);\n this.config\n .handleSubmit(this.toJSON() as Static<T>)\n .then((resp) => {\n this.setSubmitted(true);\n return resp;\n })\n .catch((e) => {\n this.setSubmitError(e);\n })\n .finally(() => {\n this.setSubmitting(false);\n });\n },\n };\n }\n\n setSubmitError(error: any): void {\n this.submitError = error;\n }\n\n protected setSubmitting(submitting: boolean): void {\n this.submitting = submitting;\n }\n\n protected setSubmitted(submitted: boolean): void {\n this.submitted = submitted;\n }\n\n reset(): void {\n this.setSubmitError(undefined);\n for (const field of Object.values(this.fields)) {\n field.reset();\n }\n }\n\n validate(): boolean {\n for (const field of Object.values(this.fields)) {\n field.setTouched(true);\n }\n return this.valid;\n }\n\n toJSON(): Partial<Static<T>> {\n const data = Object.values(this.fields).reduce(\n (fields, field) => {\n fields[field.name] = field.toJSON();\n return fields;\n },\n {} as Record<string, unknown>,\n );\n\n // Drop fields belonging to the inactive variant so submitted data matches\n // the selected member of the union exactly.\n if (IsUnion(this.schema)) {\n return Value.Clean(this.schema, data) as Partial<Static<T>>;\n }\n return data as Partial<Static<T>>;\n }\n}\n","import type { TObject } from \"typebox\";\nimport { useRef } from \"react\";\nimport { FormModel } from \"./form.model\";\nimport type { FormConfig, FormSchema } from \"./form.types\";\n\nexport const useForm = <T extends FormSchema = TObject>(\n schema: T,\n config: FormConfig<T>,\n): FormModel<T> => {\n const formRef = useRef<FormModel<T>>(undefined);\n if (formRef.current) {\n Object.assign(formRef.current.config, config);\n } else {\n formRef.current = new FormModel<T>(schema, config);\n }\n\n return formRef.current;\n};\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,cAAc,cAAqC,MAAS;AACzE,MAAa,uBAAuB;CAClC,MAAM,UAAU,WAAW,WAAW;CACtC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,mHACF;CAEF,OAAO;AACT;AAEA,MAAa,eAAe,YAAY;AAExC,MAAa,kCAAkC,WAAW,WAAW;;;;ACLrE,MAAa,WAAW,WAAW,SAAS,SAC1C,EAAE,MAAM,UAAU,GAAG,aACrB,KACA;CACA,OACE,oBAAC,cAAD;EAAc,OAAO;YACnB,oBAAC,QAAD;GAAM;GAAW,GAAI;GAAgB;GAAK,GAAI,KAAK,MAAM;GACtD;EACG;CACM;AAElB,CAAC;;;;;;;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;EACjD,KAAK,aAAa;CACpB;CAEA,AAAU,aAAa,WAA0B;EAC/C,KAAK,YAAY;CACnB;CAEA,QAAc;EACZ,KAAK,eAAe,MAAS;EAC7B,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,MAAM,GAC3C,MAAM,MAAM;CAEhB;CAEA,WAAoB;EAClB,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,MAAM,GAC3C,MAAM,WAAW,IAAI;EAEvB,OAAO,KAAK;CACd;CAEA,SAA6B;EAC3B,MAAM,OAAO,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,QACrC,QAAQ,UAAU;GACjB,OAAO,MAAM,QAAQ,MAAM,OAAO;GAClC,OAAO;EACT,GACA,CAAC,CACH;EAIA,IAAI,QAAQ,KAAK,MAAM,GACrB,OAAO,MAAM,MAAM,KAAK,QAAQ,IAAI;EAEtC,OAAO;CACT;AACF;;;;ACpKA,MAAa,WACX,QACA,WACiB;CACjB,MAAM,UAAU,OAAqB,MAAS;CAC9C,IAAI,QAAQ,SACV,OAAO,OAAO,QAAQ,QAAQ,QAAQ,MAAM;MAE5C,QAAQ,UAAU,IAAI,UAAa,QAAQ,MAAM;CAGnD,OAAO,QAAQ;AACjB"}
|
|
1
|
+
{"version":3,"file":"form.mjs","names":[],"sources":["../src/form/form.context.ts","../src/form/components/form.tsx","../src/form/components/form-when.tsx","../src/form/form-field.model.ts","../src/form/form.model.ts","../src/form/use-form.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport type { FormModel } from \"./form.model\";\n\nexport const formContext = createContext<FormModel | undefined>(undefined);\nexport const useFormContext = () => {\n const context = useContext(formContext);\n if (!context) {\n throw new Error(\n \"Form context not available. Make sure you are within the <Form> component or providing the form context manually.\",\n );\n }\n return context;\n};\n\nexport const FormProvider = formContext.Provider;\n\nexport const useFormContextIfAvailable = () => useContext(formContext);\n","import { forwardRef } from \"react\";\nimport { FormProvider } from \"../form.context\";\nimport type { FormModel } from \"../form.model\";\n\nexport interface MobxFormProps extends Omit<\n React.HTMLProps<HTMLFormElement>,\n \"form\" | \"action\" | \"method\"\n> {\n form: FormModel<any>;\n}\n\nexport const MobxForm = forwardRef(function MobxForm(\n { form, children, ...formProps }: MobxFormProps,\n ref,\n) {\n return (\n <FormProvider value={form}>\n <form noValidate {...formProps} ref={ref} {...form.props()}>\n {children}\n </form>\n </FormProvider>\n );\n});\n","import type { TUnion } from \"typebox\";\nimport { Observer } from \"mobx-react-lite\";\nimport type { FormModel } from \"../form.model\";\nimport type { FormFieldModel } from \"../form-field.model\";\nimport type {\n DiscriminatorKeys,\n DiscriminatorValue,\n FormFields,\n MatchVariant,\n} from \"../form.types\";\n\nexport interface FormWhenProps<T extends TUnion, D extends DiscriminatorKeys<T>, V extends string> {\n form: FormModel<T>;\n /** The discriminator field name. */\n field: D;\n /** Render the children only while the discriminator field equals this value. */\n value: V & DiscriminatorValue<T, D>;\n /** Receives the matching variant's fields. The form itself is already in scope. */\n children: (fields: FormFields<MatchVariant<T, D, V>>) => React.ReactNode;\n}\n\n/**\n * Renders its children only when the form's discriminator field currently holds\n * `value`, passing the fields narrowed to that variant. Stack one per variant to\n * lay out a discriminated-union form without manual conditionals or casts.\n */\nexport function FormWhen<T extends TUnion, D extends DiscriminatorKeys<T>, V extends string>({\n form,\n field,\n value,\n children,\n}: FormWhenProps<T, D, V>) {\n return (\n <Observer>\n {() => {\n const fields = form.rawFields as Record<string, FormFieldModel>;\n if (fields[field as string]?.value !== value) return null;\n return <>{children(fields as unknown as FormFields<MatchVariant<T, D, V>>)}</>;\n }}\n </Observer>\n );\n}\n","import Schema, { Validator } from \"typebox/schema\";\nimport * as Value from \"typebox/value\";\nimport * as T from \"typebox\";\nimport { makeAutoObservable, toJS } from \"mobx\";\nimport type { FormFieldConfig } from \"./form.types\";\n\n// TODO: should infer required prop\n// TODO: should also allow for \"id\", defaulting to name\n// TODO: probably shouldn't assume value is of correct type, maybe unknown?\n\nexport class FormFieldModel<T extends T.TSchema = T.TSchema> {\n readonly name: string;\n readonly schema: T;\n readonly config: FormFieldConfig<T>;\n readonly validator: Validator<T>;\n\n value: T.Static<T> | undefined;\n touched = false;\n\n get valid(): boolean {\n if (this.value === undefined && T.IsOptional(this.schema)) return true;\n return this.validator.Check(this.value);\n }\n\n get errorMessage(): string {\n if (this.valid || !this.touched) return \"\";\n // TODO: revisit this, now that .Errors returns success/fail\n const [_, errors] = this.validator.Errors(this.value);\n const error = errors.at(0);\n\n if (!error) return \"\";\n\n if (!T.IsOptional(this.schema) && (this.value === undefined || this.value === \"\")) {\n return \"This field is required.\";\n }\n\n if (\"errorMessage\" in this.schema) {\n if (typeof this.schema.errorMessage === \"string\") {\n return this.schema.errorMessage;\n } else if (typeof this.schema.errorMessage === \"function\") {\n return this.schema.errorMessage(this.value, this.schema);\n }\n }\n\n if (T.IsString(this.schema) && \"format\" in this.schema) {\n return `Please enter a valid ${String(this.schema.format)}`;\n }\n\n return error.message;\n }\n\n constructor(config: FormFieldConfig<T>) {\n this.config = config;\n this.name = config.name;\n this.schema = config.schema;\n this.validator = Schema.Compile(this.schema);\n this.value = this.convertValue(config.initialValue);\n\n makeAutoObservable(this, {\n name: false,\n schema: false,\n config: false,\n validator: false,\n });\n }\n\n setValue(value?: T.Static<T>) {\n // TODO: does this still make sense? If value is invalid,\n // then type will be wrong...revisit this\n this.value = this.convertValue(value);\n }\n\n private convertValue(value: unknown): T.Static<T> | undefined {\n // Value.Convert fabricates zero-values for undefined primitives (\"\" / 0 / false).\n // Only \"\" and false faithfully represent an empty control; a fabricated 0 reads\n // as real input (e.g. an epoch-0 date), so everything else stays undefined.\n if (value === undefined && !T.IsString(this.schema) && !T.IsBoolean(this.schema)) {\n return undefined;\n }\n return Value.Convert(this.schema, value) as T.Static<T>;\n }\n\n setTouched(touched: boolean) {\n this.touched = touched;\n }\n\n reset() {\n this.setTouched(false);\n this.setValue(this.config.initialValue);\n }\n\n // TODO: this any type is dangerous, need to figure out a good way\n // to make this work OTTB for most form controls, while allowing\n // some kind of escape hatch for special cases\n props(): any {\n return {\n name: this.name,\n onChange: (v?: T.Static<T>) => this.setValue(v),\n value: this.value,\n onBlur: () => {\n this.setTouched(true);\n },\n };\n }\n\n toJSON(): T.Static<T> | undefined {\n return toJS(this.value);\n }\n}\n","import * as Format from \"typebox/format\";\nimport * as Value from \"typebox/value\";\nimport Schema, { type Validator } from \"typebox/schema\";\nimport { IsUnion, Union, type Static, type TObject, type TSchema } from \"typebox\";\nimport { makeAutoObservable } from \"mobx\";\nimport type { FormConfig, FormFields, FormSchema, RawFormFields } from \"./form.types\";\nimport { FormFieldModel } from \"./form-field.model\";\n\n// should these be here?\nFormat.Set(\"password\", () => true);\nFormat.Set(\"phone\", () => true);\n\n// Flatten a schema's fields into a single property map. For a discriminated\n// union this merges the properties of every variant, unioning the schemas of\n// any field that appears in more than one variant (which naturally turns the\n// discriminator into a union of its literals).\nfunction resolveProperties(schema: FormSchema): Record<string, TSchema> {\n if (!IsUnion(schema)) return schema.properties;\n\n const groups: Record<string, TSchema[]> = {};\n for (const variant of schema.anyOf) {\n for (const [key, propSchema] of Object.entries((variant as TObject).properties)) {\n (groups[key] ??= []).push(propSchema as TSchema);\n }\n }\n\n const merged: Record<string, TSchema> = {};\n for (const [key, schemas] of Object.entries(groups)) {\n const distinct = [...new Map(schemas.map((s) => [JSON.stringify(s), s])).values()];\n merged[key] = distinct.length === 1 ? distinct[0]! : Union(distinct);\n }\n return merged;\n}\n\n// consider using enumerable to allow spreading of\n// field model instead of calling props() unless we need\n// to pass data to props...\n\n// TODO:\n// handleSubmit should catch a special MobxFormError\n// that can set field-level errors from an API response\n\nexport class FormModel<T extends FormSchema = TObject> {\n /** Shared fields only (for unions); every field for a plain object schema. */\n readonly fields: FormFields<T>;\n /** Every field across all variants — escape hatch for reaching variant fields. */\n readonly rawFields: RawFormFields<T>;\n readonly config: FormConfig<T>;\n readonly schema: T;\n readonly validator: Validator<T>;\n\n // TODO: maybe refactor into a \"state\" property?\n submitting = false;\n submitted = false;\n\n // TODO: what should this type be? should it be generic?\n submitError: any;\n\n constructor(schema: T, config: FormConfig<T>) {\n this.schema = schema;\n this.config = config;\n this.validator = Schema.Compile(schema);\n\n makeAutoObservable(this, {\n fields: false,\n rawFields: false,\n schema: false,\n config: false,\n validator: false,\n });\n\n const initialValues = config?.initialValues as Record<string, unknown> | undefined;\n const fields = Object.entries(resolveProperties(schema)).reduce(\n (fields, [fieldName, fieldSchema]) => {\n fields[fieldName] = new FormFieldModel({\n name: fieldName,\n schema: fieldSchema,\n initialValue: initialValues?.[fieldName],\n });\n return fields;\n },\n {} as Record<string, FormFieldModel<TSchema>>,\n );\n\n // `fields` and `rawFields` are the same object; the types differ so that a\n // union form only surfaces shared fields by default.\n this.rawFields = fields as unknown as RawFormFields<T>;\n this.fields = fields as unknown as FormFields<T>;\n }\n\n get valid(): boolean {\n // A union form can't be validated field-by-field — fields belonging to the\n // inactive variant would fail — so validate the assembled object instead.\n if (IsUnion(this.schema)) {\n return this.validator.Check(this.toJSON());\n }\n return Object.values(this.fields).every((field) => field.valid);\n }\n\n props(): any {\n return {\n onSubmit: (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n\n this.setSubmitError(undefined);\n\n if (!this.validate()) {\n return;\n }\n\n this.setSubmitting(true);\n this.config\n .handleSubmit(this.toJSON() as Static<T>)\n .then((resp) => {\n this.setSubmitted(true);\n return resp;\n })\n .catch((e) => {\n this.setSubmitError(e);\n })\n .finally(() => {\n this.setSubmitting(false);\n });\n },\n };\n }\n\n setSubmitError(error: any): void {\n this.submitError = error;\n }\n\n protected setSubmitting(submitting: boolean): void {\n this.submitting = submitting;\n }\n\n protected setSubmitted(submitted: boolean): void {\n this.submitted = submitted;\n }\n\n reset(): void {\n this.setSubmitError(undefined);\n for (const field of Object.values(this.fields)) {\n field.reset();\n }\n }\n\n validate(): boolean {\n for (const field of Object.values(this.fields)) {\n field.setTouched(true);\n }\n return this.valid;\n }\n\n toJSON(): Partial<Static<T>> {\n const data = Object.values(this.fields).reduce(\n (fields, field) => {\n fields[field.name] = field.toJSON();\n return fields;\n },\n {} as Record<string, unknown>,\n );\n\n // Drop fields belonging to the inactive variant so submitted data matches\n // the selected member of the union exactly.\n if (IsUnion(this.schema)) {\n return Value.Clean(this.schema, data) as Partial<Static<T>>;\n }\n return data as Partial<Static<T>>;\n }\n}\n","import type { TObject } from \"typebox\";\nimport { useRef } from \"react\";\nimport { FormModel } from \"./form.model\";\nimport type { FormConfig, FormSchema } from \"./form.types\";\n\nexport const useForm = <T extends FormSchema = TObject>(\n schema: T,\n config: FormConfig<T>,\n): FormModel<T> => {\n const formRef = useRef<FormModel<T>>(undefined);\n if (formRef.current) {\n Object.assign(formRef.current.config, config);\n } else {\n formRef.current = new FormModel<T>(schema, config);\n }\n\n return formRef.current;\n};\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,cAAc,cAAqC,MAAS;AACzE,MAAa,uBAAuB;CAClC,MAAM,UAAU,WAAW,WAAW;CACtC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,mHACF;CAEF,OAAO;AACT;AAEA,MAAa,eAAe,YAAY;AAExC,MAAa,kCAAkC,WAAW,WAAW;;;;ACLrE,MAAa,WAAW,WAAW,SAAS,SAC1C,EAAE,MAAM,UAAU,GAAG,aACrB,KACA;CACA,OACE,oBAAC,cAAD;EAAc,OAAO;YACnB,oBAAC,QAAD;GAAM;GAAW,GAAI;GAAgB;GAAK,GAAI,KAAK,MAAM;GACtD;EACG;CACM;AAElB,CAAC;;;;;;;;;ACID,SAAgB,SAA6E,EAC3F,MACA,OACA,OACA,YACyB;CACzB,OACE,oBAAC,UAAD,kBACS;EACL,MAAM,SAAS,KAAK;EACpB,IAAI,OAAO,MAAgB,EAAE,UAAU,OAAO,OAAO;EACrD,OAAO,4CAAG,SAAS,MAAsD,EAAI;CAC/E,EACQ;AAEd;;;;AC/BA,IAAa,iBAAb,MAA6D;CAC3D,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CAET;CACA,UAA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AEA,SAA6B;EAC3B,MAAM,OAAO,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,QACrC,QAAQ,UAAU;GACjB,OAAO,MAAM,QAAQ,MAAM,OAAO;GAClC,OAAO;EACT,GACA,CAAC,CACH;EAIA,IAAI,QAAQ,KAAK,MAAM,GACrB,OAAO,MAAM,MAAM,KAAK,QAAQ,IAAI;EAEtC,OAAO;CACT;AACF;;;;ACpKA,MAAa,WACX,QACA,WACiB;CACjB,MAAM,UAAU,OAAqB,MAAS;CAC9C,IAAI,QAAQ,SACV,OAAO,OAAO,QAAQ,QAAQ,QAAQ,MAAM;MAE5C,QAAQ,UAAU,IAAI,UAAa,QAAQ,MAAM;CAGnD,OAAO,QAAQ;AACjB"}
|
|
@@ -70,12 +70,32 @@ function lazyObservable(fetch, options) {
|
|
|
70
70
|
});
|
|
71
71
|
};
|
|
72
72
|
let observedCount = 0;
|
|
73
|
+
let loadScheduled = false;
|
|
74
|
+
/**
|
|
75
|
+
* MobX fires `onBecomeObserved` synchronously, which for an `observer()` component means *during
|
|
76
|
+
* its render*. Calling `load()` there writes `status` mid-render, and if another mounted component
|
|
77
|
+
* already observes this lazy, mobx-react-lite force-updates it while React is rendering something
|
|
78
|
+
* else — which React rejects ("Cannot update a component while rendering a different component").
|
|
79
|
+
*
|
|
80
|
+
* Deferring to a microtask moves the write just past the render pass. It still runs in the same
|
|
81
|
+
* task, well before any fetch could resolve, so the only observable difference is that `status`
|
|
82
|
+
* reads "init" rather than "loading" during that first render.
|
|
83
|
+
*/
|
|
84
|
+
const scheduleLoad = () => {
|
|
85
|
+
if (loadScheduled) return;
|
|
86
|
+
loadScheduled = true;
|
|
87
|
+
queueMicrotask(() => {
|
|
88
|
+
loadScheduled = false;
|
|
89
|
+
if (!observedCount) return;
|
|
90
|
+
if (status.get() === "error" || status.get() === "init") load();
|
|
91
|
+
});
|
|
92
|
+
};
|
|
73
93
|
const onObserved = () => {
|
|
74
94
|
observedCount = Math.min(2, observedCount + 1);
|
|
75
95
|
if (observedCount !== 1) return;
|
|
76
96
|
if (options?.debugName) console.log(`lazyObservable ${options.debugName}`, "observed");
|
|
77
97
|
clearTimeout(resetTimer);
|
|
78
|
-
if (status.get() === "error" || status.get() === "init")
|
|
98
|
+
if (status.get() === "error" || status.get() === "init") scheduleLoad();
|
|
79
99
|
};
|
|
80
100
|
const onUnobserved = () => {
|
|
81
101
|
observedCount = Math.max(0, observedCount - 1);
|
|
@@ -138,4 +158,4 @@ function lazyObservableArray(fetch, options) {
|
|
|
138
158
|
|
|
139
159
|
//#endregion
|
|
140
160
|
export { lazyObservableArray as n, lazyObservable as t };
|
|
141
|
-
//# sourceMappingURL=lazy-observable-
|
|
161
|
+
//# sourceMappingURL=lazy-observable-8dTdgRqO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lazy-observable-8dTdgRqO.mjs","names":[],"sources":["../src/lazy-observable/lazy-observable.ts"],"sourcesContent":["import {\n _allowStateChanges,\n autorun,\n type IObservableArray,\n type IReactionDisposer,\n observable,\n onBecomeObserved,\n onBecomeUnobserved,\n} from \"mobx\";\n\nexport interface LazyObservable<T = any, TInitialValue = T | undefined> {\n value: TInitialValue;\n reset(): TInitialValue;\n getOrLoad(): Promise<T>;\n set(value: T): void;\n reload(): Promise<T>;\n status: \"init\" | \"loading\" | \"loaded\" | \"error\";\n error: unknown;\n loading: boolean;\n loaded: boolean;\n}\n\nexport interface LazyObservableOptions {\n shallow?: boolean;\n resetOnUnobserved?: \"never\" | \"always\" | number;\n debugName?: string;\n}\n\nexport interface LazyObservableOptionsWithInitialValue<\n TInitialValue,\n> extends LazyObservableOptions {\n initialValue?: TInitialValue;\n}\n\nexport function lazyObservable<T>(fetch: () => Promise<T>): LazyObservable<T>;\nexport function lazyObservable<T>(\n fetch: () => Promise<T>,\n options: LazyObservableOptions,\n): LazyObservable<T>;\nexport function lazyObservable<T, TInitialValue>(\n fetch: () => Promise<T>,\n options: LazyObservableOptionsWithInitialValue<TInitialValue>,\n): LazyObservable<T, TInitialValue>;\n\nexport function lazyObservable<T>(\n fetch: () => Promise<T>,\n options?: LazyObservableOptionsWithInitialValue<T>,\n): LazyObservable<T> {\n const value = observable.box<T>(options?.initialValue, { deep: !options?.shallow });\n const status = observable.box<LazyObservable<T>[\"status\"]>(\"init\");\n const error = observable.box<unknown>(undefined);\n\n let resetTimer: NodeJS.Timeout;\n let autorunDisposer: IReactionDisposer;\n\n let promise: Promise<T> | undefined;\n let promiseResolve: ((value: T) => void) | undefined;\n let promiseReject: ((value: unknown) => void) | undefined;\n\n const getOrCreatePromise = () => {\n if (promise && status.get() !== \"loaded\" && status.get() !== \"error\") {\n return promise;\n }\n promise = new Promise<T>((resolve, reject) => {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n return promise;\n };\n\n const reset = () => {\n clearTimeout(resetTimer);\n autorunDisposer?.();\n _allowStateChanges(true, () => {\n value.set(options?.initialValue);\n status.set(\"init\");\n error.set(undefined);\n });\n return options?.initialValue;\n };\n\n const load = (): void => {\n if (status.get() === \"loading\") return;\n clearTimeout(resetTimer);\n\n // TODO: this disposer is unreliable while we are using\n // babel to convert all async function to generators\n autorunDisposer?.();\n autorunDisposer = autorun(() => {\n _allowStateChanges(true, () => {\n status.set(\"loading\");\n error.set(undefined);\n });\n\n let fetchPromise: Promise<T>;\n try {\n fetchPromise = fetch();\n } catch (e) {\n _allowStateChanges(true, () => {\n error.set(e);\n status.set(\"error\");\n promiseReject?.(e);\n });\n return;\n }\n\n fetchPromise\n .then((newValue) => {\n _allowStateChanges(true, () => {\n value.set(newValue);\n status.set(\"loaded\");\n promiseResolve?.(newValue);\n });\n })\n .catch((e) => {\n _allowStateChanges(true, () => {\n error.set(e);\n status.set(\"error\");\n promiseReject?.(e);\n });\n });\n });\n };\n\n // TODO: should this resolve any promises?\n const set = (val: T): void => {\n _allowStateChanges(true, () => {\n value.set(val);\n status.set(\"loaded\");\n });\n };\n\n let observedCount = 0;\n let loadScheduled = false;\n\n /**\n * MobX fires `onBecomeObserved` synchronously, which for an `observer()` component means *during\n * its render*. Calling `load()` there writes `status` mid-render, and if another mounted component\n * already observes this lazy, mobx-react-lite force-updates it while React is rendering something\n * else — which React rejects (\"Cannot update a component while rendering a different component\").\n *\n * Deferring to a microtask moves the write just past the render pass. It still runs in the same\n * task, well before any fetch could resolve, so the only observable difference is that `status`\n * reads \"init\" rather than \"loading\" during that first render.\n */\n const scheduleLoad = (): void => {\n if (loadScheduled) return;\n loadScheduled = true;\n queueMicrotask(() => {\n loadScheduled = false;\n // the lazy may have been unobserved again before this ran (a component that mounted and\n // immediately unmounted), or been loaded explicitly via reload()/getOrLoad()/set()\n if (!observedCount) return;\n if (status.get() === \"error\" || status.get() === \"init\") {\n load();\n }\n });\n };\n\n const onObserved = () => {\n observedCount = Math.min(2, observedCount + 1);\n\n // only consider observed the first time this handler gets called\n if (observedCount !== 1) return;\n\n if (options?.debugName) {\n console.log(`lazyObservable ${options.debugName}`, \"observed\");\n }\n clearTimeout(resetTimer);\n if (status.get() === \"error\" || status.get() === \"init\") {\n scheduleLoad();\n }\n };\n\n const onUnobserved = () => {\n observedCount = Math.max(0, observedCount - 1);\n\n // only consider unobserved when count reaches zero\n if (observedCount) return;\n\n if (options?.debugName) {\n console.log(`lazyObservable ${options.debugName}`, \"unobserved\");\n }\n\n // Errors are never cached regardless of resetOnUnobserved — failure state\n // shouldn't persist across mounts, only successfully loaded values should.\n if (status.get() === \"error\") {\n _allowStateChanges(true, () => {\n status.set(\"init\");\n error.set(undefined);\n });\n return;\n }\n\n if (options?.resetOnUnobserved === \"never\") {\n return;\n } else if (typeof options?.resetOnUnobserved === \"number\") {\n resetTimer = setTimeout(() => {\n reset();\n }, options?.resetOnUnobserved);\n } else {\n reset();\n }\n };\n\n onBecomeObserved(value, onObserved);\n onBecomeObserved(status, onObserved);\n onBecomeObserved(error, onObserved);\n\n onBecomeUnobserved(value, onUnobserved);\n onBecomeUnobserved(status, onUnobserved);\n onBecomeUnobserved(error, onUnobserved);\n\n return {\n get value() {\n return value.get();\n },\n get status() {\n return status.get();\n },\n get error() {\n return error.get();\n },\n get loading() {\n return status.get() === \"loading\";\n },\n get loaded() {\n return status.get() === \"loaded\";\n },\n reload() {\n const promise = getOrCreatePromise();\n load();\n return promise;\n },\n getOrLoad() {\n // TODO: this assertion shouldn't be necessary\n // consider fixing box/value type\n if (this.loaded) return Promise.resolve(value.get() as Promise<T>);\n return this.reload();\n },\n set,\n reset,\n };\n}\n\nexport interface LazyObservableArray<T = any> extends Omit<\n // value is never undefined: lazyObservableArray always seeds initialValue with []\n LazyObservable<IObservableArray<T>, IObservableArray<T>>,\n \"set\"\n> {\n set(value: T[]): void;\n}\n\nexport interface LazyObservableArrayOptions<T> extends LazyObservableOptions {\n initialValue?: T[];\n}\n\nexport function lazyObservableArray<T>(\n fetch: () => Promise<T[]>,\n options?: LazyObservableArrayOptions<T>,\n): LazyObservableArray<T> {\n return lazyObservable(fetch, {\n ...options,\n initialValue: options?.initialValue ?? [],\n }) as LazyObservableArray<T>;\n}\n\nexport type InferLazyObservable<O> =\n O extends LazyObservableArray<infer T> ? T[] : O extends LazyObservable<infer T> ? T : never;\n"],"mappings":";;;AA4CA,SAAgB,eACd,OACA,SACmB;CACnB,MAAM,QAAQ,WAAW,IAAO,SAAS,cAAc,EAAE,MAAM,CAAC,SAAS,QAAQ,CAAC;CAClF,MAAM,SAAS,WAAW,IAAiC,MAAM;CACjE,MAAM,QAAQ,WAAW,IAAa,MAAS;CAE/C,IAAI;CACJ,IAAI;CAEJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,2BAA2B;EAC/B,IAAI,WAAW,OAAO,IAAI,MAAM,YAAY,OAAO,IAAI,MAAM,SAC3D,OAAO;EAET,UAAU,IAAI,SAAY,SAAS,WAAW;GAC5C,iBAAiB;GACjB,gBAAgB;EAClB,CAAC;EACD,OAAO;CACT;CAEA,MAAM,cAAc;EAClB,aAAa,UAAU;EACvB,kBAAkB;EAClB,m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AO,eAAe,OAAO;EAC3B,GAAG;EACH,cAAc,SAAS,gBAAgB,CAAC;CAC1C,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lazy-observable-CSsG7nEB.d.mts","names":[],"sources":["../src/lazy-observable/lazy-observable.ts"],"mappings":";;;UAUiB,cAAA,0BAAwC,CAAA;EACvD,KAAA,EAAO,aAAA;EACP,KAAA,IAAS,aAAA;EACT,SAAA,IAAa,OAAA,CAAQ,CAAA;EACrB,GAAA,CAAI,KAAA,EAAO,CAAA;EACX,MAAA,IAAU,OAAA,CAAQ,CAAA;EAClB,MAAA;EACA,KAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,UAGe,qBAAA;EACf,OAAA;EACA,iBAAA;EACA,SAAA;AAAA;AAAA,UAGe,qCAAA,wBAEP,qBAAqB;EAC7B,YAAA,GAAe,aAAA;AAAA;AAAA,iBAGD,cAAA,IAAkB,KAAA,QAAa,OAAA,CAAQ,CAAA,IAAK,cAAA,CAAe,CAAA;AAAA,iBAC3D,cAAA,IACd,KAAA,QAAa,OAAA,CAAQ,CAAA,GACrB,OAAA,EAAS,qBAAA,GACR,cAAA,CAAe,CAAA;AAAA,iBACF,cAAA,mBACd,KAAA,QAAa,OAAA,CAAQ,CAAA,GACrB,OAAA,EAAS,qCAAA,CAAsC,aAAA,IAC9C,cAAA,CAAe,CAAA,EAAG,aAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"lazy-observable-CSsG7nEB.d.mts","names":[],"sources":["../src/lazy-observable/lazy-observable.ts"],"mappings":";;;UAUiB,cAAA,0BAAwC,CAAA;EACvD,KAAA,EAAO,aAAA;EACP,KAAA,IAAS,aAAA;EACT,SAAA,IAAa,OAAA,CAAQ,CAAA;EACrB,GAAA,CAAI,KAAA,EAAO,CAAA;EACX,MAAA,IAAU,OAAA,CAAQ,CAAA;EAClB,MAAA;EACA,KAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,UAGe,qBAAA;EACf,OAAA;EACA,iBAAA;EACA,SAAA;AAAA;AAAA,UAGe,qCAAA,wBAEP,qBAAqB;EAC7B,YAAA,GAAe,aAAA;AAAA;AAAA,iBAGD,cAAA,IAAkB,KAAA,QAAa,OAAA,CAAQ,CAAA,IAAK,cAAA,CAAe,CAAA;AAAA,iBAC3D,cAAA,IACd,KAAA,QAAa,OAAA,CAAQ,CAAA,GACrB,OAAA,EAAS,qBAAA,GACR,cAAA,CAAe,CAAA;AAAA,iBACF,cAAA,mBACd,KAAA,QAAa,OAAA,CAAQ,CAAA,GACrB,OAAA,EAAS,qCAAA,CAAsC,aAAA,IAC9C,cAAA,CAAe,CAAA,EAAG,aAAA;AAAA,UA2MJ,mBAAA,kBAAqC,IAAA,CAEpD,cAAA,CAAe,gBAAA,CAAiB,CAAA,GAAI,gBAAA,CAAiB,CAAA;EAGrD,GAAA,CAAI,KAAA,EAAO,CAAA;AAAA;AAAA,UAGI,0BAAA,YAAsC,qBAAqB;EAC1E,YAAA,GAAe,CAAA;AAAA;AAAA,iBAGD,mBAAA,IACd,KAAA,QAAa,OAAA,CAAQ,CAAA,KACrB,OAAA,GAAU,0BAAA,CAA2B,CAAA,IACpC,mBAAA,CAAoB,CAAA;AAAA,KAOX,mBAAA,MACV,CAAA,SAAU,mBAAA,YAA+B,CAAA,KAAM,CAAA,SAAU,cAAA,YAA0B,CAAA"}
|
package/dist/lazy-observable.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as lazyObservableArray, t as lazyObservable } from "./lazy-observable-
|
|
1
|
+
import { n as lazyObservableArray, t as lazyObservable } from "./lazy-observable-8dTdgRqO.mjs";
|
|
2
2
|
import { Observer } from "mobx-react-lite";
|
|
3
3
|
import { jsx } from "react/jsx-runtime";
|
|
4
4
|
|
package/dist/model.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as lazyObservableArray } from "./lazy-observable-
|
|
1
|
+
import { n as lazyObservableArray } from "./lazy-observable-8dTdgRqO.mjs";
|
|
2
2
|
import { action, makeObservable, observable, runInAction, toJS } from "mobx";
|
|
3
3
|
import * as Value from "typebox/value";
|
|
4
4
|
import * as T from "typebox";
|
package/dist/react-util.d.mts
CHANGED
|
@@ -52,8 +52,19 @@ declare const useMountEffect: (effectFn: React.EffectCallback) => void;
|
|
|
52
52
|
//#region src/react-util/useMountedState.d.ts
|
|
53
53
|
declare const useMountedState: () => (() => boolean);
|
|
54
54
|
//#endregion
|
|
55
|
-
//#region src/react-util/
|
|
56
|
-
|
|
55
|
+
//#region src/react-util/useResize.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* Reports an element's **content-box** size whenever it changes, including the initial measurement.
|
|
58
|
+
*
|
|
59
|
+
* Content box means padding, border and scrollbars are all excluded — so a width fed back into
|
|
60
|
+
* layout math can't feed back into its own overflow, and a gutter appearing or disappearing is
|
|
61
|
+
* reported as a real size change. Values are fractional; round at the point of use if you need
|
|
62
|
+
* integers.
|
|
63
|
+
*
|
|
64
|
+
* `onResize` is read through a ref, so passing an inline arrow does not tear down and re-create the
|
|
65
|
+
* observer on every render.
|
|
66
|
+
*/
|
|
67
|
+
declare const useResize: (ref: React.RefObject<HTMLElement | null>, onResize: (width: number, height: number) => void) => void;
|
|
57
68
|
//#endregion
|
|
58
|
-
export { UseAsyncFn, UseAsyncFnOptions, UseAsyncFnRun, UseAsyncFnState, UseAsyncFnStateBase, UseAsyncFnStateError, UseAsyncFnStateLoading, UseAsyncFnStateResolved, UseDebouncedCallbackOptions, useAsync, useAsyncFn, useDebouncedCallback, useDebouncedEffect, useMountEffect, useMountedState,
|
|
69
|
+
export { UseAsyncFn, UseAsyncFnOptions, UseAsyncFnRun, UseAsyncFnState, UseAsyncFnStateBase, UseAsyncFnStateError, UseAsyncFnStateLoading, UseAsyncFnStateResolved, UseDebouncedCallbackOptions, useAsync, useAsyncFn, useDebouncedCallback, useDebouncedEffect, useMountEffect, useMountedState, useResize };
|
|
59
70
|
//# sourceMappingURL=react-util.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-util.d.mts","names":[],"sources":["../src/react-util/useAsyncFn.ts","../src/react-util/useAsync.ts","../src/react-util/useDebouncedCallback.tsx","../src/react-util/useDebouncedEffect.tsx","../src/react-util/useMountEffect.tsx","../src/react-util/useMountedState.ts","../src/react-util/
|
|
1
|
+
{"version":3,"file":"react-util.d.mts","names":[],"sources":["../src/react-util/useAsyncFn.ts","../src/react-util/useAsync.ts","../src/react-util/useDebouncedCallback.tsx","../src/react-util/useDebouncedEffect.tsx","../src/react-util/useMountEffect.tsx","../src/react-util/useMountedState.ts","../src/react-util/useResize.ts"],"mappings":";;;UAEiB,iBAAA,WAA4B,UAAA;EAC3C,YAAA,GAAe,UAAA,CAAW,CAAA;EAC1B,UAAA;EACA,YAAA;AAAA;AAAA,KAGU,UAAA,IAAc,MAAA,EAAQ,WAAA,KAAgB,IAAA,YAAgB,OAAO;AAAA,KAC7D,aAAA,gBAA6B,IAAA,yBACjC,IAAA,EAAM,IAAA,KAAS,OAAA,CAAQ,KAAA,UACrB,OAAA,CAAQ,KAAA;AAAA,UAED,mBAAA;EACf,GAAA,EAAK,aAAA,CAAc,KAAA,EAAO,IAAA;AAAA;AAAA,UAGX,sBAAA,sBAA4C,mBAAA,CAAoB,KAAA,EAAO,IAAA;EACtF,OAAA;EACA,KAAA,GAAQ,KAAA;EACR,KAAA,GAAQ,KAAA;AAAA;AAAA,UAGO,oBAAA,sBAA0C,mBAAA,CAAoB,KAAA,EAAO,IAAA;EACpF,OAAA;EACA,KAAA,EAAO,KAAA;EACP,KAAA;AAAA;AAAA,UAGe,uBAAA,sBAA6C,mBAAA,CAAoB,KAAA,EAAO,IAAA;EACvF,OAAA;EACA,KAAA;EACA,KAAA,EAAO,KAAA;AAAA;AAAA,KAGJ,UAAA,WAAqB,UAAA,IAAc,OAAA,CAAQ,UAAA,CAAW,CAAA;AAAA,KACtD,SAAA,WAAoB,UAAA,IAAc,UAAA,CAAW,CAAA,iCAAkC,IAAA;AAAA,KAExE,eAAA,gBACR,sBAAA,CAAuB,KAAA,EAAO,IAAA,IAC9B,oBAAA,CAAqB,KAAA,EAAO,IAAA,IAC5B,uBAAA,CAAwB,KAAA,EAAO,IAAA;AAAA,cAEtB,UAAA,aAAwB,UAAA,UAAoB,UAAA,CAAW,CAAA,UAAW,SAAA,CAAU,CAAA,GAAE,EAAA,EACrF,CAAA,EAAC,IAAA,GACC,cAAA,EAAc,OAAA,GACV,iBAAA,CAAkB,CAAA,MAC3B,eAAA,CAAgB,KAAA,EAAO,IAAA;;;cC5Cb,QAAA,aAAsB,UAAA,EAAU,EAAA,EACvC,CAAA,EAAC,IAAA,GACC,cAAA,EAAc,OAAA,GACV,iBAAA,CAAkB,CAAA;EAAO,cAAA;AAAA,MAA0B,eAAA,CAAA,OAAA,CAAA,UAAA,CAAA,CAAA,IAAA,UAAA,CAAA,CAAA,iCAAA,IAAA;;;UCJ9C,2BAAA;EACf,OAAA;EACA,OAAO;AAAA;AAAA,iBAGO,oBAAA,eAAmC,IAAA,eACjD,QAAA,EAAU,CAAA,EACV,IAAA,EAAM,cAAA,EACN,OAAA,GAAU,2BAAA,GA0CE,CAAA;;;iBCjDE,kBAAA,CACd,QAAA,EAAU,cAAA,EACV,IAAA,EAAM,cAAA,EACN,OAAA,GAAU,2BAAA;;;cCJC,cAAA,GAAc,QAAA,EAAc,KAAA,CAAM,cAAc;;;cCAhD,eAAA;;;;;;ALAb;;;;;;;;cMWa,SAAA,GAAS,GAAA,EACf,KAAA,CAAM,SAAS,CAAC,WAAA,UAAmB,QAAA,GAC7B,KAAA,UAAe,MAAA"}
|
package/dist/react-util.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as useResize } from "./useResize-BhJdvtef.mjs";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
3
|
|
|
3
4
|
//#region src/react-util/useAsyncFn.ts
|
|
4
5
|
const useAsyncFn = (fn, deps = [], options) => {
|
|
@@ -126,27 +127,5 @@ const useMountedState = () => {
|
|
|
126
127
|
};
|
|
127
128
|
|
|
128
129
|
//#endregion
|
|
129
|
-
|
|
130
|
-
const useResizeObserver = (ref, onResize) => {
|
|
131
|
-
const onResizeRef = useRef(onResize);
|
|
132
|
-
const handleResize = useCallback(() => {
|
|
133
|
-
if (ref.current) onResizeRef.current(ref.current.clientWidth, ref.current.clientHeight);
|
|
134
|
-
}, [ref]);
|
|
135
|
-
useLayoutEffect(() => {
|
|
136
|
-
const el = ref.current;
|
|
137
|
-
if (!el) return;
|
|
138
|
-
handleResize();
|
|
139
|
-
if (typeof ResizeObserver === "function") {
|
|
140
|
-
const resizeObserver = new ResizeObserver(() => handleResize());
|
|
141
|
-
resizeObserver.observe(el);
|
|
142
|
-
return () => resizeObserver.disconnect();
|
|
143
|
-
} else {
|
|
144
|
-
window.addEventListener("resize", handleResize);
|
|
145
|
-
return () => window.window.removeEventListener("resize", handleResize);
|
|
146
|
-
}
|
|
147
|
-
}, [ref, handleResize]);
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
//#endregion
|
|
151
|
-
export { useAsync, useAsyncFn, useDebouncedCallback, useDebouncedEffect, useMountEffect, useMountedState, useResizeObserver };
|
|
130
|
+
export { useAsync, useAsyncFn, useDebouncedCallback, useDebouncedEffect, useMountEffect, useMountedState, useResize };
|
|
152
131
|
//# sourceMappingURL=react-util.mjs.map
|
package/dist/react-util.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-util.mjs","names":[],"sources":["../src/react-util/useAsyncFn.ts","../src/react-util/useAsync.ts","../src/react-util/useDebouncedCallback.tsx","../src/react-util/useDebouncedEffect.tsx","../src/react-util/useMountEffect.tsx","../src/react-util/useMountedState.ts","../src/react-util/useResizeObserver.tsx"],"sourcesContent":["import { type DependencyList, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncFnOptions<F extends UseAsyncFn> {\n initialValue?: InferValue<F>;\n debounceMs?: number;\n debounceType?: \"leading\" | \"trailing\";\n}\n\nexport type UseAsyncFn = (signal: AbortSignal, ...args: any[]) => Promise<any>;\nexport type UseAsyncFnRun<Value, Args> = Args extends unknown[]\n ? (...args: Args) => Promise<Value>\n : () => Promise<Value>;\n\nexport interface UseAsyncFnStateBase<Value, Args> {\n run: UseAsyncFnRun<Value, Args>;\n}\n\nexport interface UseAsyncFnStateLoading<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: true;\n error?: Error | undefined;\n value?: Value;\n}\n\nexport interface UseAsyncFnStateError<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: false;\n error: Error;\n value?: undefined;\n}\n\nexport interface UseAsyncFnStateResolved<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: false;\n error?: undefined;\n value: Value;\n}\n\ntype InferValue<F extends UseAsyncFn> = Awaited<ReturnType<F>>;\ntype InferArgs<F extends UseAsyncFn> = Parameters<F> extends [any, ...infer Rest] ? Rest : [];\n\nexport type UseAsyncFnState<Value, Args> =\n | UseAsyncFnStateLoading<Value, Args>\n | UseAsyncFnStateError<Value, Args>\n | UseAsyncFnStateResolved<Value, Args>;\n\nexport const useAsyncFn = <F extends UseAsyncFn, Value = InferValue<F>, Args = InferArgs<F>>(\n fn: F,\n deps: DependencyList = [],\n options?: UseAsyncFnOptions<F>,\n): UseAsyncFnState<Value, Args> => {\n const { debounceType = \"leading\", debounceMs = 650 } = options ?? {};\n\n const timeoutRef = useRef<number | undefined>(undefined);\n const abortControllerRef = useRef<AbortController | undefined>(undefined);\n\n const [state, setState] = useState<Omit<UseAsyncFnState<Value, Args>, \"run\">>(\n options?.initialValue ? { loading: false, value: options?.initialValue } : { loading: true },\n );\n\n const run = useCallback((...args: Parameters<F>) => {\n window.clearTimeout(timeoutRef.current);\n\n abortControllerRef.current?.abort();\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n if (!state?.loading) {\n setState((prevState) => ({ ...prevState, loading: true }));\n }\n\n return new Promise((resolve, reject) => {\n const timeoutMs = debounceType === \"leading\" && !timeoutRef.current ? 0 : debounceMs;\n\n timeoutRef.current = window.setTimeout(() => {\n fn(abortController.signal, ...args)\n .then(\n (value) => {\n if (!abortController.signal.aborted) {\n setState({ value, loading: false });\n }\n resolve(value);\n },\n (error) => {\n if (!abortController.signal.aborted) {\n setState({ error, loading: false });\n }\n reject(error);\n },\n )\n .finally(() => {\n timeoutRef.current = undefined;\n });\n }, timeoutMs);\n });\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: deps are controlled by caller\n }, deps);\n\n useEffect(() => {\n return () => abortControllerRef.current?.abort();\n }, []);\n\n return { ...state, run } as UseAsyncFnState<Value, Args>;\n};\n","import { type DependencyList, useEffect, useRef } from \"react\";\nimport { type UseAsyncFn, type UseAsyncFnOptions, useAsyncFn } from \"./useAsyncFn\";\n\nexport const useAsync = <F extends UseAsyncFn>(\n fn: F,\n deps: DependencyList = [],\n options?: UseAsyncFnOptions<F> & { runImmediately?: boolean },\n) => {\n const firstRun = useRef(true);\n\n const { runImmediately = true, ...useAsyncFnOptions } = options ?? {};\n\n const asyncFn = useAsyncFn(fn, deps, useAsyncFnOptions);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: option changes should not trigger effect\n useEffect(() => {\n const isFirstRun = firstRun.current;\n firstRun.current = false;\n\n if (!runImmediately && isFirstRun) return;\n\n // TODO: how should errors be handled? this isn't great...\n void asyncFn.run();\n }, [asyncFn.run]);\n\n return asyncFn;\n};\n","import { type DependencyList, useCallback, useEffect, useRef } from \"react\";\n\nexport interface UseDebouncedCallbackOptions {\n leading?: boolean;\n delayMs?: number;\n}\n\nexport function useDebouncedCallback<T extends (...args: any) => any>(\n callback: T,\n deps: DependencyList,\n options?: UseDebouncedCallbackOptions,\n) {\n const ref = useRef<\n UseDebouncedCallbackOptions & {\n timeout: number | null;\n mounted: boolean;\n leadingTriggered: boolean;\n }\n >({\n ...options,\n timeout: null,\n mounted: false,\n leadingTriggered: options?.leading ?? false,\n });\n\n useEffect(() => {\n const currentRef = ref.current;\n currentRef.mounted = true;\n currentRef.leadingTriggered = false;\n return () => {\n currentRef.mounted = false;\n window.clearTimeout(currentRef.timeout!);\n };\n }, []);\n\n return useCallback((...params: Parameters<T>) => {\n const currentRef = ref.current;\n window.clearTimeout(currentRef.timeout!);\n if (!currentRef.leadingTriggered && currentRef.leading) {\n currentRef.leadingTriggered = true;\n callback(...params);\n currentRef.timeout = window.setTimeout(() => {\n currentRef.leadingTriggered = true;\n }, currentRef.delayMs ?? 1600);\n } else {\n currentRef.timeout = window.setTimeout(() => {\n if (!currentRef.mounted) return;\n callback(...params);\n currentRef.leadingTriggered = false;\n }, currentRef.delayMs ?? 1600);\n }\n // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>\n }, deps) as T;\n}\n","import { type DependencyList, type EffectCallback, useEffect } from \"react\";\nimport { type UseDebouncedCallbackOptions, useDebouncedCallback } from \"./useDebouncedCallback\";\n\nexport function useDebouncedEffect(\n callback: EffectCallback,\n deps: DependencyList,\n options?: UseDebouncedCallbackOptions,\n) {\n const debouncedCallback = useDebouncedCallback(callback, deps, { leading: true, ...options });\n // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>\n return useEffect(debouncedCallback, deps);\n}\n","import { useEffect } from \"react\";\n\nexport const useMountEffect = (effectFn: React.EffectCallback): void => useEffect(effectFn, []);\n","import { useCallback, useEffect, useRef } from \"react\";\n\nexport const useMountedState = (): (() => boolean) => {\n const mountedRef = useRef<boolean>(false);\n const get = useCallback(() => mountedRef.current, []);\n\n useEffect(() => {\n mountedRef.current = true;\n\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return get;\n};\n","import { useCallback, useLayoutEffect, useRef } from \"react\";\n\nexport const useResizeObserver = (\n ref: React.MutableRefObject<HTMLElement | null>,\n onResize: (width: number, height: number) => void,\n): void => {\n const onResizeRef = useRef(onResize);\n const handleResize = useCallback(() => {\n if (ref.current) {\n onResizeRef.current(ref.current.clientWidth, ref.current.clientHeight);\n }\n }, [ref]);\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) {\n return;\n }\n\n handleResize();\n\n if (typeof ResizeObserver === \"function\") {\n const resizeObserver = new ResizeObserver(() => handleResize());\n\n resizeObserver.observe(el);\n\n return () => resizeObserver.disconnect();\n } else {\n window.addEventListener(\"resize\", handleResize);\n\n return () => window.window.removeEventListener(\"resize\", handleResize);\n }\n }, [ref, handleResize]);\n};\n"],"mappings":";;;AA2CA,MAAa,cACX,IACA,OAAuB,CAAC,GACxB,YACiC;CACjC,MAAM,EAAE,eAAe,WAAW,aAAa,QAAQ,WAAW,CAAC;CAEnE,MAAM,aAAa,OAA2B,MAAS;CACvD,MAAM,qBAAqB,OAAoC,MAAS;CAExE,MAAM,CAAC,OAAO,YAAY,SACxB,SAAS,eAAe;EAAE,SAAS;EAAO,OAAO,SAAS;CAAa,IAAI,EAAE,SAAS,KAAK,CAC7F;CAEA,MAAM,MAAM,aAAa,GAAG,SAAwB;EAClD,OAAO,aAAa,WAAW,OAAO;EAEtC,mBAAmB,SAAS,MAAM;EAClC,MAAM,kBAAkB,IAAI,gBAAgB;EAC5C,mBAAmB,UAAU;EAE7B,IAAI,CAAC,OAAO,SACV,UAAU,eAAe;GAAE,GAAG;GAAW,SAAS;EAAK,EAAE;EAG3D,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,YAAY,iBAAiB,aAAa,CAAC,WAAW,UAAU,IAAI;GAE1E,WAAW,UAAU,OAAO,iBAAiB;IAC3C,GAAG,gBAAgB,QAAQ,GAAG,IAAI,CAAC,CAChC,MACE,UAAU;KACT,IAAI,CAAC,gBAAgB,OAAO,SAC1B,SAAS;MAAE;MAAO,SAAS;KAAM,CAAC;KAEpC,QAAQ,KAAK;IACf,IACC,UAAU;KACT,IAAI,CAAC,gBAAgB,OAAO,SAC1B,SAAS;MAAE;MAAO,SAAS;KAAM,CAAC;KAEpC,OAAO,KAAK;I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,mBAAmB;EAChC,GAAG,WAAW,WAAW,IAAI;CAGjC,GAAG,IAAI;AACT;;;;AClDA,SAAgB,mBACd,UACA,MACA,SACA;CAGA,OAAO,UAFmB,qBAAqB,UAAU,MAAM;EAAE,SAAS;EAAM,GAAG;CAAQ,CAE1D,GAAG,IAAI;AAC1C;;;;ACTA,MAAa,kBAAkB,aAAyC,UAAU,UAAU,CAAC,CAAC;;;;ACA9F,MAAa,wBAAyC;CACpD,MAAM,aAAa,OAAgB,KAAK;CACxC,MAAM,MAAM,kBAAkB,WAAW,SAAS,CAAC,CAAC;CAEpD,gBAAgB;EACd,WAAW,UAAU;EAErB,aAAa;GACX,WAAW,UAAU;EACvB;CACF,GAAG,CAAC,CAAC;CAEL,OAAO;AACT;;;;ACbA,MAAa,qBACX,KACA,aACS;CACT,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,eAAe,kBAAkB;EACrC,IAAI,IAAI,SACN,YAAY,QAAQ,IAAI,QAAQ,aAAa,IAAI,QAAQ,YAAY;CAEzE,GAAG,CAAC,GAAG,CAAC;CAER,sBAAsB;EACpB,MAAM,KAAK,IAAI;EACf,IAAI,CAAC,IACH;EAGF,aAAa;EAEb,IAAI,OAAO,mBAAmB,YAAY;GACxC,MAAM,iBAAiB,IAAI,qBAAqB,aAAa,CAAC;GAE9D,eAAe,QAAQ,EAAE;GAEzB,aAAa,eAAe,WAAW;EACzC,OAAO;GACL,OAAO,iBAAiB,UAAU,YAAY;GAE9C,aAAa,OAAO,OAAO,oBAAoB,UAAU,YAAY;EACvE;CACF,GAAG,CAAC,KAAK,YAAY,CAAC;AACxB"}
|
|
1
|
+
{"version":3,"file":"react-util.mjs","names":[],"sources":["../src/react-util/useAsyncFn.ts","../src/react-util/useAsync.ts","../src/react-util/useDebouncedCallback.tsx","../src/react-util/useDebouncedEffect.tsx","../src/react-util/useMountEffect.tsx","../src/react-util/useMountedState.ts"],"sourcesContent":["import { type DependencyList, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncFnOptions<F extends UseAsyncFn> {\n initialValue?: InferValue<F>;\n debounceMs?: number;\n debounceType?: \"leading\" | \"trailing\";\n}\n\nexport type UseAsyncFn = (signal: AbortSignal, ...args: any[]) => Promise<any>;\nexport type UseAsyncFnRun<Value, Args> = Args extends unknown[]\n ? (...args: Args) => Promise<Value>\n : () => Promise<Value>;\n\nexport interface UseAsyncFnStateBase<Value, Args> {\n run: UseAsyncFnRun<Value, Args>;\n}\n\nexport interface UseAsyncFnStateLoading<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: true;\n error?: Error | undefined;\n value?: Value;\n}\n\nexport interface UseAsyncFnStateError<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: false;\n error: Error;\n value?: undefined;\n}\n\nexport interface UseAsyncFnStateResolved<Value, Args> extends UseAsyncFnStateBase<Value, Args> {\n loading: false;\n error?: undefined;\n value: Value;\n}\n\ntype InferValue<F extends UseAsyncFn> = Awaited<ReturnType<F>>;\ntype InferArgs<F extends UseAsyncFn> = Parameters<F> extends [any, ...infer Rest] ? Rest : [];\n\nexport type UseAsyncFnState<Value, Args> =\n | UseAsyncFnStateLoading<Value, Args>\n | UseAsyncFnStateError<Value, Args>\n | UseAsyncFnStateResolved<Value, Args>;\n\nexport const useAsyncFn = <F extends UseAsyncFn, Value = InferValue<F>, Args = InferArgs<F>>(\n fn: F,\n deps: DependencyList = [],\n options?: UseAsyncFnOptions<F>,\n): UseAsyncFnState<Value, Args> => {\n const { debounceType = \"leading\", debounceMs = 650 } = options ?? {};\n\n const timeoutRef = useRef<number | undefined>(undefined);\n const abortControllerRef = useRef<AbortController | undefined>(undefined);\n\n const [state, setState] = useState<Omit<UseAsyncFnState<Value, Args>, \"run\">>(\n options?.initialValue ? { loading: false, value: options?.initialValue } : { loading: true },\n );\n\n const run = useCallback((...args: Parameters<F>) => {\n window.clearTimeout(timeoutRef.current);\n\n abortControllerRef.current?.abort();\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n if (!state?.loading) {\n setState((prevState) => ({ ...prevState, loading: true }));\n }\n\n return new Promise((resolve, reject) => {\n const timeoutMs = debounceType === \"leading\" && !timeoutRef.current ? 0 : debounceMs;\n\n timeoutRef.current = window.setTimeout(() => {\n fn(abortController.signal, ...args)\n .then(\n (value) => {\n if (!abortController.signal.aborted) {\n setState({ value, loading: false });\n }\n resolve(value);\n },\n (error) => {\n if (!abortController.signal.aborted) {\n setState({ error, loading: false });\n }\n reject(error);\n },\n )\n .finally(() => {\n timeoutRef.current = undefined;\n });\n }, timeoutMs);\n });\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: deps are controlled by caller\n }, deps);\n\n useEffect(() => {\n return () => abortControllerRef.current?.abort();\n }, []);\n\n return { ...state, run } as UseAsyncFnState<Value, Args>;\n};\n","import { type DependencyList, useEffect, useRef } from \"react\";\nimport { type UseAsyncFn, type UseAsyncFnOptions, useAsyncFn } from \"./useAsyncFn\";\n\nexport const useAsync = <F extends UseAsyncFn>(\n fn: F,\n deps: DependencyList = [],\n options?: UseAsyncFnOptions<F> & { runImmediately?: boolean },\n) => {\n const firstRun = useRef(true);\n\n const { runImmediately = true, ...useAsyncFnOptions } = options ?? {};\n\n const asyncFn = useAsyncFn(fn, deps, useAsyncFnOptions);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: option changes should not trigger effect\n useEffect(() => {\n const isFirstRun = firstRun.current;\n firstRun.current = false;\n\n if (!runImmediately && isFirstRun) return;\n\n // TODO: how should errors be handled? this isn't great...\n void asyncFn.run();\n }, [asyncFn.run]);\n\n return asyncFn;\n};\n","import { type DependencyList, useCallback, useEffect, useRef } from \"react\";\n\nexport interface UseDebouncedCallbackOptions {\n leading?: boolean;\n delayMs?: number;\n}\n\nexport function useDebouncedCallback<T extends (...args: any) => any>(\n callback: T,\n deps: DependencyList,\n options?: UseDebouncedCallbackOptions,\n) {\n const ref = useRef<\n UseDebouncedCallbackOptions & {\n timeout: number | null;\n mounted: boolean;\n leadingTriggered: boolean;\n }\n >({\n ...options,\n timeout: null,\n mounted: false,\n leadingTriggered: options?.leading ?? false,\n });\n\n useEffect(() => {\n const currentRef = ref.current;\n currentRef.mounted = true;\n currentRef.leadingTriggered = false;\n return () => {\n currentRef.mounted = false;\n window.clearTimeout(currentRef.timeout!);\n };\n }, []);\n\n return useCallback((...params: Parameters<T>) => {\n const currentRef = ref.current;\n window.clearTimeout(currentRef.timeout!);\n if (!currentRef.leadingTriggered && currentRef.leading) {\n currentRef.leadingTriggered = true;\n callback(...params);\n currentRef.timeout = window.setTimeout(() => {\n currentRef.leadingTriggered = true;\n }, currentRef.delayMs ?? 1600);\n } else {\n currentRef.timeout = window.setTimeout(() => {\n if (!currentRef.mounted) return;\n callback(...params);\n currentRef.leadingTriggered = false;\n }, currentRef.delayMs ?? 1600);\n }\n // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>\n }, deps) as T;\n}\n","import { type DependencyList, type EffectCallback, useEffect } from \"react\";\nimport { type UseDebouncedCallbackOptions, useDebouncedCallback } from \"./useDebouncedCallback\";\n\nexport function useDebouncedEffect(\n callback: EffectCallback,\n deps: DependencyList,\n options?: UseDebouncedCallbackOptions,\n) {\n const debouncedCallback = useDebouncedCallback(callback, deps, { leading: true, ...options });\n // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>\n return useEffect(debouncedCallback, deps);\n}\n","import { useEffect } from \"react\";\n\nexport const useMountEffect = (effectFn: React.EffectCallback): void => useEffect(effectFn, []);\n","import { useCallback, useEffect, useRef } from \"react\";\n\nexport const useMountedState = (): (() => boolean) => {\n const mountedRef = useRef<boolean>(false);\n const get = useCallback(() => mountedRef.current, []);\n\n useEffect(() => {\n mountedRef.current = true;\n\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return get;\n};\n"],"mappings":";;;;AA2CA,MAAa,cACX,IACA,OAAuB,CAAC,GACxB,YACiC;CACjC,MAAM,EAAE,eAAe,WAAW,aAAa,QAAQ,WAAW,CAAC;CAEnE,MAAM,a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