functype-react 1.21.0 → 1.21.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 +17 -20
- package/dist/TaskState-DWxGWqXf.d.ts +24 -0
- package/dist/async/TaskState.d.ts +2 -0
- package/dist/async/index.d.ts +9 -7
- package/dist/async/index.js +1 -1
- package/dist/async/index.js.map +1 -1
- package/dist/async/useTask.d.ts +24 -0
- package/dist/async/useTask.js +2 -0
- package/dist/async/useTask.js.map +1 -0
- package/dist/async/useTaskPromise.d.ts +14 -0
- package/dist/async/useTaskPromise.js +2 -0
- package/dist/async/useTaskPromise.js.map +1 -0
- package/dist/async/useTaskValue.d.ts +24 -0
- package/dist/async/useTaskValue.js +2 -0
- package/dist/async/useTaskValue.js.map +1 -0
- package/dist/{eq-CR56QmPb.d.ts → eq-CK6oQqWG.d.ts} +3 -1
- package/dist/forms/Validated.d.ts +2 -0
- package/dist/forms/Validated.js.map +1 -1
- package/dist/forms/useValidatedField.d.ts +2 -0
- package/dist/forms/useValidatedField.js.map +1 -1
- package/dist/forms/useValidatedForm.d.ts +2 -0
- package/dist/forms/useValidatedForm.js.map +1 -1
- package/dist/hooks/eq.d.ts +1 -1
- package/dist/hooks/eq.js.map +1 -1
- package/dist/hooks/index.d.ts +9 -9
- package/dist/hooks/useEither.d.ts +1 -1
- package/dist/hooks/useEither.js.map +1 -1
- package/dist/hooks/useList.d.ts +1 -1
- package/dist/hooks/useList.js.map +1 -1
- package/dist/hooks/useOption.d.ts +1 -1
- package/dist/hooks/useOption.js.map +1 -1
- package/dist/hooks/useStableCallback.d.ts +1 -1
- package/dist/hooks/useStableCallback.js.map +1 -1
- package/dist/hooks/useStableEffect.d.ts +1 -1
- package/dist/hooks/useStableEffect.js.map +1 -1
- package/dist/hooks/useStableMemo.d.ts +1 -1
- package/dist/hooks/useStableMemo.js.map +1 -1
- package/dist/hooks/useStableState.d.ts +1 -1
- package/dist/hooks/useStableState.js.map +1 -1
- package/dist/hooks/useTry.d.ts +1 -1
- package/dist/hooks/useTry.js.map +1 -1
- package/dist/{index-Dr09mq-A.d.ts → index-DjzwkXMF.d.ts} +9 -1
- package/dist/index.d.ts +10 -10
- package/dist/match/index.d.ts +1 -1
- package/dist/match/index.js +1 -1
- package/dist/match-CkGESkj9.js.map +1 -1
- package/dist/query/IOQueryError.d.ts +2 -0
- package/dist/query/IOQueryError.js.map +1 -1
- package/dist/query/ioQueryFn.d.ts +4 -3
- package/dist/query/ioQueryFn.js +1 -1
- package/dist/query/ioQueryFn.js.map +1 -1
- package/dist/query/queryState.d.ts +10 -8
- package/dist/query/queryState.js.map +1 -1
- package/dist/query/useIOMutation.d.ts +2 -0
- package/dist/query/useIOMutation.js.map +1 -1
- package/dist/query/useIOMutationState.d.ts +6 -4
- package/dist/query/useIOMutationState.js.map +1 -1
- package/dist/query/useIOQuery.d.ts +2 -0
- package/dist/query/useIOQuery.js.map +1 -1
- package/dist/query/useIOQueryState.d.ts +7 -5
- package/dist/query/useIOQueryState.js.map +1 -1
- package/dist/{useEither-D1Rn_tLR.d.ts → useEither-DyPW7OaA.d.ts} +3 -1
- package/dist/{useList-C_7X5OA_.d.ts → useList-B5Iox1xv.d.ts} +3 -1
- package/dist/{useOption-B8UyOh8h.d.ts → useOption-CXXNC1_S.d.ts} +3 -1
- package/dist/{useStableCallback-C5jd1hKf.d.ts → useStableCallback-CXQQOhl6.d.ts} +4 -2
- package/dist/{useStableEffect-BiDhoNpC.d.ts → useStableEffect-C-5NCd1T.d.ts} +4 -2
- package/dist/{useStableMemo-DCeNIpt5.d.ts → useStableMemo-PYyLBWwd.d.ts} +4 -2
- package/dist/{useStableState-BPVQ-XMX.d.ts → useStableState-fi6nURHS.d.ts} +4 -2
- package/dist/{useTry-ie1X0NiH.d.ts → useTry-B0HIcFFb.d.ts} +3 -1
- package/package.json +10 -10
- package/dist/AsyncState-DxKw9NF6.d.ts +0 -21
- package/dist/async/AsyncState.d.ts +0 -2
- package/dist/async/useIO.d.ts +0 -27
- package/dist/async/useIO.js +0 -2
- package/dist/async/useIO.js.map +0 -1
- package/dist/async/useIOPromise.d.ts +0 -15
- package/dist/async/useIOPromise.js +0 -2
- package/dist/async/useIOPromise.js.map +0 -1
- package/dist/async/useIOValue.d.ts +0 -24
- package/dist/async/useIOValue.js +0 -2
- package/dist/async/useIOValue.js.map +0 -1
- /package/dist/async/{AsyncState.js → TaskState.js} +0 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ React bindings for the [functype](https://github.com/jordanburke/functype) funct
|
|
|
4
4
|
|
|
5
5
|
## Thesis
|
|
6
6
|
|
|
7
|
-
Push the same ADTs (`Option`, `Either`, `Try`, `
|
|
7
|
+
Push the same ADTs (`Option`, `Either`, `Try`, `Task`, `Validated`) you already trust on the server-side into React component boundaries, so design/requirement errors fail compilation in the UI layer instead of leaking through as `data && !error && !loading` flag soup.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -20,7 +20,7 @@ pnpm add functype functype-react react react-dom
|
|
|
20
20
|
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
21
21
|
| `functype-react` (main) | Stable hooks (`useStable*`), ADT hooks (`useOption`, `useEither`, `useTry`, `useList`), `Match` family components, equality helpers |
|
|
22
22
|
| `functype-react/match` | `<Match>`, `<MatchOption>`, `<MatchEither>`, `<MatchTry>` (also re-exported from main) |
|
|
23
|
-
| `functype-react/async` | `
|
|
23
|
+
| `functype-react/async` | `useTask`, `useTaskPromise`, `useTaskValue` (React 19 `use()` bridge), `<TaskBoundary>` |
|
|
24
24
|
| `functype-react/forms` | `Validated<E, A>` type alias, `useValidatedField`, `useValidatedForm` |
|
|
25
25
|
| `functype-react/query` | `useIOQuery(State)`, `useIOMutation(State)`, `ioQueryFn`, `ioMutationFn`, `IOQueryError`, `toQueryState` — TanStack Query adapters for `IO` |
|
|
26
26
|
|
|
@@ -71,38 +71,35 @@ import { Match, MatchOption } from "functype-react"
|
|
|
71
71
|
|
|
72
72
|
Omitting a `_tag` case is a compile error.
|
|
73
73
|
|
|
74
|
-
## Tier 3 — async /
|
|
74
|
+
## Tier 3 — async / Task
|
|
75
75
|
|
|
76
76
|
```ts
|
|
77
|
-
import {
|
|
78
|
-
import { useIO } from "functype-react/async"
|
|
77
|
+
import { useTask } from "functype-react/async"
|
|
79
78
|
|
|
80
79
|
function UserPanel({ id }: { id: string }) {
|
|
81
|
-
const state =
|
|
80
|
+
const state = useTask((signal) => fetch(`/users/${id}`, { signal }).then((r) => r.json()), [id])
|
|
82
81
|
if (state.isPending) return <Spinner />
|
|
83
|
-
if (state.isFailure) return <Err err={state.error} />
|
|
82
|
+
if (state.isFailure) return <Err err={state.error} />
|
|
84
83
|
return state.isSuccess ? <Profile user={state.value} /> : null
|
|
85
84
|
}
|
|
86
85
|
```
|
|
87
86
|
|
|
88
|
-
On unmount or a `deps` change the signal aborts, and the effect stops at its next step (no further retries, polls or `flatMap`s run). A typed failure becomes `Failure`; a defect is rethrown to the nearest error boundary.
|
|
89
|
-
|
|
90
87
|
For React 19 `use()` + Suspense:
|
|
91
88
|
|
|
92
89
|
```tsx
|
|
93
|
-
import {
|
|
90
|
+
import { TaskBoundary, useTaskValue } from "functype-react/async"
|
|
94
91
|
|
|
95
92
|
function UserPanel({ id }: { id: string }) {
|
|
96
|
-
const user =
|
|
93
|
+
const user = useTaskValue((signal) => fetch(`/users/${id}`, { signal }).then((r) => r.json()), [id])
|
|
97
94
|
return <Profile user={user} />
|
|
98
95
|
}
|
|
99
96
|
|
|
100
|
-
;<
|
|
97
|
+
;<TaskBoundary pending={<Spinner />} fallback={(err, reset) => <ErrorPanel err={err} onRetry={reset} />}>
|
|
101
98
|
<UserPanel id="42" />
|
|
102
|
-
</
|
|
99
|
+
</TaskBoundary>
|
|
103
100
|
```
|
|
104
101
|
|
|
105
|
-
`
|
|
102
|
+
`useTaskValue` requires React 19. See the JSDoc on the hook for invariant documentation (stable promise refs, ErrorBoundary outside Suspense, no SSR).
|
|
106
103
|
|
|
107
104
|
## Tier 4 — forms with accumulating validation
|
|
108
105
|
|
|
@@ -168,7 +165,7 @@ if (error) {
|
|
|
168
165
|
|
|
169
166
|
### Matching instead of flag soup
|
|
170
167
|
|
|
171
|
-
The result above is still React Query's — `data` is `A | undefined`, so the success path needs a `!` or a guard. `toQueryState` projects it onto the same `
|
|
168
|
+
The result above is still React Query's — `data` is `A | undefined`, so the success path needs a `!` or a guard. `toQueryState` projects it onto the same `TaskState` ADT that `functype-react/async` returns, so a query matches exhaustively like any other functype value:
|
|
172
169
|
|
|
173
170
|
```tsx
|
|
174
171
|
import { Match } from "functype-react"
|
|
@@ -194,7 +191,7 @@ function UserPanel({ id }: { id: string }) {
|
|
|
194
191
|
|
|
195
192
|
The projection is a pure function over the result, so you keep everything else React Query gives you (`refetch`, `isFetching`, `dataUpdatedAt`) on the original object. (Invalidation is a client-level operation — `queryClient.invalidateQueries()` — not a method on the result.)
|
|
196
193
|
|
|
197
|
-
If the ADT is all you need, `useIOQueryState` skips the projection step — it returns `
|
|
194
|
+
If the ADT is all you need, `useIOQueryState` skips the projection step — it returns `TaskState` directly, plus the `isIdle`/`isPending`/`isSuccess`/`isFailure` flags and `refetch`, mirroring what `useTask` returns in Tier 3:
|
|
198
195
|
|
|
199
196
|
```tsx
|
|
200
197
|
const user = useIOQueryState(["user", id], ({ signal }) => Http.get<User>(url, { signal }))
|
|
@@ -215,8 +212,8 @@ Both read only the fields they project. For **queries** that matters: React Quer
|
|
|
215
212
|
|
|
216
213
|
Two behaviours worth knowing before you rely on the ADT:
|
|
217
214
|
|
|
218
|
-
- **A failed background refetch projects to `Failure` even though React Query still holds the last successful `data`.** `
|
|
219
|
-
- **`defect: true` means `.error` is not an `E`** — check it before matching on `_tag`. It is set when the effect factory throws before an `IO` is produced, when the effect produces a defect (`Exit.Die`: a throwing `IO.sync` thunk, a throwing `map`/`flatMap`/`mapError` callback, or `IO.die`), or when the effect is interrupted
|
|
215
|
+
- **A failed background refetch projects to `Failure` even though React Query still holds the last successful `data`.** `TaskState` has no "loaded but stale" variant. This is the deliberate default — it never silently hides a failure — but it does mean a transient refetch error flips a loaded view to the error branch. To keep rendering stale data, read `query.data` alongside the projection or branch on `query.isRefetchError` before projecting.
|
|
216
|
+
- **`defect: true` means `.error` is not an `E`** — check it before matching on `_tag`. It is set when the effect factory throws before an `IO` is produced, when the effect produces a defect (`Exit.Die`: a throwing `IO.sync` thunk, a throwing `map`/`flatMap`/`mapError` callback, or `IO.die`), or when the effect is interrupted. Conversely `defect: false` genuinely means `.error` is an `E` — the bridge reads `runExit()`, so it can see the difference. (It previously read `run()`, whose `Either` could not, so a defect arrived indistinguishable from a typed failure and the flag read `false`.)
|
|
220
217
|
|
|
221
218
|
Mutations mirror the shape (React Query supplies no `AbortSignal` to mutations, so the callback takes only the variables):
|
|
222
219
|
|
|
@@ -258,7 +255,7 @@ Both the hooks and the primitives are generic over any `IO<never, E, A>` — not
|
|
|
258
255
|
## Compatibility
|
|
259
256
|
|
|
260
257
|
- **TypeScript**: `strict: true` + `noUncheckedIndexedAccess: true`. Loose configs will silently lose the type-level exhaustiveness guarantees.
|
|
261
|
-
- **React**: peer dep range `>=18 <20`. Tier 3's `
|
|
258
|
+
- **React**: peer dep range `>=18 <20`. Tier 3's `useTaskValue` (and consequently anything that depends on React 19's `use()` hook) is React-19-only at runtime; the rest of the package works on both.
|
|
262
259
|
- **SSR / RSC**: hooks are client-only and marked with `"use client"`. `<Match>` family components are pure and render fine in Server Components.
|
|
263
260
|
- **React Query**: Tier 5 targets `@tanstack/react-query` v5 (`>=5.0.0`), an optional peer. The `ioQueryFn` / `ioMutationFn` primitives type their context structurally, so they carry no `@tanstack` types and are unaffected by its major-version churn.
|
|
264
261
|
|
|
@@ -293,7 +290,7 @@ They work without type information and are more precise with it (`parserOptions.
|
|
|
293
290
|
|
|
294
291
|
- `./optics` subpath (`useLens`, `useOptional`, `useSelector`) — blocked on core not shipping a lens module yet.
|
|
295
292
|
- Codemods, Storybook, cookbook recipes on the Astro site.
|
|
296
|
-
- Playwright browser-based testing for `
|
|
293
|
+
- Playwright browser-based testing for `useTaskValue` + `<TaskBoundary>` (jsdom doesn't unsuspend React 19's `use()` reliably).
|
|
297
294
|
|
|
298
295
|
## License
|
|
299
296
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/async/TaskState.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Lifecycle state of an async operation managed by `useTask`.
|
|
4
|
+
*
|
|
5
|
+
* Note: the tag values are `Idle | Pending | Success | Failure` — these are
|
|
6
|
+
* the consumer-facing lifecycle phases, intentionally broader than functype
|
|
7
|
+
* core's `TaskOutcome<T>` (which has only `Ok | Err`). The hook maps
|
|
8
|
+
* `TaskOutcome.Ok → Success`, `TaskOutcome.Err → Failure`, and adds `Idle`
|
|
9
|
+
* (pre-mount) and `Pending` (in flight) for the rendering side.
|
|
10
|
+
*/
|
|
11
|
+
type TaskState<E, A> = {
|
|
12
|
+
readonly _tag: "Idle";
|
|
13
|
+
} | {
|
|
14
|
+
readonly _tag: "Pending";
|
|
15
|
+
} | {
|
|
16
|
+
readonly _tag: "Success";
|
|
17
|
+
readonly value: A;
|
|
18
|
+
} | {
|
|
19
|
+
readonly _tag: "Failure";
|
|
20
|
+
readonly error: E;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { TaskState as t };
|
|
24
|
+
//# sourceMappingURL=TaskState-DWxGWqXf.d.ts.map
|
package/dist/async/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { t as TaskState } from "../TaskState-DWxGWqXf.js";
|
|
2
|
+
import { UseTaskResult, useTask } from "./useTask.js";
|
|
3
|
+
import { useTaskPromise } from "./useTaskPromise.js";
|
|
4
|
+
import { useTaskValue } from "./useTaskValue.js";
|
|
5
5
|
import { ReactElement, ReactNode } from "react";
|
|
6
|
+
//#region src/async/TaskBoundary.d.ts
|
|
6
7
|
type Props = {
|
|
7
8
|
readonly pending: ReactNode;
|
|
8
9
|
readonly fallback: (error: unknown, reset: () => void) => ReactNode;
|
|
9
10
|
readonly children: ReactNode;
|
|
10
11
|
};
|
|
11
12
|
/**
|
|
12
|
-
* Combines `<Suspense>` (for pending
|
|
13
|
+
* Combines `<Suspense>` (for pending Tasks consumed via `useTaskValue`) with
|
|
13
14
|
* an ErrorBoundary that catches thrown failures. The `fallback` render prop
|
|
14
15
|
* receives the thrown value (typed `unknown` — consumers narrow) and a
|
|
15
16
|
* `reset` callback that clears the error so children can be re-attempted.
|
|
@@ -17,6 +18,7 @@ type Props = {
|
|
|
17
18
|
* The ErrorBoundary wraps the Suspense, matching React's documented rule
|
|
18
19
|
* (otherwise Suspense would catch errors instead of the boundary).
|
|
19
20
|
*/
|
|
20
|
-
export declare function
|
|
21
|
-
|
|
21
|
+
export declare function TaskBoundary(props: Props): ReactElement;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { type TaskState, type UseTaskResult, useTask, useTaskPromise, useTaskValue };
|
|
22
24
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/async/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useTask as e}from"./useTask.js";import{useTaskPromise as t}from"./useTaskPromise.js";import{useTaskValue as n}from"./useTaskValue.js";import{Component as r,Suspense as i}from"react";import{jsx as a}from"react/jsx-runtime";var o=class extends r{constructor(...e){super(...e),this.state={_tag:`Ok`},this.reset=()=>{this.setState({_tag:`Ok`})}}static getDerivedStateFromError(e){return{_tag:`Errored`,error:e}}componentDidCatch(e,t){}render(){return this.state._tag===`Errored`?this.props.fallback(this.state.error,this.reset):this.props.children}};function s(e){return/* @__PURE__ */ a(o,{fallback:e.fallback,children:/* @__PURE__ */ a(i,{fallback:e.pending,children:e.children})})}export{s as TaskBoundary,e as useTask,t as useTaskPromise,n as useTaskValue};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/async/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["TaskErrorBoundary","Component","_args","TaskBoundary","props","Suspense","useTask","useTaskPromise","useTaskValue"],"sources":["../../src/async/TaskBoundary.tsx"],"sourcesContent":["\"use client\"\n\nimport { Component, type ErrorInfo, type ReactElement, type ReactNode, Suspense } from \"react\"\n\ntype Props = {\n readonly pending: ReactNode\n readonly fallback: (error: unknown, reset: () => void) => ReactNode\n readonly children: ReactNode\n}\n\ntype State = { readonly _tag: \"Ok\" } | { readonly _tag: \"Errored\"; readonly error: unknown }\n\nclass TaskErrorBoundary extends Component<\n { readonly fallback: Props[\"fallback\"]; readonly children: ReactNode },\n State\n> {\n override state: State = { _tag: \"Ok\" }\n\n static getDerivedStateFromError(error: unknown): State {\n return { _tag: \"Errored\", error }\n }\n\n override componentDidCatch(_error: unknown, _info: ErrorInfo): void {\n // hook for telemetry; intentionally noop in v0.1\n }\n\n reset = (): void => {\n this.setState({ _tag: \"Ok\" })\n }\n\n override render(): ReactNode {\n if (this.state._tag === \"Errored\") {\n return this.props.fallback(this.state.error, this.reset)\n }\n return this.props.children\n }\n}\n\n/**\n * Combines `<Suspense>` (for pending Tasks consumed via `useTaskValue`) with\n * an ErrorBoundary that catches thrown failures. The `fallback` render prop\n * receives the thrown value (typed `unknown` — consumers narrow) and a\n * `reset` callback that clears the error so children can be re-attempted.\n *\n * The ErrorBoundary wraps the Suspense, matching React's documented rule\n * (otherwise Suspense would catch errors instead of the boundary).\n */\nexport function TaskBoundary(props: Props): ReactElement {\n return (\n <TaskErrorBoundary fallback={props.fallback}>\n <Suspense fallback={props.pending}>{props.children}</Suspense>\n </TaskErrorBoundary>\n )\n}\n"],"mappings":"qOAYA,IAAMA,EAAN,cAAgCC,CAG9B,+BACA,KAAS,MAAe,CAAE,KAAM,IAAK,EAUrC,KAAA,UAAoB,CAClB,KAAK,SAAS,CAAE,KAAM,IAAK,CAAC,CAC9B,EAVA,OAAO,yBAAyB,EAAuB,CACrD,MAAO,CAAE,KAAM,UAAW,OAAM,CAClC,CAEA,kBAA2B,EAAiB,EAAwB,CAEpE,CAMA,QAA6B,CAI3B,OAHI,KAAK,MAAM,OAAS,UACf,KAAK,MAAM,SAAS,KAAK,MAAM,MAAO,KAAK,KAAK,EAElD,KAAK,MAAM,QACpB,CACF,EAWA,SAAgBE,EAAa,EAA4B,CACvD,MACE,kBAACH,EAAD,CAAmB,SAAUI,EAAM,SACjC,SAAA,kBAACC,EAAD,CAAU,SAAUD,EAAM,QAAU,SAAAA,EAAM,QAAmB,CAAA,CAC5C,CAAA,CAEvB"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { t as TaskState } from "../TaskState-DWxGWqXf.js";
|
|
2
|
+
import { Throwable } from "functype";
|
|
3
|
+
//#region src/async/useTask.d.ts
|
|
4
|
+
export type UseTaskResult<E, A> = TaskState<E, A> & {
|
|
5
|
+
readonly isIdle: boolean;
|
|
6
|
+
readonly isPending: boolean;
|
|
7
|
+
readonly isSuccess: boolean;
|
|
8
|
+
readonly isFailure: boolean;
|
|
9
|
+
refetch: () => void;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Run an async operation tied to a React component's lifecycle.
|
|
13
|
+
*
|
|
14
|
+
* - Returns a discriminated `TaskState<Throwable, A>` plus boolean flags and
|
|
15
|
+
* a `refetch` trigger.
|
|
16
|
+
* - The `task` callback receives an `AbortSignal` wired to a cancellation
|
|
17
|
+
* token that fires when the component unmounts or `deps` change. Pass the
|
|
18
|
+
* signal to `fetch` (or any abortable API) to cancel in-flight work.
|
|
19
|
+
* - StrictMode-safe: the cleanup fn cancels the token and discards any
|
|
20
|
+
* late-arriving result.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useTask<A>(task: (signal: AbortSignal) => Promise<A> | A, deps: ReadonlyArray<unknown>): UseTaskResult<Throwable, A>;
|
|
23
|
+
//#endregion
|
|
24
|
+
//# sourceMappingURL=useTask.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";import{useCallback as e,useEffect as t,useReducer as n,useRef as r}from"react";import{Task as i,createCancellationTokenSource as a}from"functype";function o(e,t){return t.type===`PENDING`?{_tag:`Pending`}:t.type===`SUCCESS`?{_tag:`Success`,value:t.value}:{_tag:`Failure`,error:t.error}}function s(s,c){let[l,u]=n(o,{_tag:`Idle`}),[d,f]=n(e=>e+1,0),p=r(s);p.current=s,t(()=>{let e={value:!1},t=a();return u({type:`PENDING`}),i().Async(()=>p.current(t.token.signal),void 0,void 0,t.token).then(t=>{e.value||(t.isOk()?u({type:`SUCCESS`,value:t.value}):u({type:`FAILURE`,error:t.error}))}),()=>{e.value=!0,t.cancel()}},[...c,d]);let m=e(()=>f(),[]);return{...l,isIdle:l._tag===`Idle`,isPending:l._tag===`Pending`,isSuccess:l._tag===`Success`,isFailure:l._tag===`Failure`,refetch:m}}export{s as useTask};
|
|
2
|
+
//# sourceMappingURL=useTask.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTask.js","names":["reducer","action","useTask","state","dispatch","useReducer","refetchTick","forceRefetch","n","taskRef","useRef","task","useEffect","cancelled","tokenSource","createCancellationTokenSource","Task","outcome","deps","refetch","useCallback"],"sources":["../../src/async/useTask.ts"],"sourcesContent":["\"use client\"\n\nimport { createCancellationTokenSource, Task, type Throwable } from \"functype\"\nimport { useCallback, useEffect, useReducer, useRef } from \"react\"\n\nimport type { TaskState } from \"./TaskState\"\n\ntype Action<E, A> =\n | { readonly type: \"PENDING\" }\n | { readonly type: \"SUCCESS\"; readonly value: A }\n | { readonly type: \"FAILURE\"; readonly error: E }\n\nfunction reducer<E, A>(_state: TaskState<E, A>, action: Action<E, A>): TaskState<E, A> {\n if (action.type === \"PENDING\") return { _tag: \"Pending\" }\n if (action.type === \"SUCCESS\") return { _tag: \"Success\", value: action.value }\n return { _tag: \"Failure\", error: action.error }\n}\n\nexport type UseTaskResult<E, A> = TaskState<E, A> & {\n readonly isIdle: boolean\n readonly isPending: boolean\n readonly isSuccess: boolean\n readonly isFailure: boolean\n refetch: () => void\n}\n\n/**\n * Run an async operation tied to a React component's lifecycle.\n *\n * - Returns a discriminated `TaskState<Throwable, A>` plus boolean flags and\n * a `refetch` trigger.\n * - The `task` callback receives an `AbortSignal` wired to a cancellation\n * token that fires when the component unmounts or `deps` change. Pass the\n * signal to `fetch` (or any abortable API) to cancel in-flight work.\n * - StrictMode-safe: the cleanup fn cancels the token and discards any\n * late-arriving result.\n */\nexport function useTask<A>(\n task: (signal: AbortSignal) => Promise<A> | A,\n deps: ReadonlyArray<unknown>,\n): UseTaskResult<Throwable, A> {\n const [state, dispatch] = useReducer(reducer<Throwable, A>, { _tag: \"Idle\" })\n const [refetchTick, forceRefetch] = useReducer((n: number) => n + 1, 0)\n const taskRef = useRef(task)\n taskRef.current = task\n\n useEffect(() => {\n const cancelled = { value: false }\n const tokenSource = createCancellationTokenSource()\n dispatch({ type: \"PENDING\" })\n\n void Task<A>()\n .Async<A>(() => taskRef.current(tokenSource.token.signal) as Promise<A>, undefined, undefined, tokenSource.token)\n .then((outcome) => {\n if (cancelled.value) return\n if (outcome.isOk()) {\n dispatch({ type: \"SUCCESS\", value: outcome.value as A })\n } else {\n dispatch({ type: \"FAILURE\", error: outcome.error as Throwable })\n }\n })\n\n return () => {\n cancelled.value = true\n tokenSource.cancel()\n }\n }, [...deps, refetchTick])\n\n const refetch = useCallback(() => forceRefetch(), [])\n\n return {\n ...state,\n isIdle: state._tag === \"Idle\",\n isPending: state._tag === \"Pending\",\n isSuccess: state._tag === \"Success\",\n isFailure: state._tag === \"Failure\",\n refetch,\n }\n}\n"],"mappings":"+JAYA,SAASA,EAAc,EAAyB,EAAuC,CAGrF,OAFIC,EAAO,OAAS,UAAkB,CAAE,KAAM,SAAU,EACpDA,EAAO,OAAS,UAAkB,CAAE,KAAM,UAAW,MAAOA,EAAO,KAAM,EACtE,CAAE,KAAM,UAAW,MAAOA,EAAO,KAAM,CAChD,CAqBA,SAAgBC,EACd,EACA,EAC6B,CAC7B,GAAM,CAACC,EAAOC,GAAYC,EAAWL,EAAuB,CAAE,KAAM,MAAO,CAAC,EACtE,CAACM,EAAaC,GAAgBF,EAAY,GAAcG,EAAI,EAAG,CAAC,EAChEC,EAAUC,EAAOC,CAAI,EAC3B,EAAQ,QAAUA,EAElBC,MAAgB,CACd,IAAMC,EAAY,CAAE,MAAO,EAAM,EAC3BC,EAAcC,EAA8B,EAclD,OAbAX,EAAS,CAAE,KAAM,SAAU,CAAC,EAE5BY,EAAa,CAAC,CACX,UAAeP,EAAQ,QAAQK,EAAY,MAAM,MAAM,EAAiB,IAAA,GAAW,IAAA,GAAWA,EAAY,KAAK,CAAC,CAChH,KAAM,GAAY,CACbD,EAAU,QACVI,EAAQ,KAAK,EACfb,EAAS,CAAE,KAAM,UAAW,MAAOa,EAAQ,KAAW,CAAC,EAEvDb,EAAS,CAAE,KAAM,UAAW,MAAOa,EAAQ,KAAmB,CAAC,EAEnE,CAAC,MAEU,CACX,EAAU,MAAQ,GAClBH,EAAY,OAAO,CACrB,CACF,EAAG,CAAC,GAAGI,EAAMZ,CAAW,CAAC,EAEzB,IAAMa,EAAUC,MAAkBb,EAAa,EAAG,CAAC,CAAC,EAEpD,MAAO,CACL,GAAGJ,EACH,OAAQA,EAAM,OAAS,OACvB,UAAWA,EAAM,OAAS,UAC1B,UAAWA,EAAM,OAAS,UAC1B,UAAWA,EAAM,OAAS,UAC1B,SACF,CACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TaskOutcome } from "functype";
|
|
2
|
+
//#region src/async/useTaskPromise.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Returns a `Promise<TaskOutcome<A>>` that is stable across renders with the
|
|
5
|
+
* same `deps`. Intended for consumers of React 19's `use()` hook — providing
|
|
6
|
+
* a new promise reference on each render would infinite-suspend.
|
|
7
|
+
*
|
|
8
|
+
* The `task` callback is read through a ref, so the latest closure is invoked
|
|
9
|
+
* even if it isn't included in `deps`. Encode in `deps` whatever semantically
|
|
10
|
+
* changes the task's result.
|
|
11
|
+
*/
|
|
12
|
+
export declare function useTaskPromise<A>(task: (signal: AbortSignal) => Promise<A> | A, deps: ReadonlyArray<unknown>): Promise<TaskOutcome<A>>;
|
|
13
|
+
//#endregion
|
|
14
|
+
//# sourceMappingURL=useTaskPromise.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";import{useMemo as e,useRef as t}from"react";import{Task as n,createCancellationTokenSource as r}from"functype";function i(i,a){let o=t(i);return o.current=i,e(()=>{let e=r();return n().Async(()=>o.current(e.token.signal),void 0,void 0,e.token)},a)}export{i as useTaskPromise};
|
|
2
|
+
//# sourceMappingURL=useTaskPromise.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTaskPromise.js","names":["useTaskPromise","taskRef","useRef","task","useMemo","tokenSource","createCancellationTokenSource","Task","deps"],"sources":["../../src/async/useTaskPromise.ts"],"sourcesContent":["\"use client\"\n\nimport { createCancellationTokenSource, Task, type TaskOutcome } from \"functype\"\nimport { useMemo, useRef } from \"react\"\n\n/**\n * Returns a `Promise<TaskOutcome<A>>` that is stable across renders with the\n * same `deps`. Intended for consumers of React 19's `use()` hook — providing\n * a new promise reference on each render would infinite-suspend.\n *\n * The `task` callback is read through a ref, so the latest closure is invoked\n * even if it isn't included in `deps`. Encode in `deps` whatever semantically\n * changes the task's result.\n */\nexport function useTaskPromise<A>(\n task: (signal: AbortSignal) => Promise<A> | A,\n deps: ReadonlyArray<unknown>,\n): Promise<TaskOutcome<A>> {\n const taskRef = useRef(task)\n taskRef.current = task\n\n return useMemo(() => {\n const tokenSource = createCancellationTokenSource()\n return Task<A>().Async<A>(\n () => taskRef.current(tokenSource.token.signal) as Promise<A>,\n undefined,\n undefined,\n tokenSource.token,\n )\n }, deps)\n}\n"],"mappings":"4HAcA,SAAgBA,EACd,EACA,EACyB,CACzB,IAAMC,EAAUC,EAAOC,CAAI,EAG3B,MAFA,GAAQ,QAAUA,EAEXC,MAAc,CACnB,IAAMC,EAAcC,EAA8B,EAClD,OAAOC,EAAQ,CAAC,CAAC,UACTN,EAAQ,QAAQI,EAAY,MAAM,MAAM,EAC9C,IAAA,GACA,IAAA,GACAA,EAAY,KACd,CACF,EAAGG,CAAI,CACT"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/async/useTaskValue.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Suspense-aware variant of `useTask` for React 19+. Suspends the component
|
|
4
|
+
* while the task is pending and throws on failure — both behaviors integrate
|
|
5
|
+
* with `<TaskBoundary>` (or a hand-rolled Suspense + ErrorBoundary pair).
|
|
6
|
+
*
|
|
7
|
+
* Invariants enforced by React 19:
|
|
8
|
+
* 1. The promise must be stable across renders. `useTaskPromise` memoizes by
|
|
9
|
+
* `deps`, so passing the same deps yields the same promise.
|
|
10
|
+
* 2. An ErrorBoundary must wrap the Suspense, never the reverse — otherwise
|
|
11
|
+
* Suspense will catch the thrown error instead of the boundary.
|
|
12
|
+
* 3. Do not call this on the server. Pass the underlying `Task` (or its
|
|
13
|
+
* promise) into a Client Component and call `useTaskValue` there.
|
|
14
|
+
*
|
|
15
|
+
* @interop React's `use()` reaches the nearest ErrorBoundary only through a throw, not an Either return.
|
|
16
|
+
*
|
|
17
|
+
* Testing note: React 19's `use()` does not unsuspend reliably under jsdom +
|
|
18
|
+
* @testing-library/react. End-to-end tests of `useTaskValue` + `<TaskBoundary>`
|
|
19
|
+
* require a real browser scheduler (Playwright); unit tests of `useTask` and
|
|
20
|
+
* `useTaskPromise` cover the Task plumbing.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useTaskValue<A>(task: (signal: AbortSignal) => Promise<A> | A, deps: ReadonlyArray<unknown>): A;
|
|
23
|
+
//#endregion
|
|
24
|
+
//# sourceMappingURL=useTaskValue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTaskValue.js","names":["useTaskValue","outcome","use","useTaskPromise","task","deps"],"sources":["../../src/async/useTaskValue.ts"],"sourcesContent":["\"use client\"\n\nimport { use } from \"react\"\n\nimport { useTaskPromise } from \"./useTaskPromise\"\n\n/**\n * Suspense-aware variant of `useTask` for React 19+. Suspends the component\n * while the task is pending and throws on failure — both behaviors integrate\n * with `<TaskBoundary>` (or a hand-rolled Suspense + ErrorBoundary pair).\n *\n * Invariants enforced by React 19:\n * 1. The promise must be stable across renders. `useTaskPromise` memoizes by\n * `deps`, so passing the same deps yields the same promise.\n * 2. An ErrorBoundary must wrap the Suspense, never the reverse — otherwise\n * Suspense will catch the thrown error instead of the boundary.\n * 3. Do not call this on the server. Pass the underlying `Task` (or its\n * promise) into a Client Component and call `useTaskValue` there.\n *\n * @interop React's `use()` reaches the nearest ErrorBoundary only through a throw, not an Either return.\n *\n * Testing note: React 19's `use()` does not unsuspend reliably under jsdom +\n * @testing-library/react. End-to-end tests of `useTaskValue` + `<TaskBoundary>`\n * require a real browser scheduler (Playwright); unit tests of `useTask` and\n * `useTaskPromise` cover the Task plumbing.\n */\nexport function useTaskValue<A>(task: (signal: AbortSignal) => Promise<A> | A, deps: ReadonlyArray<unknown>): A {\n const outcome = use(useTaskPromise(task, deps))\n if (outcome.isErr()) {\n throw outcome.error\n }\n return outcome.value as A\n}\n"],"mappings":"8FA0BA,SAAgBA,EAAgB,EAA+C,EAAiC,CAC9G,IAAMC,EAAUC,EAAIC,EAAeC,EAAMC,CAAI,CAAC,EAC9C,GAAIJ,EAAQ,MAAM,EAChB,MAAMA,EAAQ,MAEhB,OAAOA,EAAQ,KACjB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#region src/hooks/eq.d.ts
|
|
1
2
|
/**
|
|
2
3
|
* Equality comparators for use with `useStable*` hooks.
|
|
3
4
|
*
|
|
@@ -24,5 +25,6 @@ declare const tagEq: Eq<unknown>;
|
|
|
24
25
|
* behavior. Functions compare by reference.
|
|
25
26
|
*/
|
|
26
27
|
declare const structuralEq: Eq<unknown>;
|
|
28
|
+
//#endregion
|
|
27
29
|
export { tagEq as i, referenceEq as n, structuralEq as r, Eq as t };
|
|
28
|
-
//# sourceMappingURL=eq-
|
|
30
|
+
//# sourceMappingURL=eq-CK6oQqWG.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Either, List } from "functype";
|
|
2
|
+
//#region src/forms/Validated.d.ts
|
|
2
3
|
/**
|
|
3
4
|
* Applicative-error-accumulating result for form validation.
|
|
4
5
|
*
|
|
@@ -15,4 +16,5 @@ export type Validated<E, A> = Either<List<E>, A>;
|
|
|
15
16
|
export declare function valid<A>(value: A): Validated<never, A>;
|
|
16
17
|
/** Construct an `Invalid` (Left) result from an iterable of errors. */
|
|
17
18
|
export declare function invalid<E>(errors: List<E> | ReadonlyArray<E>): Validated<E, never>;
|
|
19
|
+
//#endregion
|
|
18
20
|
//# sourceMappingURL=Validated.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Validated.js","names":["valid","Right","value","invalid","list","errors","List","Left"],"sources":["../../src/forms/Validated.ts"],"sourcesContent":["import { type Either, Left, List, type List as ListT, Right } from \"functype\"\n\n/**\n * Applicative-error-accumulating result for form validation.\n *\n * Encoded as `Either<List<E>, A>` — the same shape Scala's cats uses for\n * `ValidatedNel`. Multiple field errors accumulate via `List.concat`; on\n * success, the validated value rides in the `Right` channel.\n *\n * functype core already exposes this pattern via `FormValidation<T>` in\n * `packages/functype/src/error/typed/Validation.ts`; this alias just gives\n * the React-facing surface an ergonomic name.\n */\nexport type Validated<E, A> = Either<ListT<E>, A>\n\n/** Construct a `Valid` (Right) result. */\nexport function valid<A>(value: A): Validated<never, A> {\n return Right<ListT<never>, A>(value)\n}\n\n/** Construct an `Invalid` (Left) result from an iterable of errors. */\nexport function invalid<E>(errors: ListT<E> | ReadonlyArray<E>): Validated<E, never> {\n const list = errors instanceof Array ? List<E>(errors) : (errors as ListT<E>)\n return Left<ListT<E>, never>(list)\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Validated.js","names":["valid","Right","value","invalid","list","errors","List","Left"],"sources":["../../src/forms/Validated.ts"],"sourcesContent":["import { type Either, Left, List, type List as ListT, Right } from \"functype\"\n\n/**\n * Applicative-error-accumulating result for form validation.\n *\n * Encoded as `Either<List<E>, A>` — the same shape Scala's cats uses for\n * `ValidatedNel`. Multiple field errors accumulate via `List.concat`; on\n * success, the validated value rides in the `Right` channel.\n *\n * functype core already exposes this pattern via `FormValidation<T>` in\n * `packages/functype/src/error/typed/Validation.ts`; this alias just gives\n * the React-facing surface an ergonomic name.\n */\nexport type Validated<E, A> = Either<ListT<E>, A>\n\n/** Construct a `Valid` (Right) result. */\nexport function valid<A>(value: A): Validated<never, A> {\n return Right<ListT<never>, A>(value)\n}\n\n/** Construct an `Invalid` (Left) result from an iterable of errors. */\nexport function invalid<E>(errors: ListT<E> | ReadonlyArray<E>): Validated<E, never> {\n const list = errors instanceof Array ? List<E>(errors) : (errors as ListT<E>)\n return Left<ListT<E>, never>(list)\n}\n"],"mappings":"qDAgBA,SAAgBA,EAAS,EAA+B,CACtD,OAAOC,EAAuBC,CAAK,CACrC,CAGA,SAAgBC,EAAW,EAA0D,CACnF,IAAMC,EAAOC,aAAkB,MAAQC,EAAQD,CAAM,EAAKA,EAC1D,OAAOE,EAAsBH,CAAI,CACnC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Validated } from "./Validated.js";
|
|
2
2
|
import { ChangeEvent } from "react";
|
|
3
3
|
import { List } from "functype";
|
|
4
|
+
//#region src/forms/useValidatedField.d.ts
|
|
4
5
|
/**
|
|
5
6
|
* Single-field state container with continuously-derived validation.
|
|
6
7
|
*
|
|
@@ -25,4 +26,5 @@ export declare function useValidatedField<A, E = string>(opts: {
|
|
|
25
26
|
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
|
|
26
27
|
};
|
|
27
28
|
};
|
|
29
|
+
//#endregion
|
|
28
30
|
//# sourceMappingURL=useValidatedField.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useValidatedField.js","names":["useValidatedField","value","setValue","useState","opts","validation","useMemo","es","List","useCallback"],"sources":["../../src/forms/useValidatedField.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype\"\nimport { type ChangeEvent, useCallback, useMemo, useState } from \"react\"\n\nimport type { Validated } from \"./Validated\"\n\n/**\n * Single-field state container with continuously-derived validation.\n *\n * `validation` is re-derived from `validate(value)` on every render — keep\n * `validate` cheap or memoize the callback.\n *\n * `bind()` returns props ready to spread onto a native `<input>`. The\n * generic `A` may be any value type; `bind` is most useful when `A` is\n * string-shaped. For non-string fields, wire `value`/`setValue` directly.\n */\nexport function useValidatedField<A, E = string>(opts: {\n readonly initial: A\n readonly validate: (a: A) => Validated<E, A>\n}): {\n readonly value: A\n setValue: (a: A) => void\n readonly validation: Validated<E, A>\n readonly errors: ListT<E>\n readonly isValid: boolean\n bind: () => { value: A; onChange: (e: ChangeEvent<HTMLInputElement>) => void }\n} {\n const [value, setValue] = useState<A>(opts.initial)\n\n const validation = useMemo(() => opts.validate(value), [opts, value])\n const errors = useMemo(\n () =>\n validation.fold(\n (es) => es,\n () => List.empty<E>(),\n ),\n [validation],\n )\n const isValid = validation.isRight()\n\n const bind = useCallback(\n () => ({\n value,\n onChange: (e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value as unknown as A),\n }),\n [value],\n )\n\n return { value, setValue, validation, errors, isValid, bind }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useValidatedField.js","names":["useValidatedField","value","setValue","useState","opts","validation","useMemo","es","List","useCallback"],"sources":["../../src/forms/useValidatedField.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype\"\nimport { type ChangeEvent, useCallback, useMemo, useState } from \"react\"\n\nimport type { Validated } from \"./Validated\"\n\n/**\n * Single-field state container with continuously-derived validation.\n *\n * `validation` is re-derived from `validate(value)` on every render — keep\n * `validate` cheap or memoize the callback.\n *\n * `bind()` returns props ready to spread onto a native `<input>`. The\n * generic `A` may be any value type; `bind` is most useful when `A` is\n * string-shaped. For non-string fields, wire `value`/`setValue` directly.\n */\nexport function useValidatedField<A, E = string>(opts: {\n readonly initial: A\n readonly validate: (a: A) => Validated<E, A>\n}): {\n readonly value: A\n setValue: (a: A) => void\n readonly validation: Validated<E, A>\n readonly errors: ListT<E>\n readonly isValid: boolean\n bind: () => { value: A; onChange: (e: ChangeEvent<HTMLInputElement>) => void }\n} {\n const [value, setValue] = useState<A>(opts.initial)\n\n const validation = useMemo(() => opts.validate(value), [opts, value])\n const errors = useMemo(\n () =>\n validation.fold(\n (es) => es,\n () => List.empty<E>(),\n ),\n [validation],\n )\n const isValid = validation.isRight()\n\n const bind = useCallback(\n () => ({\n value,\n onChange: (e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value as unknown as A),\n }),\n [value],\n )\n\n return { value, setValue, validation, errors, isValid, bind }\n}\n"],"mappings":"4GAiBA,SAAgBA,EAAiC,EAU/C,CACA,GAAM,CAACC,EAAOC,GAAYC,EAAYC,EAAK,OAAO,EAE5CC,EAAaC,MAAcF,EAAK,SAASH,CAAK,EAAG,CAACG,EAAMH,CAAK,CAAC,EAmBpE,MAAO,CAAE,QAAO,WAAU,aAAY,OAlBvBK,MAEXD,EAAW,KACR,GAAOE,MACFC,EAAK,MAAS,CACtB,EACF,CAACH,CAAU,CAY8B,EAAG,QAV9BA,EAAW,QAUyB,EAAG,KAR1CI,OACJ,CACL,QACA,SAAW,GAAqCP,EAAS,EAAE,OAAO,KAAqB,CACzF,GACA,CAACD,CAAK,CAGkD,CAAE,CAC9D"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Validated } from "./Validated.js";
|
|
2
2
|
import { FormEvent } from "react";
|
|
3
3
|
import { List } from "functype";
|
|
4
|
+
//#region src/forms/useValidatedForm.d.ts
|
|
4
5
|
/**
|
|
5
6
|
* Form-level state container with applicative error accumulation.
|
|
6
7
|
*
|
|
@@ -31,4 +32,5 @@ export declare function useValidatedForm<S extends Record<string, unknown>, E =
|
|
|
31
32
|
reset: () => void;
|
|
32
33
|
handleSubmit: (onValid: (s: S) => void | Promise<void>) => (e: FormEvent) => void;
|
|
33
34
|
};
|
|
35
|
+
//#endregion
|
|
34
36
|
//# sourceMappingURL=useValidatedForm.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useValidatedForm.js","names":["useValidatedForm","values","setValues","useState","opts","setField","useCallback","prev","key","value","reset","validation","useMemo","es","List","e","onValid","s"],"sources":["../../src/forms/useValidatedForm.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype\"\nimport { type FormEvent, useCallback, useMemo, useState } from \"react\"\n\nimport type { Validated } from \"./Validated\"\n\n/**\n * Form-level state container with applicative error accumulation.\n *\n * The consumer-provided `validate` is the canonical place to accumulate\n * field-level errors. A common pattern:\n *\n * ```ts\n * const validate = (s: Form): Validated<string, Form> => {\n * const errs = List<string>([])\n * .concat(s.email.includes(\"@\") ? List([]) : List([\"email must contain @\"]))\n * .concat(s.age >= 18 ? List([]) : List([\"age must be 18+\"]))\n * return errs.isEmpty ? valid(s) : invalid(errs)\n * }\n * ```\n *\n * `handleSubmit(onValid)` returns an event handler that calls `e.preventDefault()`\n * and only invokes `onValid` when the current form value passes validation.\n */\nexport function useValidatedForm<S extends Record<string, unknown>, E = string>(opts: {\n readonly initial: S\n readonly validate: (s: S) => Validated<E, S>\n}): {\n readonly values: S\n setField: <K extends keyof S>(key: K, value: S[K]) => void\n readonly validation: Validated<E, S>\n readonly errors: ListT<E>\n readonly isValid: boolean\n reset: () => void\n handleSubmit: (onValid: (s: S) => void | Promise<void>) => (e: FormEvent) => void\n} {\n const [values, setValues] = useState<S>(opts.initial)\n\n const setField = useCallback(<K extends keyof S>(key: K, value: S[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n }, [])\n\n const reset = useCallback(() => setValues(opts.initial), [opts.initial])\n\n const validation = useMemo(() => opts.validate(values), [opts, values])\n const errors = useMemo(\n () =>\n validation.fold(\n (es) => es,\n () => List.empty<E>(),\n ),\n [validation],\n )\n const isValid = validation.isRight()\n\n const handleSubmit = useCallback(\n (onValid: (s: S) => void | Promise<void>) => (e: FormEvent) => {\n e.preventDefault()\n validation.fold(\n () => undefined,\n (s) => {\n void onValid(s)\n },\n )\n },\n [validation],\n )\n\n return { values, setField, validation, errors, isValid, reset, handleSubmit }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useValidatedForm.js","names":["useValidatedForm","values","setValues","useState","opts","setField","useCallback","prev","key","value","reset","validation","useMemo","es","List","e","onValid","s"],"sources":["../../src/forms/useValidatedForm.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype\"\nimport { type FormEvent, useCallback, useMemo, useState } from \"react\"\n\nimport type { Validated } from \"./Validated\"\n\n/**\n * Form-level state container with applicative error accumulation.\n *\n * The consumer-provided `validate` is the canonical place to accumulate\n * field-level errors. A common pattern:\n *\n * ```ts\n * const validate = (s: Form): Validated<string, Form> => {\n * const errs = List<string>([])\n * .concat(s.email.includes(\"@\") ? List([]) : List([\"email must contain @\"]))\n * .concat(s.age >= 18 ? List([]) : List([\"age must be 18+\"]))\n * return errs.isEmpty ? valid(s) : invalid(errs)\n * }\n * ```\n *\n * `handleSubmit(onValid)` returns an event handler that calls `e.preventDefault()`\n * and only invokes `onValid` when the current form value passes validation.\n */\nexport function useValidatedForm<S extends Record<string, unknown>, E = string>(opts: {\n readonly initial: S\n readonly validate: (s: S) => Validated<E, S>\n}): {\n readonly values: S\n setField: <K extends keyof S>(key: K, value: S[K]) => void\n readonly validation: Validated<E, S>\n readonly errors: ListT<E>\n readonly isValid: boolean\n reset: () => void\n handleSubmit: (onValid: (s: S) => void | Promise<void>) => (e: FormEvent) => void\n} {\n const [values, setValues] = useState<S>(opts.initial)\n\n const setField = useCallback(<K extends keyof S>(key: K, value: S[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n }, [])\n\n const reset = useCallback(() => setValues(opts.initial), [opts.initial])\n\n const validation = useMemo(() => opts.validate(values), [opts, values])\n const errors = useMemo(\n () =>\n validation.fold(\n (es) => es,\n () => List.empty<E>(),\n ),\n [validation],\n )\n const isValid = validation.isRight()\n\n const handleSubmit = useCallback(\n (onValid: (s: S) => void | Promise<void>) => (e: FormEvent) => {\n e.preventDefault()\n validation.fold(\n () => undefined,\n (s) => {\n void onValid(s)\n },\n )\n },\n [validation],\n )\n\n return { values, setField, validation, errors, isValid, reset, handleSubmit }\n}\n"],"mappings":"4GAyBA,SAAgBA,EAAgE,EAW9E,CACA,GAAM,CAACC,EAAQC,GAAaC,EAAYC,EAAK,OAAO,EAE9CC,EAAWC,GAAgC,EAAQ,IAAgB,CACvEJ,EAAW,IAAU,CAAE,GAAGK,GAAOC,GAAMC,CAAM,EAAE,CACjD,EAAG,CAAC,CAAC,EAECC,EAAQJ,MAAkBJ,EAAUE,EAAK,OAAO,EAAG,CAACA,EAAK,OAAO,CAAC,EAEjEO,EAAaC,MAAcR,EAAK,SAASH,CAAM,EAAG,CAACG,EAAMH,CAAM,CAAC,EAwBtE,MAAO,CAAE,SAAQ,WAAU,aAAY,OAvBxBW,MAEXD,EAAW,KACR,GAAOE,MACFC,EAAK,MAAS,CACtB,EACF,CAACH,CAAU,CAiB+B,EAAG,QAf/BA,EAAW,QAe0B,EAAG,QAAO,aAb1CL,EAClB,GAA6C,GAAiB,CAC7DS,EAAE,eAAe,EACjBJ,EAAW,SACH,IAAA,GACL,GAAM,CACLK,EAAaC,CAAC,CAChB,CACF,CACF,EACA,CAACN,CAAU,CAG6D,CAAE,CAC9E"}
|
package/dist/hooks/eq.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as tagEq, n as referenceEq, r as structuralEq, t as Eq } from "../eq-
|
|
1
|
+
import { i as tagEq, n as referenceEq, r as structuralEq, t as Eq } from "../eq-CK6oQqWG.js";
|
|
2
2
|
export { Eq, referenceEq, structuralEq, tagEq };
|
package/dist/hooks/eq.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eq.js","names":["referenceEq","tagEq","a","b","ta","tb","structuralEq","item","i","ka","kb","k"],"sources":["../../src/hooks/eq.ts"],"sourcesContent":["/**\n * Equality comparators for use with `useStable*` hooks.\n *\n * functype core doesn't ship an Eq typeclass; instead, comparators are passed\n * explicitly. The default everywhere is `referenceEq` (Object.is), matching\n * React's built-in dependency comparison.\n */\n\nexport type Eq<A> = (a: A, b: A) => boolean\n\n/**\n * Reference equality, identical to React's default `Object.is` for hook deps.\n */\nexport const referenceEq: Eq<unknown> = Object.is\n\n/**\n * Compares two functype ADTs by their `_tag` literal only.\n *\n * Useful when you only care about variant changes (e.g., re-render when an\n * `Option` flips between Some and None, but not on payload changes). Returns\n * false for non-tagged values.\n */\nexport const tagEq: Eq<unknown> = (a, b) => {\n if (Object.is(a, b)) return true\n if (typeof a !== \"object\" || a === null) return false\n if (typeof b !== \"object\" || b === null) return false\n const ta = (a as { _tag?: unknown })._tag\n const tb = (b as { _tag?: unknown })._tag\n return ta !== undefined && ta === tb\n}\n\n/**\n * Recursive structural equality. Handles primitives, arrays, plain objects, and\n * tagged ADTs. Cycles are not detected — passing cyclic structures is undefined\n * behavior. Functions compare by reference.\n */\nexport const structuralEq: Eq<unknown> = (a, b) => {\n if (Object.is(a, b)) return true\n if (typeof a !== typeof b) return false\n if (a === null || b === null) return false\n if (typeof a !== \"object\") return false\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false\n return a.every((item, i) => structuralEq(item, b[i]))\n }\n if (Array.isArray(b)) return false\n\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n if (ka.length !== kb.length) return false\n return ka.every(\n (k) =>\n Object.prototype.hasOwnProperty.call(b, k) &&\n structuralEq((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n}\n"],"mappings":"AAaA,MAAaA,EAA2B,OAAO,GASlCC,GAAsB,EAAG,IAAM,CAC1C,GAAI,OAAO,GAAGC,EAAGC,CAAC,EAAG,MAAO,GAE5B,GADI,OAAOD,GAAM,WAAYA,GACzB,OAAOC,GAAM,WAAYA,EAAY,MAAO,GAChD,IAAMC,EAAMF,EAAyB,KAC/BG,EAAMF,EAAyB,KACrC,OAAOC,IAAO,IAAA,IAAaA,IAAOC,CACpC,EAOaC,GAA6B,EAAG,IAAM,CACjD,GAAI,OAAO,GAAGJ,EAAGC,CAAC,EAAG,MAAO,GAG5B,GAFI,OAAOD,GAAM,OAAOC,GACpBD,IAAM,MAAQC,IAAM,MACpB,OAAOD,GAAM,SAAU,MAAO,GAElC,GAAI,MAAM,QAAQA,CAAC,EAEjB,MADI,CAAC,MAAM,QAAQC,CAAC,GAAKD,EAAE,SAAWC,EAAE,OAAe,GAChDD,EAAE,OAAO,EAAM,IAAMI,EAAaC,EAAMJ,EAAEK,EAAE,CAAC,EAEtD,GAAI,MAAM,QAAQL,CAAC,EAAG,MAAO,GAE7B,IAAMM,EAAK,OAAO,KAAKP,CAAW,EAC5BQ,EAAK,OAAO,KAAKP,CAAW,EAElC,OADIM,EAAG,SAAWC,EAAG,QACdD,EAAG,MACP,GACC,OAAO,UAAU,eAAe,KAAKN,EAAGQ,CAAC,GACzCL,EAAcJ,EAA8BS,GAAKR,EAA8BQ,EAAE,CACrF,CACF
|
|
1
|
+
{"version":3,"file":"eq.js","names":["referenceEq","tagEq","a","b","ta","tb","structuralEq","item","i","ka","kb","k"],"sources":["../../src/hooks/eq.ts"],"sourcesContent":["/**\n * Equality comparators for use with `useStable*` hooks.\n *\n * functype core doesn't ship an Eq typeclass; instead, comparators are passed\n * explicitly. The default everywhere is `referenceEq` (Object.is), matching\n * React's built-in dependency comparison.\n */\n\nexport type Eq<A> = (a: A, b: A) => boolean\n\n/**\n * Reference equality, identical to React's default `Object.is` for hook deps.\n */\nexport const referenceEq: Eq<unknown> = Object.is\n\n/**\n * Compares two functype ADTs by their `_tag` literal only.\n *\n * Useful when you only care about variant changes (e.g., re-render when an\n * `Option` flips between Some and None, but not on payload changes). Returns\n * false for non-tagged values.\n */\nexport const tagEq: Eq<unknown> = (a, b) => {\n if (Object.is(a, b)) return true\n if (typeof a !== \"object\" || a === null) return false\n if (typeof b !== \"object\" || b === null) return false\n const ta = (a as { _tag?: unknown })._tag\n const tb = (b as { _tag?: unknown })._tag\n return ta !== undefined && ta === tb\n}\n\n/**\n * Recursive structural equality. Handles primitives, arrays, plain objects, and\n * tagged ADTs. Cycles are not detected — passing cyclic structures is undefined\n * behavior. Functions compare by reference.\n */\nexport const structuralEq: Eq<unknown> = (a, b) => {\n if (Object.is(a, b)) return true\n if (typeof a !== typeof b) return false\n if (a === null || b === null) return false\n if (typeof a !== \"object\") return false\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false\n return a.every((item, i) => structuralEq(item, b[i]))\n }\n if (Array.isArray(b)) return false\n\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n if (ka.length !== kb.length) return false\n return ka.every(\n (k) =>\n Object.prototype.hasOwnProperty.call(b, k) &&\n structuralEq((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n}\n"],"mappings":"AAaA,MAAaA,EAA2B,OAAO,GASlCC,GAAsB,EAAG,IAAM,CAC1C,GAAI,OAAO,GAAGC,EAAGC,CAAC,EAAG,MAAO,GAE5B,GADI,OAAOD,GAAM,WAAYA,GACzB,OAAOC,GAAM,WAAYA,EAAY,MAAO,GAChD,IAAMC,EAAMF,EAAyB,KAC/BG,EAAMF,EAAyB,KACrC,OAAOC,IAAO,IAAA,IAAaA,IAAOC,CACpC,EAOaC,GAA6B,EAAG,IAAM,CACjD,GAAI,OAAO,GAAGJ,EAAGC,CAAC,EAAG,MAAO,GAG5B,GAFI,OAAOD,GAAM,OAAOC,GACpBD,IAAM,MAAQC,IAAM,MACpB,OAAOD,GAAM,SAAU,MAAO,GAElC,GAAI,MAAM,QAAQA,CAAC,EAEjB,MADI,CAAC,MAAM,QAAQC,CAAC,GAAKD,EAAE,SAAWC,EAAE,OAAe,GAChDD,EAAE,OAAO,EAAM,IAAMI,EAAaC,EAAMJ,EAAEK,EAAE,CAAC,EAEtD,GAAI,MAAM,QAAQL,CAAC,EAAG,MAAO,GAE7B,IAAMM,EAAK,OAAO,KAAKP,CAAW,EAC5BQ,EAAK,OAAO,KAAKP,CAAW,EAElC,OADIM,EAAG,SAAWC,EAAG,QACdD,EAAG,MACP,GACC,OAAO,UAAU,eAAe,KAAKN,EAAGQ,CAAC,GACzCL,EAAcJ,EAA8BS,GAAKR,EAA8BQ,EAAE,CACrF,CACF"}
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { i as tagEq, n as referenceEq, r as structuralEq, t as Eq } from "../eq-
|
|
2
|
-
import { t as useEither } from "../useEither-
|
|
3
|
-
import { t as useList } from "../useList-
|
|
4
|
-
import { t as useOption } from "../useOption-
|
|
5
|
-
import { t as useStableCallback } from "../useStableCallback-
|
|
6
|
-
import { t as useStableEffect } from "../useStableEffect-
|
|
7
|
-
import { t as useStableMemo } from "../useStableMemo-
|
|
8
|
-
import { t as useStableState } from "../useStableState-
|
|
9
|
-
import { t as useTry } from "../useTry-
|
|
1
|
+
import { i as tagEq, n as referenceEq, r as structuralEq, t as Eq } from "../eq-CK6oQqWG.js";
|
|
2
|
+
import { t as useEither } from "../useEither-DyPW7OaA.js";
|
|
3
|
+
import { t as useList } from "../useList-B5Iox1xv.js";
|
|
4
|
+
import { t as useOption } from "../useOption-CXXNC1_S.js";
|
|
5
|
+
import { t as useStableCallback } from "../useStableCallback-CXQQOhl6.js";
|
|
6
|
+
import { t as useStableEffect } from "../useStableEffect-C-5NCd1T.js";
|
|
7
|
+
import { t as useStableMemo } from "../useStableMemo-PYyLBWwd.js";
|
|
8
|
+
import { t as useStableState } from "../useStableState-fi6nURHS.js";
|
|
9
|
+
import { t as useTry } from "../useTry-B0HIcFFb.js";
|
|
10
10
|
export { type Eq, referenceEq, structuralEq, tagEq, useEither, useList, useOption, useStableCallback, useStableEffect, useStableMemo, useStableState, useTry };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useEither } from "../useEither-
|
|
1
|
+
import { t as useEither } from "../useEither-DyPW7OaA.js";
|
|
2
2
|
export { useEither };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useEither.js","names":["useEither","value","setValue","useState","initial","Left","setRight","useCallback","Right","a","setLeft","e","fold","onLeft","onRight","useMemo"],"sources":["../../src/hooks/useEither.ts"],"sourcesContent":["\"use client\"\n\nimport { type Either, Left, Right } from \"functype/either\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful Either container. Defaults to Left(undefined) when no initial.\n */\nexport function useEither<E, A>(\n initial?: Either<E, A>,\n): {\n readonly value: Either<E, A>\n setRight: (a: A) => void\n setLeft: (e: E) => void\n fold: <R>(onLeft: (e: E) => R, onRight: (a: A) => R) => R\n} {\n const [value, setValue] = useState<Either<E, A>>(() => initial ?? Left<E, A>(undefined as unknown as E))\n\n const setRight = useCallback((a: A) => setValue(Right<E, A>(a)), [])\n const setLeft = useCallback((e: E) => setValue(Left<E, A>(e)), [])\n\n const fold = useCallback(<R>(onLeft: (e: E) => R, onRight: (a: A) => R) => value.fold(onLeft, onRight), [value])\n\n return useMemo(() => ({ value, setRight, setLeft, fold }), [value, setRight, setLeft, fold])\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useEither.js","names":["useEither","value","setValue","useState","initial","Left","setRight","useCallback","Right","a","setLeft","e","fold","onLeft","onRight","useMemo"],"sources":["../../src/hooks/useEither.ts"],"sourcesContent":["\"use client\"\n\nimport { type Either, Left, Right } from \"functype/either\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful Either container. Defaults to Left(undefined) when no initial.\n */\nexport function useEither<E, A>(\n initial?: Either<E, A>,\n): {\n readonly value: Either<E, A>\n setRight: (a: A) => void\n setLeft: (e: E) => void\n fold: <R>(onLeft: (e: E) => R, onRight: (a: A) => R) => R\n} {\n const [value, setValue] = useState<Either<E, A>>(() => initial ?? Left<E, A>(undefined as unknown as E))\n\n const setRight = useCallback((a: A) => setValue(Right<E, A>(a)), [])\n const setLeft = useCallback((e: E) => setValue(Left<E, A>(e)), [])\n\n const fold = useCallback(<R>(onLeft: (e: E) => R, onRight: (a: A) => R) => value.fold(onLeft, onRight), [value])\n\n return useMemo(() => ({ value, setRight, setLeft, fold }), [value, setRight, setLeft, fold])\n}\n"],"mappings":"8HAQA,SAAgBA,EACd,EAMA,CACA,GAAM,CAACC,EAAOC,GAAYC,MAA6BC,GAAWC,EAAW,IAAA,EAAyB,CAAC,EAEjGC,EAAWC,EAAa,GAASL,EAASM,EAAYC,CAAC,CAAC,EAAG,CAAC,CAAC,EAC7DC,EAAUH,EAAa,GAASL,EAASG,EAAWM,CAAC,CAAC,EAAG,CAAC,CAAC,EAE3DC,EAAOL,GAAgB,EAAqB,IAAyBN,EAAM,KAAKY,EAAQC,CAAO,EAAG,CAACb,CAAK,CAAC,EAE/G,OAAOc,OAAe,CAAE,QAAO,WAAU,UAAS,MAAK,GAAI,CAACd,EAAOK,EAAUI,EAASE,CAAI,CAAC,CAC7F"}
|
package/dist/hooks/useList.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useList } from "../useList-
|
|
1
|
+
import { t as useList } from "../useList-B5Iox1xv.js";
|
|
2
2
|
export { useList };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useList.js","names":["useList","value","setValue","useState","List","initial","add","useCallback","prev","a","remove","removeAt","index","clear","map","f","filter","p","useMemo"],"sources":["../../src/hooks/useList.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype/list\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful immutable List container. All mutators return new state.\n */\nexport function useList<A>(initial?: readonly A[]): {\n readonly value: ListT<A>\n add: (a: A) => void\n remove: (a: A) => void\n removeAt: (index: number) => void\n clear: () => void\n map: <B>(f: (a: A) => B) => ListT<B>\n filter: (p: (a: A) => boolean) => ListT<A>\n} {\n const [value, setValue] = useState<ListT<A>>(() => List<A>(initial ?? []))\n\n const add = useCallback((a: A) => setValue((prev) => prev.add(a) as ListT<A>), [])\n const remove = useCallback((a: A) => setValue((prev) => prev.remove(a)), [])\n const removeAt = useCallback((index: number) => setValue((prev) => prev.removeAt(index)), [])\n const clear = useCallback(() => setValue(List.empty<A>()), [])\n\n const map = useCallback(<B>(f: (a: A) => B) => value.map(f), [value])\n const filter = useCallback((p: (a: A) => boolean) => value.filter(p), [value])\n\n return useMemo(\n () => ({ value, add, remove, removeAt, clear, map, filter }),\n [value, add, remove, removeAt, clear, map, filter],\n )\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useList.js","names":["useList","value","setValue","useState","List","initial","add","useCallback","prev","a","remove","removeAt","index","clear","map","f","filter","p","useMemo"],"sources":["../../src/hooks/useList.ts"],"sourcesContent":["\"use client\"\n\nimport { List, type List as ListT } from \"functype/list\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful immutable List container. All mutators return new state.\n */\nexport function useList<A>(initial?: readonly A[]): {\n readonly value: ListT<A>\n add: (a: A) => void\n remove: (a: A) => void\n removeAt: (index: number) => void\n clear: () => void\n map: <B>(f: (a: A) => B) => ListT<B>\n filter: (p: (a: A) => boolean) => ListT<A>\n} {\n const [value, setValue] = useState<ListT<A>>(() => List<A>(initial ?? []))\n\n const add = useCallback((a: A) => setValue((prev) => prev.add(a) as ListT<A>), [])\n const remove = useCallback((a: A) => setValue((prev) => prev.remove(a)), [])\n const removeAt = useCallback((index: number) => setValue((prev) => prev.removeAt(index)), [])\n const clear = useCallback(() => setValue(List.empty<A>()), [])\n\n const map = useCallback(<B>(f: (a: A) => B) => value.map(f), [value])\n const filter = useCallback((p: (a: A) => boolean) => value.filter(p), [value])\n\n return useMemo(\n () => ({ value, add, remove, removeAt, clear, map, filter }),\n [value, add, remove, removeAt, clear, map, filter],\n )\n}\n"],"mappings":"iHAQA,SAAgBA,EAAW,EAQzB,CACA,GAAM,CAACC,EAAOC,GAAYC,MAAyBC,EAAQC,GAAW,CAAC,CAAC,CAAC,EAEnEC,EAAMC,EAAa,GAASL,EAAU,GAASM,EAAK,IAAIC,CAAC,CAAa,EAAG,CAAC,CAAC,EAC3EC,EAASH,EAAa,GAASL,EAAU,GAASM,EAAK,OAAOC,CAAC,CAAC,EAAG,CAAC,CAAC,EACrEE,EAAWJ,EAAa,GAAkBL,EAAU,GAASM,EAAK,SAASI,CAAK,CAAC,EAAG,CAAC,CAAC,EACtFC,EAAQN,MAAkBL,EAASE,EAAK,MAAS,CAAC,EAAG,CAAC,CAAC,EAEvDU,EAAMP,EAAgB,GAAmBN,EAAM,IAAIc,CAAC,EAAG,CAACd,CAAK,CAAC,EAC9De,EAAST,EAAa,GAAyBN,EAAM,OAAOgB,CAAC,EAAG,CAAChB,CAAK,CAAC,EAE7E,OAAOiB,OACE,CAAE,QAAO,MAAK,SAAQ,WAAU,QAAO,MAAK,QAAO,GAC1D,CAACjB,EAAOK,EAAKI,EAAQC,EAAUE,EAAOC,EAAKE,CAAM,CACnD,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useOption } from "../useOption-
|
|
1
|
+
import { t as useOption } from "../useOption-CXXNC1_S.js";
|
|
2
2
|
export { useOption };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOption.js","names":["useOption","value","setValue","useState","Option","initial","set","useCallback","a","clear","map","f","fold","onNone","onSome","useMemo"],"sources":["../../src/hooks/useOption.ts"],"sourcesContent":["\"use client\"\n\nimport { Option, type Option as OptionT } from \"functype/option\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful Option container. `set(null | undefined)` clears to None.\n *\n * @interop This hook converts nullable JS values into Option, so `initial` and `set` must accept them.\n */\nexport function useOption<A>(initial?: A): {\n readonly value: OptionT<A>\n set: (a: A | null | undefined) => void\n clear: () => void\n map: <B>(f: (a: A) => B) => OptionT<B>\n fold: <R>(onNone: () => R, onSome: (a: A) => R) => R\n} {\n const [value, setValue] = useState<OptionT<A>>(() => Option<A>(initial))\n\n const set = useCallback((a: A | null | undefined) => setValue(Option<A>(a)), [])\n const clear = useCallback(() => setValue(Option.none<A>()), [])\n\n const map = useCallback(<B>(f: (a: A) => B) => value.map(f), [value])\n const fold = useCallback(<R>(onNone: () => R, onSome: (a: A) => R) => value.fold(onNone, onSome), [value])\n\n return useMemo(() => ({ value, set, clear, map, fold }), [value, set, clear, map, fold])\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useOption.js","names":["useOption","value","setValue","useState","Option","initial","set","useCallback","a","clear","map","f","fold","onNone","onSome","useMemo"],"sources":["../../src/hooks/useOption.ts"],"sourcesContent":["\"use client\"\n\nimport { Option, type Option as OptionT } from \"functype/option\"\nimport { useCallback, useMemo, useState } from \"react\"\n\n/**\n * Stateful Option container. `set(null | undefined)` clears to None.\n *\n * @interop This hook converts nullable JS values into Option, so `initial` and `set` must accept them.\n */\nexport function useOption<A>(initial?: A): {\n readonly value: OptionT<A>\n set: (a: A | null | undefined) => void\n clear: () => void\n map: <B>(f: (a: A) => B) => OptionT<B>\n fold: <R>(onNone: () => R, onSome: (a: A) => R) => R\n} {\n const [value, setValue] = useState<OptionT<A>>(() => Option<A>(initial))\n\n const set = useCallback((a: A | null | undefined) => setValue(Option<A>(a)), [])\n const clear = useCallback(() => setValue(Option.none<A>()), [])\n\n const map = useCallback(<B>(f: (a: A) => B) => value.map(f), [value])\n const fold = useCallback(<R>(onNone: () => R, onSome: (a: A) => R) => value.fold(onNone, onSome), [value])\n\n return useMemo(() => ({ value, set, clear, map, fold }), [value, set, clear, map, fold])\n}\n"],"mappings":"qHAUA,SAAgBA,EAAa,EAM3B,CACA,GAAM,CAACC,EAAOC,GAAYC,MAA2BC,EAAUC,CAAO,CAAC,EAEjEC,EAAMC,EAAa,GAA4BL,EAASE,EAAUI,CAAC,CAAC,EAAG,CAAC,CAAC,EACzEC,EAAQF,MAAkBL,EAASE,EAAO,KAAQ,CAAC,EAAG,CAAC,CAAC,EAExDM,EAAMH,EAAgB,GAAmBN,EAAM,IAAIU,CAAC,EAAG,CAACV,CAAK,CAAC,EAC9DW,EAAOL,GAAgB,EAAiB,IAAwBN,EAAM,KAAKY,EAAQC,CAAM,EAAG,CAACb,CAAK,CAAC,EAEzG,OAAOc,OAAe,CAAE,QAAO,MAAK,QAAO,MAAK,MAAK,GAAI,CAACd,EAAOK,EAAKG,EAAOC,EAAKE,CAAI,CAAC,CACzF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useStableCallback } from "../useStableCallback-
|
|
1
|
+
import { t as useStableCallback } from "../useStableCallback-CXQQOhl6.js";
|
|
2
2
|
export { useStableCallback };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useStableCallback.js","names":["useStableCallback","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useCallback","callback"],"sources":["../../src/hooks/useStableCallback.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, useCallback, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useCallback`, but only returns a new function when *some* dep has\n * changed under the supplied (or default) comparator.\n */\nexport function useStableCallback<F extends (...args: never[]) => unknown>(\n callback: F,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): F {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n return useCallback(callback, [tick.current]) as F\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useStableCallback.js","names":["useStableCallback","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useCallback","callback"],"sources":["../../src/hooks/useStableCallback.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, useCallback, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useCallback`, but only returns a new function when *some* dep has\n * changed under the supplied (or default) comparator.\n */\nexport function useStableCallback<F extends (...args: never[]) => unknown>(\n callback: F,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): F {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n return useCallback(callback, [tick.current]) as F\n}\n"],"mappings":"mGAUA,SAAgBA,EACd,EACA,EAEA,EACG,CACH,IAAMC,EAAOC,EAA8B,IAAI,EACzCC,EAAOD,EAAO,CAAC,EAErB,GAAID,EAAK,UAAY,KACnB,EAAK,QAAUG,EACf,EAAK,SAAW,MACX,CACL,IAAMC,EAAQJ,EAAK,QACHG,EAAK,MAAM,EAAG,IAErB,EADKE,IAAMC,IAAMC,EAAA,CACZH,EAAME,GAAIE,CAAC,CAEf,IACR,EAAK,QAAUL,EACf,EAAK,SAAW,EAEpB,CAEA,OAAOM,EAAYC,EAAU,CAACR,EAAK,OAAO,CAAC,CAC7C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useStableEffect } from "../useStableEffect-
|
|
1
|
+
import { t as useStableEffect } from "../useStableEffect-C-5NCd1T.js";
|
|
2
2
|
export { useStableEffect };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useStableEffect.js","names":["useStableEffect","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useEffect","effect"],"sources":["../../src/hooks/useStableEffect.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, type EffectCallback, useEffect, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useEffect`, but re-runs only when *some* dep has changed under the\n * supplied (or default) comparator. The `eqs` array is aligned positionally\n * with `deps`; missing entries fall back to `referenceEq`.\n *\n * Useful when deps include functype ADTs (`Option`, `Either`, etc.) whose\n * structural identity is what matters, but whose references churn every render.\n */\nexport function useStableEffect(\n effect: EffectCallback,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): void {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n useEffect(effect, [tick.current])\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useStableEffect.js","names":["useStableEffect","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useEffect","effect"],"sources":["../../src/hooks/useStableEffect.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, type EffectCallback, useEffect, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useEffect`, but re-runs only when *some* dep has changed under the\n * supplied (or default) comparator. The `eqs` array is aligned positionally\n * with `deps`; missing entries fall back to `referenceEq`.\n *\n * Useful when deps include functype ADTs (`Option`, `Either`, etc.) whose\n * structural identity is what matters, but whose references churn every render.\n */\nexport function useStableEffect(\n effect: EffectCallback,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): void {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n useEffect(effect, [tick.current])\n}\n"],"mappings":"iGAcA,SAAgBA,EACd,EACA,EAEA,EACM,CACN,IAAMC,EAAOC,EAA8B,IAAI,EACzCC,EAAOD,EAAO,CAAC,EAErB,GAAID,EAAK,UAAY,KACnB,EAAK,QAAUG,EACf,EAAK,SAAW,MACX,CACL,IAAMC,EAAQJ,EAAK,QACHG,EAAK,MAAM,EAAG,IAErB,EADKE,IAAMC,IAAMC,EAAA,CACZH,EAAME,GAAIE,CAAC,CAEf,IACR,EAAK,QAAUL,EACf,EAAK,SAAW,EAEpB,CAEAM,EAAUC,EAAQ,CAACR,EAAK,OAAO,CAAC,CAClC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useStableMemo } from "../useStableMemo-
|
|
1
|
+
import { t as useStableMemo } from "../useStableMemo-PYyLBWwd.js";
|
|
2
2
|
export { useStableMemo };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useStableMemo.js","names":["useStableMemo","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useMemo","factory"],"sources":["../../src/hooks/useStableMemo.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, useMemo, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useMemo`, but recomputes only when *some* dep has changed under the\n * supplied (or default) comparator. The `eqs` array is aligned positionally\n * with `deps`; missing entries fall back to `referenceEq`.\n */\nexport function useStableMemo<A>(\n factory: () => A,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): A {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n return useMemo(factory, [tick.current])\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useStableMemo.js","names":["useStableMemo","prev","useRef","tick","deps","stale","eqs","i","referenceEq","d","useMemo","factory"],"sources":["../../src/hooks/useStableMemo.ts"],"sourcesContent":["\"use client\"\n\nimport { type DependencyList, useMemo, useRef } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Like `useMemo`, but recomputes only when *some* dep has changed under the\n * supplied (or default) comparator. The `eqs` array is aligned positionally\n * with `deps`; missing entries fall back to `referenceEq`.\n */\nexport function useStableMemo<A>(\n factory: () => A,\n deps: DependencyList,\n // eslint-disable-next-line functype/prefer-option -- an `undefined` slot means \"default equality for this dep\"; replacing it with Eq.default is a 1.x-breaking API change, deferred to 2.0.\n eqs?: ReadonlyArray<Eq<unknown> | undefined>,\n): A {\n const prev = useRef<DependencyList | null>(null)\n const tick = useRef(0)\n\n if (prev.current === null) {\n prev.current = deps\n tick.current += 1\n } else {\n const stale = prev.current\n const changed = deps.some((d, i) => {\n const cmp = eqs?.[i] ?? referenceEq\n return !cmp(stale[i], d)\n })\n if (changed) {\n prev.current = deps\n tick.current += 1\n }\n }\n\n return useMemo(factory, [tick.current])\n}\n"],"mappings":"+FAWA,SAAgBA,EACd,EACA,EAEA,EACG,CACH,IAAMC,EAAOC,EAA8B,IAAI,EACzCC,EAAOD,EAAO,CAAC,EAErB,GAAID,EAAK,UAAY,KACnB,EAAK,QAAUG,EACf,EAAK,SAAW,MACX,CACL,IAAMC,EAAQJ,EAAK,QACHG,EAAK,MAAM,EAAG,IAErB,EADKE,IAAMC,IAAMC,EAAA,CACZH,EAAME,GAAIE,CAAC,CAEf,IACR,EAAK,QAAUL,EACf,EAAK,SAAW,EAEpB,CAEA,OAAOM,EAAQC,EAAS,CAACR,EAAK,OAAO,CAAC,CACxC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useStableState } from "../useStableState-
|
|
1
|
+
import { t as useStableState } from "../useStableState-fi6nURHS.js";
|
|
2
2
|
export { useStableState };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useStableState.js","names":["useStableState","referenceEq","value","setValue","useState","initial","ref","useRef","useCallback","resolved","next","eq"],"sources":["../../src/hooks/useStableState.ts"],"sourcesContent":["\"use client\"\n\nimport { useCallback, useRef, useState } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Drop-in replacement for `useState` that no-ops when the next value is equal\n * to the current under `eq`. Defaults to `Object.is` (React's built-in), so the\n * behavior is identical to `useState` unless an `eq` is supplied.\n *\n * @param initial - Initial value or a lazy producer (called once)\n * @param eq - Comparator used to decide whether to skip the update\n */\nexport function useStableState<A>(\n initial: A | (() => A),\n eq: Eq<A> = referenceEq as Eq<A>,\n): readonly [A, (next: A | ((prev: A) => A)) => void] {\n const [value, setValue] = useState<A>(initial)\n const ref = useRef<A>(value)\n ref.current = value\n\n const setStable = useCallback(\n (next: A | ((prev: A) => A)) => {\n const resolved = typeof next === \"function\" ? (next as (prev: A) => A)(ref.current) : next\n if (!eq(ref.current, resolved)) {\n setValue(resolved)\n }\n },\n [eq],\n )\n\n return [value, setStable] as const\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useStableState.js","names":["useStableState","referenceEq","value","setValue","useState","initial","ref","useRef","useCallback","resolved","next","eq"],"sources":["../../src/hooks/useStableState.ts"],"sourcesContent":["\"use client\"\n\nimport { useCallback, useRef, useState } from \"react\"\n\nimport { type Eq, referenceEq } from \"./eq\"\n\n/**\n * Drop-in replacement for `useState` that no-ops when the next value is equal\n * to the current under `eq`. Defaults to `Object.is` (React's built-in), so the\n * behavior is identical to `useState` unless an `eq` is supplied.\n *\n * @param initial - Initial value or a lazy producer (called once)\n * @param eq - Comparator used to decide whether to skip the update\n */\nexport function useStableState<A>(\n initial: A | (() => A),\n eq: Eq<A> = referenceEq as Eq<A>,\n): readonly [A, (next: A | ((prev: A) => A)) => void] {\n const [value, setValue] = useState<A>(initial)\n const ref = useRef<A>(value)\n ref.current = value\n\n const setStable = useCallback(\n (next: A | ((prev: A) => A)) => {\n const resolved = typeof next === \"function\" ? (next as (prev: A) => A)(ref.current) : next\n if (!eq(ref.current, resolved)) {\n setValue(resolved)\n }\n },\n [eq],\n )\n\n return [value, setStable] as const\n}\n"],"mappings":"iHAcA,SAAgBA,EACd,EACA,EAAYC,EACwC,CACpD,GAAM,CAACC,EAAOC,GAAYC,EAAYC,CAAO,EACvCC,EAAMC,EAAUL,CAAK,EAa3B,MAZA,GAAI,QAAUA,EAYP,CAACA,EAVUM,EACf,GAA+B,CAC9B,IAAMC,EAAW,OAAOC,GAAS,WAAcA,EAAwBJ,EAAI,OAAO,EAAII,EACjFC,EAAGL,EAAI,QAASG,CAAQ,GAC3BN,EAASM,CAAQ,CAErB,EACA,CAACE,CAAE,CAGkB,CAAC,CAC1B"}
|
package/dist/hooks/useTry.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as useTry } from "../useTry-
|
|
1
|
+
import { t as useTry } from "../useTry-B0HIcFFb.js";
|
|
2
2
|
export { useTry };
|