126 Commits

Author SHA1 Message Date
Julien Valverdé d32389fa81 Fix CI
Lint / lint (push) Successful in 55s
2026-07-26 00:13:35 +02:00
Julien Valverdé 5e9c25641f Fix
Lint / lint (push) Failing after 39s
2026-07-25 23:56:44 +02:00
Julien Valverdé 2b677f8810 Fix tests
Lint / lint (push) Failing after 39s
2026-07-25 23:54:24 +02:00
Julien Valverdé 73399c1b24 Fix tests
Lint / lint (push) Failing after 39s
2026-07-25 23:52:11 +02:00
Julien Valverdé 65e90325d0 Change build system
Lint / lint (push) Failing after 40s
2026-07-25 23:47:16 +02:00
Julien Valverdé 3533fa0c84 Remove ErrorObserver
Lint / lint (push) Failing after 39s
2026-07-25 22:48:42 +02:00
Julien Valverdé c40df980ed Rename vite plugin
Lint / lint (push) Failing after 38s
2026-07-25 22:44:09 +02:00
Julien Valverdé 23547afe91 Fix refresh plugin
Lint / lint (push) Failing after 39s
2026-07-25 22:27:11 +02:00
Julien Valverdé 462895a3c2 Add Refreshable trait
Lint / lint (push) Failing after 1m45s
2026-07-25 02:02:17 +02:00
Julien Valverdé 116c1b440d Add tests to CI
Lint / lint (push) Failing after 43s
2026-07-24 23:42:22 +02:00
Julien Valverdé 7d6bab81be Fix ScopeRegistry
Lint / lint (push) Failing after 41s
2026-07-24 23:07:06 +02:00
Julien Valverdé faac021527 Fix Async
Lint / lint (push) Failing after 42s
2026-07-23 04:58:41 +02:00
Julien Valverdé 3a25b1a34e Fix example
Lint / lint (push) Failing after 41s
2026-07-23 04:36:31 +02:00
Julien Valverdé 296f65ee1b Fix
Lint / lint (push) Failing after 42s
2026-07-23 04:13:27 +02:00
Julien Valverdé d8b9c0394c Fix
Lint / lint (push) Failing after 48s
2026-07-23 03:35:38 +02:00
Julien Valverdé 71f66cd5bc Fix
Lint / lint (push) Failing after 49s
2026-07-23 03:33:15 +02:00
Julien Valverdé d09c17e1c2 Fix
Lint / lint (push) Failing after 48s
2026-07-23 03:26:14 +02:00
Julien Valverdé cce0a47ea5 Fix
Lint / lint (push) Failing after 51s
2026-07-23 03:22:16 +02:00
Julien Valverdé 7e816d041e Fix
Lint / lint (push) Failing after 48s
2026-07-23 03:13:17 +02:00
Julien Valverdé c6eeb7b8bc Fix
Lint / lint (push) Failing after 2m8s
2026-07-23 03:08:42 +02:00
Julien Valverdé ccb33973db Fix
Lint / lint (push) Failing after 41s
2026-07-23 01:34:17 +02:00
Julien Valverdé 3516ba05f8 Fix
Lint / lint (push) Failing after 42s
2026-07-23 01:30:29 +02:00
Julien Valverdé cb62639829 Implement ScopeRegistry
Lint / lint (push) Failing after 42s
2026-07-23 01:22:14 +02:00
Julien Valverdé 8fed17789a ScopeMap -> ScopeRegistry
Lint / lint (push) Failing after 43s
2026-07-22 22:51:38 +02:00
Julien Valverdé c151b4608f Add report
Lint / lint (push) Failing after 41s
2026-07-22 22:22:25 +02:00
Julien Valverdé cce1d6e485 Fix
Lint / lint (push) Failing after 42s
2026-07-22 21:41:26 +02:00
Julien Valverdé a5867ef36a Fix Query tests
Lint / lint (push) Failing after 42s
2026-07-22 21:07:16 +02:00
Julien Valverdé fa058ecf53 Improve README
Lint / lint (push) Failing after 43s
2026-07-22 20:56:51 +02:00
Julien Valverdé ffed4bda40 Improve README 2026-07-22 20:56:42 +02:00
Julien Valverdé c48ca0acd3 Add ErrorHandler report
Lint / lint (push) Failing after 2m32s
2026-07-22 06:04:37 +02:00
Julien Valverdé 6e7172a24e Add React Refresh feasibility report
Lint / lint (push) Failing after 42s
2026-07-22 05:11:45 +02:00
Julien Valverdé b91729888c Fix
Lint / lint (push) Failing after 41s
2026-07-22 04:56:32 +02:00
Julien Valverdé 5f3e560969 Fix docs
Lint / lint (push) Failing after 41s
2026-07-22 04:52:40 +02:00
Julien Valverdé 8f8a66f7a9 Add logo
Lint / lint (push) Failing after 41s
2026-07-22 04:51:05 +02:00
Julien Valverdé 9789969ecf Improve docs landing page
Lint / lint (push) Failing after 44s
2026-07-22 04:24:59 +02:00
Julien Valverdé 4be5b12121 Update docs
Lint / lint (push) Failing after 43s
2026-07-22 04:13:14 +02:00
Julien Valverdé 547aeec2fb Update docs
Lint / lint (push) Failing after 41s
2026-07-22 03:51:26 +02:00
Julien Valverdé 1651e96696 Update docs
Lint / lint (push) Failing after 44s
2026-07-22 03:44:16 +02:00
Julien Valverdé 22933b2a09 Update docs
Lint / lint (push) Failing after 41s
2026-07-22 03:34:27 +02:00
Julien Valverdé 36c47e1b4b Improve docs
Lint / lint (push) Failing after 42s
2026-07-22 03:23:16 +02:00
Julien Valverdé c4b954d21c Update docs
Lint / lint (push) Failing after 42s
2026-07-22 02:51:43 +02:00
Julien Valverdé f669dbee3a Add Mutation docs
Lint / lint (push) Failing after 42s
2026-07-22 02:21:36 +02:00
Julien Valverdé e610fa1773 Add Query docs
Lint / lint (push) Failing after 1m44s
2026-07-22 02:09:57 +02:00
Julien Valverdé 75f51cdf1c Overhaul form docs
Lint / lint (push) Failing after 42s
2026-07-22 01:31:17 +02:00
Julien Valverdé d7f0aa1a38 Fix docs
Lint / lint (push) Failing after 42s
2026-07-22 01:17:11 +02:00
Julien Valverdé 9a93d72e48 Change useContextFromLayer to useLayer
Lint / lint (push) Failing after 43s
2026-07-20 20:40:13 +02:00
Julien Valverdé 19d5aba009 Docs work
Lint / lint (push) Failing after 47s
2026-07-20 07:35:44 +02:00
Julien Valverdé 5017ccf5ba Docs work
Lint / lint (push) Failing after 46s
2026-07-20 07:26:17 +02:00
Julien Valverdé 10784322b1 Docs work
Lint / lint (push) Failing after 46s
2026-07-20 07:24:17 +02:00
Julien Valverdé 1fa2440d71 Fix
Lint / lint (push) Failing after 49s
2026-07-20 07:20:26 +02:00
Julien Valverdé fb4fd633dc Fix
Lint / lint (push) Failing after 40s
2026-07-20 03:14:40 +02:00
Julien Valverdé c804262e5f Fix
Lint / lint (push) Failing after 40s
2026-07-20 03:10:40 +02:00
Julien Valverdé a47ae73618 Add a working LensForm example
Lint / lint (push) Failing after 40s
2026-07-20 03:10:27 +02:00
Julien Valverdé efdf490bc0 Fix form example
Lint / lint (push) Failing after 39s
2026-07-20 02:43:38 +02:00
Julien Valverdé 8bbeed9b8d Fix scope registry race condition
Lint / lint (push) Successful in 1m43s
2026-07-20 02:15:39 +02:00
Julien Valverdé 4ba7943bef Test 2026-07-20 01:59:29 +02:00
Julien Valverdé 89c8ac59bc Fix
Lint / lint (push) Successful in 39s
2026-07-20 01:33:45 +02:00
Julien Valverdé d21ff53c26 Fix Query state
Lint / lint (push) Successful in 39s
2026-07-20 00:57:25 +02:00
Julien Valverdé 6551969bb1 Fix Query lifecycle
Lint / lint (push) Successful in 39s
2026-07-19 20:41:59 +02:00
Julien Valverdé cc01e46997 Fix runtime
Lint / lint (push) Successful in 38s
2026-07-19 18:55:01 +02:00
Julien Valverdé 1dc8368750 Rename withRuntime to withContext
Lint / lint (push) Successful in 39s
2026-07-19 18:44:01 +02:00
Julien Valverdé f22743eefe Fix
Lint / lint (push) Successful in 39s
2026-07-19 18:20:22 +02:00
Julien Valverdé 31d87ffcab Fix
Lint / lint (push) Successful in 38s
2026-07-19 04:00:46 +02:00
Julien Valverdé 885cff74b3 Example fix
Lint / lint (push) Successful in 38s
2026-07-19 03:27:41 +02:00
Julien Valverdé cbb050673b Fix
Lint / lint (push) Successful in 38s
2026-07-19 03:20:24 +02:00
Julien Valverdé 9b25ef4b57 Fix
Lint / lint (push) Successful in 39s
2026-07-19 03:15:55 +02:00
Julien Valverdé be1038fc8d Rename Form subtypes
Lint / lint (push) Failing after 40s
2026-07-19 03:01:38 +02:00
Julien Valverdé 956c77d45b Fix
Lint / lint (push) Failing after 38s
2026-07-19 02:56:32 +02:00
Julien Valverdé 985556b430 Fix
Lint / lint (push) Failing after 39s
2026-07-19 02:50:37 +02:00
Julien Valverdé feced4732f Refactor Form subtypes
Lint / lint (push) Failing after 1m43s
2026-07-19 02:43:48 +02:00
Julien Valverdé cc64ae785d Refactor Form
Lint / lint (push) Failing after 39s
2026-07-19 00:46:36 +02:00
Julien Valverdé 3fc3904c6c Upgrade effect-lens
Lint / lint (push) Failing after 1m44s
2026-07-17 21:25:07 +02:00
Julien Valverdé 23cdfb3894 Refactor Query
Lint / lint (push) Failing after 37s
2026-07-17 01:15:53 +02:00
Julien Valverdé 7a7783e7de Refactor Query
Lint / lint (push) Failing after 45s
2026-07-07 21:22:05 +02:00
Julien Valverdé e07ce1cd68 Refactor Query
Lint / lint (push) Failing after 1m1s
2026-07-01 21:12:05 +02:00
Julien Valverdé c59e2ee035 Refactor Query/Mutation
Lint / lint (push) Failing after 14s
2026-06-26 02:54:40 +02:00
Julien Valverdé e5ac120cea Refactor Mutation
Lint / lint (push) Failing after 48s
2026-06-26 02:38:24 +02:00
Julien Valverdé 015aa0c816 Refactor Query
Lint / lint (push) Failing after 49s
2026-06-25 04:37:14 +02:00
Julien Valverdé 5945953555 Refactor QueryClient
Lint / lint (push) Failing after 16s
2026-06-24 00:54:10 +02:00
Julien Valverdé 65fcfb395e Refactor
Lint / lint (push) Successful in 15s
2026-06-23 04:08:49 +02:00
Julien Valverdé a86cb7e024 Refactor Component
Lint / lint (push) Failing after 16s
2026-06-23 03:57:56 +02:00
Julien Valverdé 24ce543092 Fix
Lint / lint (push) Failing after 14s
2026-06-23 03:32:13 +02:00
Julien Valverdé 6b5c501a98 Refactor
Lint / lint (push) Failing after 1m6s
2026-06-23 03:25:58 +02:00
Julien Valverdé c8df30480a Fix
Lint / lint (push) Failing after 16s
2026-06-22 06:44:31 +02:00
Julien Valverdé a38be0b172 Component v4 migration work
Lint / lint (push) Failing after 16s
2026-06-22 06:36:32 +02:00
Julien Valverdé 091e102b23 Add Effect v4 version
Lint / lint (push) Successful in 48s
2026-06-22 02:04:20 +02:00
Julien Valverdé b7ea35006d Add forms doc
Lint / lint (push) Successful in 16s
2026-06-22 01:38:06 +02:00
Julien Valverdé 257d505fdf Docs
Lint / lint (push) Successful in 14s
2026-06-12 01:51:30 +02:00
Julien Valverdé 241d489b0c Docs
Lint / lint (push) Successful in 14s
2026-06-12 01:44:40 +02:00
Julien Valverdé cf2cb8bf09 Docs
Lint / lint (push) Successful in 16s
2026-06-11 14:25:00 +02:00
Julien Valverdé 7ae5d08555 Docs
Lint / lint (push) Successful in 46s
2026-06-11 12:29:10 +02:00
Julien Valverdé 9fb56da120 Docs
Lint / lint (push) Successful in 35s
2026-06-09 22:25:53 +02:00
Julien Valverdé 1cead4bb7b Docs
Lint / lint (push) Successful in 16s
2026-06-09 22:21:26 +02:00
Julien Valverdé ad1ef4a73b Docs
Lint / lint (push) Successful in 16s
2026-06-09 22:15:41 +02:00
Julien Valverdé 81fb1dcf42 Docs
Lint / lint (push) Successful in 16s
2026-06-09 21:59:12 +02:00
Julien Valverdé c90c5f9532 Docs
Lint / lint (push) Successful in 15s
2026-06-09 21:44:08 +02:00
Julien Valverdé 436dc275b3 Docs
Lint / lint (push) Successful in 16s
2026-06-09 20:34:24 +02:00
Julien Valverdé 5791c08b51 Docs
Lint / lint (push) Successful in 18s
2026-06-09 19:00:09 +02:00
Julien Valverdé a74ec6e398 Docs
Lint / lint (push) Successful in 17s
2026-06-09 18:09:47 +02:00
Julien Valverdé fe65cd96aa Docs
Lint / lint (push) Successful in 16s
2026-06-09 15:30:00 +02:00
Julien Valverdé c492408969 Docs
Lint / lint (push) Successful in 14s
2026-06-09 14:50:25 +02:00
Julien Valverdé 86bdb5374e Docs
Lint / lint (push) Successful in 15s
2026-06-09 13:35:58 +02:00
Julien Valverdé 054f8773f0 Docs
Lint / lint (push) Successful in 16s
2026-06-09 11:34:13 +02:00
Julien Valverdé eb81ff16d2 Docs
Lint / lint (push) Successful in 15s
2026-06-09 11:27:39 +02:00
Julien Valverdé 3000ff2d87 Docs
Lint / lint (push) Successful in 17s
2026-06-09 11:18:08 +02:00
Julien Valverdé 91670779fe Docs
Lint / lint (push) Successful in 15s
2026-06-09 11:16:33 +02:00
Julien Valverdé d3525aaad7 Docs
Lint / lint (push) Successful in 16s
2026-06-09 11:09:47 +02:00
Julien Valverdé 0a59fdf2b4 Docs
Lint / lint (push) Successful in 17s
2026-06-09 10:54:00 +02:00
Julien Valverdé 88b3a1c98a Docs
Lint / lint (push) Successful in 19s
2026-06-09 10:48:46 +02:00
Julien Valverdé 74a8e3a102 Fix
Lint / lint (push) Successful in 47s
2026-06-09 10:42:42 +02:00
Julien Valverdé 8303c1f70e Docs
Lint / lint (push) Successful in 16s
2026-06-08 22:23:49 +02:00
Julien Valverdé c941e5970a Docs
Lint / lint (push) Successful in 16s
2026-06-08 22:19:58 +02:00
Julien Valverdé a8d4520fed Docs
Lint / lint (push) Successful in 16s
2026-06-08 22:03:42 +02:00
Julien Valverdé d40ac326ec Docs
Lint / lint (push) Successful in 15s
2026-06-08 22:01:58 +02:00
Julien Valverdé 05a8ae9ae4 Docs
Lint / lint (push) Successful in 14s
2026-06-08 21:47:27 +02:00
Julien Valverdé 25fac0ca32 Fix
Lint / lint (push) Successful in 15s
2026-06-08 15:35:15 +02:00
Julien Valverdé 845aa193ba Add getting started docs
Lint / lint (push) Successful in 16s
2026-06-08 13:55:16 +02:00
Julien Valverdé 1292b9885a Fix
Lint / lint (push) Successful in 48s
2026-06-08 11:14:31 +02:00
Julien Valverdé 658e6bb8ea Fix tests
Lint / lint (push) Successful in 13s
2026-06-07 15:15:57 +02:00
Julien Valverdé 7638324f2f Add tests
Lint / lint (push) Successful in 14s
2026-06-07 15:10:26 +02:00
Julien Valverdé fcb29c0d76 Add tests
Lint / lint (push) Successful in 15s
2026-06-07 15:01:07 +02:00
Julien Valverdé ea0108650b Add tests
Lint / lint (push) Successful in 47s
2026-06-07 14:51:18 +02:00
Thilawyn 721ab7d736 0.3.0 (#50)
Publish / publish (push) Successful in 26s
Lint / lint (push) Successful in 13s
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: Thilawyn/effect-fc#50
2026-06-04 17:06:51 +02:00
Thilawyn e5d0808b02 0.2.6 (#49)
Publish / publish (push) Successful in 30s
Lint / lint (push) Successful in 14s
Co-authored-by: Renovate Bot <renovate-bot@valverde.cloud>
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: Thilawyn/effect-fc#49
2026-05-04 02:10:53 +02:00
Thilawyn ff13e941e3 0.2.5 (#43)
Publish / publish (push) Successful in 52s
Lint / lint (push) Successful in 14s
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Co-authored-by: Renovate Bot <renovate-bot@valverde.cloud>
Reviewed-on: Thilawyn/effect-fc#43
2026-03-31 21:01:12 +02:00
Thilawyn 67b01d4621 0.2.4 (#38)
Publish / publish (push) Successful in 59s
Lint / lint (push) Successful in 15s
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Co-authored-by: Renovate Bot <renovate-bot@valverde.cloud>
Reviewed-on: Thilawyn/effect-fc#38
2026-03-16 00:30:17 +01:00
144 changed files with 17688 additions and 1686 deletions
View File
+2
View File
@@ -16,3 +16,5 @@ jobs:
run: bun lint:tsc
- name: Lint Biome
run: bun lint:biome
- name: Test
run: bun run test
+175
View File
@@ -0,0 +1,175 @@
# Effect FC Next error-handling review
## Verdict
`ErrorObserver` is a reasonable *opt-in failure notification bus*, but it is
not an application error handler. It neither recovers from errors nor, in
`effect-fc-next`, observes the application's effects by default. Keeping it
as the central error-handling mechanism would make error delivery implicit,
incomplete, and easy to duplicate.
The better model is:
1. Handle expected, typed failures where the operation is rendered or invoked.
2. Report unhandled/background failures through one explicit runtime boundary.
3. Let React error boundaries render defects and render-time failures.
In particular, queries, mutations, and forms should keep their current
`AsyncResult`/validation state as the user-facing error path; a global service
should not replace that state.
## What exists today
`packages/effect-fc-next/src/ErrorObserver.ts` provides a context service
backed by an unbounded `PubSub<Cause.Cause<E>>`:
- `handle(effect)` uses `Effect.tapCause` to publish every non-successful
cause, then preserves the original result;
- `subscribe` exposes a scoped subscription;
- module-level `handle(effect)` is a no-op when the service is absent.
This is narrower than the similarly named service in the legacy
`packages/effect-fc` package. The legacy default runtime layer installs an
Effect supervisor that attempts to publish every failed fiber. The Next
runtime's `preludeLayer` contains only `Component.ScopeMap`; it does not
install `ErrorObserver.layer`. There are also no `ErrorObserver.handle(...)`
call sites in `effect-fc-next`.
Therefore, as checked at this revision, a consumer can create and subscribe to
the service manually, but no failure is automatically delivered to it. It is
not currently an app-wide error mechanism.
## What is good about the pattern
- It keeps the original failure intact. Observability does not accidentally
turn a failing effect into a successful one.
- It publishes `Cause`, not only `E`, so defects, interruption, parallel
failures, and traces are not discarded.
- The service is optional, which is useful for a library: applications that do
not want reporting do not need to install a logger/telemetry dependency.
- A scoped subscription has the right basic lifetime shape for a React
component or a root-level reporting worker.
## Main issues
### It is opt-in at every execution site
Wrapping effects with `ErrorObserver.handle` is both easy to forget and
ambiguous. It does not cover failures from `Component.useCallbackPromise`,
`Async.async`, `useReactEffect`, or a fork unless each path explicitly wraps
the relevant effect. Conversely, adding wrappers at multiple levels reports
the same failure more than once.
### Its type promise is unsound
`handle<A, E1, R>` accepts any `E1` then casts its `Cause<E1>` to
`Cause<E>`. A value retrieved as `ErrorObserver<NetworkError>` can receive a
`ValidationError` or a defect. `Cause` is correctly broader than a single
app-error type, but the generic parameter suggests filtering that the service
does not perform.
### "Error" and "handle" blur distinct responsibilities
The code only observes/reports failures; it does not decide a fallback, show a
toast, retry, recover, log, or rethrow. Calling it a handler encourages using
a global side channel for errors that should remain part of local UI state.
### An unbounded, raw pub/sub is a risky public policy
A slow or absent subscriber can retain an unbounded backlog. Consumers must
also inspect every `Cause`, decide whether interruption is meaningful, dedupe
retries, redact data, and ensure their own reporting failure does not affect
the application. Those are application policy choices, not library defaults.
### It is not a React error boundary
React error boundaries cover render/lifecycle errors in the React tree. They
do not replace reporting of failures from detached/background Effect fibers,
and an Effect failure should not be blindly thrown into render merely to reach
one. These are complementary boundaries.
## Recommended replacement
Replace the public observer with a small **`FailureReporter`** service. Make
reporting explicit at the handful of Effect-to-JavaScript runtime boundaries,
not at every business effect.
```ts
interface FailureReporter {
readonly report: (event: FailureEvent) => Effect.Effect<void>
}
interface FailureEvent {
readonly cause: Cause.Cause<unknown>
readonly source: "event" | "effect" | "async-component" | "background"
readonly componentName?: string
readonly operation?: string
}
```
The default implementation should be a no-op. Application layers can add
logging, Sentry/OpenTelemetry, a toast dispatcher, or a bounded in-memory
development sink. `report` should be made best-effort at the boundary
(`Effect.ignore`/equivalent after recording its own diagnostics) so reporting
outages never replace the original failure.
Provide one internal combinator, for example `reportFailure(effect, metadata)`,
which reports only a non-interruption failure and then re-fails with exactly
the original cause. Use it in these adapters:
- `Component.useCallbackPromise` and any promise-returning event callback;
- `Component.useReactEffect` / layout-effect execution;
- `Async.async` before the promise is handed to React;
- library-created detached fibers whose failures are not represented in an
`AsyncResult`.
Do **not** use it for query/mutation/form operations whose failure is already
captured and displayed in `AsyncResult`; report only when the caller abandons
or explicitly escalates that result. This avoids a failed request producing a
toast/log and an inline error merely because it was expected.
At the application root, pair this with a normal React `ErrorBoundary` that
reports render defects and presents the recovery UI. Keep its reporting
separate from the Effect service; optionally normalize both into the same
application telemetry event schema.
## Lower-risk incremental path
If replacing the API now is too disruptive:
1. Do not add `ErrorObserver.layer` to the Next prelude merely to make it look
global. A hidden global bus still has unclear coverage and duplicate-event
semantics.
2. Rename `handle` to `observeFailure` and document that it is an explicit
notification wrapper, not recovery or global supervision.
3. Remove the generic `E`, or expose `Cause.Cause<unknown>`; alternatively
accept a predicate/decoder that actually filters before publication.
4. Make the queue policy explicit: preferably no public queue, or a bounded,
dropping development event sink with a dropped-event counter.
5. Add tests for: preservation of the original exit, defects, interruption
filtering, a failing reporter, duplicate wrapping, and teardown of a scoped
subscriber.
## Names
`ErrorHandler` is inaccurate, and `ErrorObserver` is acceptable only for the
current low-level notification primitive. Recommended names by role:
| Role | Recommended name | Why |
| --- | --- | --- |
| Application service that sends telemetry/logs | `FailureReporter` | Says it reports an Effect failure without claiming recovery. |
| Wrapper combinator | `reportFailure` | Describes the side effect and retains the original failure. |
| Optional stream-like dev/testing primitive | `FailureEvents` or `FailureEventBus` | Makes the pub/sub nature explicit. |
| React UI component | `AppErrorBoundary` | Uses React's established boundary terminology. |
I would use **`FailureReporter`** for the replacement. "Failure" is more
accurate than "error" in Effect because it can intentionally retain the full
`Cause`, while "reporter" makes the non-recovery responsibility clear.
## Decision
Treat `ErrorObserver` as an experimental diagnostic primitive, not the app
error architecture. Design expected errors into local state, add a
best-effort `FailureReporter` at the few execution boundaries, and use a React
error boundary for render failures. This gives complete, testable coverage
without turning every domain failure into a global event.
+484
View File
@@ -0,0 +1,484 @@
# EffectReact Render Lifecycle Report
## Purpose
This report describes the lifecycle problem in `effect-fc-next`, why abandoned React renders leak Effect scopes, what the experimental implementations attempted, why those implementations are not satisfactory, and how a robust system should be designed.
The experimental implementation discussed here has been removed from the source tree. This document is intended as design material for a clean reimplementation.
## Executive summary
The fundamental problem is not scope disposal by itself. It is that `effect-fc-next` performs Effect work and creates resource scopes while React is rendering.
React distinguishes between two broad phases:
1. **Render:** React evaluates components and builds a prospective tree. React may retry, pause, duplicate, or permanently abandon this work.
2. **Commit:** React accepts a rendered tree and runs layout and passive effects. Cleanup callbacks only exist for work that reached this phase.
The existing `Component.useScope` creates and registers an Effect scope during render, but installs its cleanup from `React.useEffect`. If React abandons the render, the effect is never mounted, its cleanup is never installed, and the render-created scope remains registered indefinitely.
There is no public React callback for “this render attempt was abandoned.” Consequently, an object created only for a render attempt cannot receive deterministic abandonment notification.
A correct architecture must therefore choose one of these models:
- Do not acquire resources until commit.
- Store render-time resources in an external registry under an explicit, stable identity.
- Treat render-time resources as speculative cached entries and garbage-collect idle entries, while ensuring an expired entry can always be recreated safely.
The first model is simplest. The second is the model used by atom/resource systems. The third is necessarily a cache/TTL design rather than exact component-lifecycle tracking.
## The original `useScope` lifecycle
The implementation in `Component.ts` performs approximately the following work:
```ts
function useScope(dependencies) {
const { key, scope } = React.useMemo(() => {
const key = makeIdentity()
const scope = makeEffectScope()
scopeMap.set(key, { scope, closeFiber: none() })
return { key, scope }
}, dependencies)
React.useEffect(() => {
cancelPreviouslyScheduledClose(key)
return () => {
const closeFiber = sleep(debounce).andThen(close(scope)).fork()
scopeMap.set(key, { scope, closeFiber: some(closeFiber) })
}
}, [key])
return scope
}
```
The intended committed lifecycle is:
```text
render
create scope
insert scope into ScopeMap
commit
run useEffect setup
cancel any pending close left by a rapid remount
unmount or dependency change
run useEffect cleanup
wait for the debounce
close the scope
remove it from ScopeMap
```
For an ordinary committed component, this works. The debounce also bridges React Strict Modes development-only effect cycle:
```text
effect setup
effect cleanup schedules close
effect setup again cancels close
```
The failing lifecycle is:
```text
render
create scope
insert scope into ScopeMap
React abandons render
useEffect setup never runs
useEffect cleanup therefore never exists
no close is scheduled
ScopeMap retains the scope forever
```
Suspense can trigger this by throwing a promise before the component commits. Concurrent rendering and failed/erroring renders can produce the same category of problem.
## Why React cannot directly report abandonment
Hooks such as `useEffect` and `useLayoutEffect` describe the lifetime of a committed component. They are deliberately not executed for render work that never commits.
Render-time hook state does not solve this:
- `useMemo` may be discarded with the render attempt.
- `useRef` belongs to the same provisional fiber state.
- `useState` belongs to the same provisional fiber state.
- Cleanup returned from `useEffect` only exists after effect setup has run.
- A component cannot read its React `key`; React consumes it before props reach the component.
JavaScript garbage collection is also insufficient. `FinalizationRegistry` is nondeterministic and cannot be used to guarantee timely execution of Effect finalizers.
This means there is no reliable per-render-attempt destructor available to application code.
## Why Effect Atom can use an external lifecycle
Effect Atom has something a component scope does not: an atom is an explicit object with stable identity outside React.
The conceptual flow is:
```text
React receives an Atom object
AtomRegistry.getOrCreate(atom)
├── returns an existing external node
└── or creates a new external node and schedules idle removal
React commit subscribes to the node
└── subscription prevents idle removal
React unmount unsubscribes
└── node becomes eligible for removal
```
If a render is abandoned, no subscription is established. The node is still owned by the external registry and can remove itself when idle. If React retries later, it asks the registry for the atom again. The registry either returns the still-live node or creates a replacement.
`useSyncExternalStore` belongs naturally in this design because an atom node has a changing snapshot. React must both subscribe to changes and read a consistent value.
A component scope does not naturally have either property:
- It has no explicit identity external to React.
- Its scope object is not a changing UI snapshot.
Therefore, copying the Atom mechanism without first solving identity produces abstractions that look like an external store but are actually render-attempt bookkeeping.
## The experimental external-store implementation
The first experiment introduced three concepts:
- A runtime-owned registry.
- A render-owned store/handle created with `useMemo`.
- A registry entry containing the Effect scope and its cleanup state.
It used `useSyncExternalStore` as follows:
```text
getSnapshot during render
create a scope entry
register it externally
immediately schedule idle cleanup
subscribe during commit
retain the entry
cancel idle cleanup
unsubscribe during unmount
release the entry
schedule cleanup
```
This fixed the abandoned-render leak because an uncommitted entry had no subscriber and its initial cleanup remained scheduled.
It also allowed a closed snapshot to be replaced: if cleanup won a race before subscription, a later `getSnapshot` could create another entry.
However, it had several design problems:
1. The “store” was created by `useMemo`, so it was not truly an externally identified store.
2. `useSyncExternalStore` was being used primarily as a commit/unmount detector rather than for observable state.
3. The names “store,” “entry,” and “snapshot” obscured the resource lifecycle.
4. It introduced listener notification machinery even though a scope has no meaningful changing value for the UI.
5. It gave the appearance of Atoms semantics without possessing Atoms stable external identity.
It was functional as a self-healing speculative cache, but it was not a clean model for a component instance.
## The experimental retain/release implementation
The second experiment removed `useSyncExternalStore` and represented the lifecycle directly:
```ts
const registration = React.useMemo(
() => scopeMap.register(context, options),
dependencies,
)
React.useLayoutEffect(() => {
registration.retain()
return registration.release
}, [registration])
return registration.scope
```
Registration immediately scheduled its own close. A committed layout effect cancelled that close through `retain()`. Unmount called `release()` and scheduled it again.
This was much easier to understand:
```text
registration created → provisional
layout effect setup → retained
layout effect cleanup → released
idle timeout → closed
```
It still had a serious race:
```text
render creates provisional registration
React delays commit longer than the cleanup debounce
registration closes
React eventually commits the same render
layout effect calls retain on an already-closed registration
component now holds a closed Effect scope
```
The external-store version could recover by returning a new snapshot. The direct retain/release version could not trigger a render-time replacement after the scope had closed.
Increasing the timeout reduces the likelihood but does not make the system correct. A timeout cannot prove that React has abandoned work.
## What the bookkeeping in the experiment was doing
The experimental implementation contained more machinery than the conceptual model suggested. Each part existed for a specific race:
### Runtime registry
The registry retained every scope that might still need disposal. It also allowed `ReactRuntime` disposal to close every remaining scope.
A `HashMap` and `Ref` were used, but neither is essential for a synchronous JavaScript registry. A `Set<Registration>` would express the ownership more clearly unless atomic Effect composition is specifically required.
### Unique registration key
Each speculative render needed a separate map entry. Otherwise two simultaneous attempts could overwrite or close one another.
### Cleanup fiber
The fiber represented the debounce period followed by scope closure. Retaining the registration interrupted this fiber.
### Cleanup generation
Interrupting an Effect fiber is not equivalent to synchronously erasing every continuation it may execute. Consider:
```text
cleanup A is running
retain interrupts cleanup A
release schedules cleanup B
cleanup A's ensuring handler finishes afterward
```
If cleanup A blindly clears the `closeFiber` field, it erases the reference to cleanup B. A monotonically increasing generation lets a finalizer clear the field only if it still represents the current scheduled close.
### Retain count
A count allows repeated retain/release pairs, including Strict Mode effect simulation, without closing while at least one committed lease remains. A boolean is sufficient only if the code can prove that setup and cleanup are perfectly paired and never nested.
These details are legitimate in a speculative cache, but they should be encapsulated behind a much smaller domain model.
## The identity problem
An external registry needs a key that means “this logical resource.” Possible candidates all have limitations:
### Component definition
Using the `Component` object would make every mounted instance of the same component share one scope. That breaks per-instance mount state and cleanup.
### Props or dependency values
Two component instances can have equal props while requiring independent scopes. Object props may also be recreated on every render.
### `useId`
`useId` is intended for accessibility and hydration identifiers, not general cache identity. Concurrent versions of the same logical component can receive the same identifier, and uniqueness across multiple roots depends on root configuration. It should not silently become a resource-ownership contract.
### React `key`
This would be conceptually useful, but React does not expose it to the component. Requiring a separate explicit resource key would be an API change.
### A value made by `useMemo`, `useRef`, or `useState`
These values identify a React fiber lifetime only after React preserves that hook state. They do not survive an abandoned initial render and therefore cannot provide Atom-style external identity.
The clean external design consequently requires an explicit identity supplied by the application or created outside the speculative render.
## Recommended architecture
The API should distinguish committed lifecycle work from render-time resources instead of trying to give them identical semantics.
### 1. Commit-only component scopes
Use this model for resources that do not need to affect the current render synchronously.
```ts
function useCommittedScope(options): ScopeState {
const [scope, setScope] = React.useState<Scope.Closeable | undefined>()
React.useLayoutEffect(() => {
const scope = makeScope(options)
setScope(scope)
return () => runClose(scope)
}, dependencies)
return scope
}
```
The exact API need not use state, but the invariant should be:
> No resource is acquired until React commits the component.
An abandoned render then has nothing to clean up.
This may require changing APIs that currently expect acquisition results during the same render. Such APIs cannot be made commit-only without representing an uninitialized/loading state or causing a subsequent render.
### 2. Explicit external resources for Suspense
Use this model when rendering depends on asynchronous acquisition or a promise.
```ts
interface ResourceKey {
readonly id: string
}
interface ResourceNode<A> {
readonly read: () => A
readonly subscribe: (listener: () => void) => () => void
}
const node = resourceRegistry.getOrCreate(key, createResource)
const value = React.useSyncExternalStore(node.subscribe, node.read, node.read)
```
Here `useSyncExternalStore` is justified because the node is truly external, has a stable explicit key, and has a changing observable result.
The node lifecycle should be:
```text
absent
│ getOrCreate
idle/pending ── subscribe ──► retained
▲ │
└──── unsubscribe ──────────┘
└── idle TTL expires ──► disposed and removed
```
If a node expires before a retry, `getOrCreate` constructs a new node. No React render can remain permanently bound to an expired object without revalidating it.
### 3. Make `useOnMount` semantics explicit
The name `useOnMount` suggests commit-time execution, but if its Effect is evaluated from `useMemo` during render, it is actually speculative render-time execution.
The library should choose and document one of these contracts:
- `useOnMount` runs only after commit and cannot synchronously return an acquisition result during the initial render.
- A separate render-safe primitive accepts only pure/synchronous computation.
- A resource primitive uses an explicit external resource key and supports Suspense.
Allowing arbitrary scoped Effects to execute during render while promising exact component cleanup is the combination that creates the unsolvable abandonment problem.
## Required invariants for an external resource registry
If an Atom-style registry is implemented, it should satisfy all of the following:
1. **Stable identity:** Every node is addressed by an explicit resource key independent of React hook state.
2. **Idempotent lookup:** Repeated reads of the same key return the same live node.
3. **Recoverable expiry:** A lookup after disposal returns a new live node, never the disposed node.
4. **Commit retention:** A committed subscriber prevents idle disposal.
5. **Abandoned-render collection:** A node read by an abandoned render has no subscriber and becomes eligible for disposal.
6. **Reference-counted ownership:** One unmount cannot dispose a node still used by another subscriber.
7. **Idempotent disposal:** Closing a node multiple times has the same result as closing it once.
8. **Registry disposal:** Disposing the runtime closes every node regardless of subscriber state.
9. **Generation safety:** Completion of an older cleanup task cannot overwrite or cancel newer lifecycle state.
10. **Consistent snapshot:** React must never receive a closed node as the current live snapshot.
## Required test matrix
A replacement should be tested against lifecycle sequences, not only final rendered output.
### Normal lifecycle
- Initial commit acquires exactly the intended resources.
- Rerender with equivalent dependencies does not reacquire.
- Dependency change releases the old resource and acquires the new one.
- Unmount runs every finalizer once.
### Strict Mode
- Development render duplication does not leak the discarded attempt.
- Effect setup/cleanup/setup simulation does not prematurely close the committed resource.
- Final unmount closes all remaining resources.
### Suspense
- A render that suspends forever does not retain resources indefinitely.
- A suspended render that retries can obtain a live resource after any idle cleanup.
- Resolving an obsolete promise cannot mutate or resurrect a newer node.
- Changing props while pending disposes or detaches the obsolete computation.
### Concurrent replacement
- The current committed tree remains usable while a replacement tree renders.
- Abandoning the replacement does not affect the current tree.
- Committing the replacement releases the previous tree only after the replacement commits.
### Runtime disposal
- Disposing `ReactRuntime` closes committed resources.
- It also closes idle, pending, and speculative registry nodes.
- Pending async fibers are interrupted without unhandled promise rejections.
### Timing races
- Retain racing with scheduled disposal has a deterministic winner.
- Disposal racing with retry either preserves the live node or forces recreation.
- An old cleanup task cannot clear the handle for a newer cleanup task.
## Suggested minimal domain model
For a real external resource cache, the implementation can remain small if the names match the responsibilities:
```ts
interface ResourceRegistry {
getOrCreate<A>(key: ResourceKey, create: () => ResourceNode<A>): ResourceNode<A>
dispose: Effect.Effect<void>
}
interface ResourceNode<A> {
readonly key: ResourceKey
readonly read: () => A
readonly subscribe: (listener: () => void) => () => void
readonly dispose: Effect.Effect<void>
}
```
Internally, a node can own:
- Its Effect scope.
- Its current result or promise.
- Its subscribers.
- Its idle cleanup task.
- Its lifecycle generation.
There should not be a separate render-owned object called a “store.” React should interact directly with the externally owned node.
For commit-only scopes, the model is even smaller:
```ts
interface ComponentScope {
readonly scope: Scope.Closeable
readonly close: Effect.Effect<void>
}
```
Create it at commit and close it at effect cleanup. No registry, snapshot, subscription, speculative timer, or abandonment recovery is necessary unless runtime-wide disposal must independently own it.
## Final recommendation for `effect-fc-next`
Do not attempt to hide both committed component lifecycles and render-time Suspense resources behind one implicit `Scope` mechanism.
The most defensible direction is:
1. Make normal component acquisition commit-driven.
2. Prevent or clearly label arbitrary Effect acquisition during render.
3. Introduce a separate external resource abstraction for async/Suspense work.
4. Require that abstraction to have an explicit stable key.
5. Use `useSyncExternalStore` only for those externally owned nodes whose snapshots can change.
6. Treat idle timeout as cache eviction, not as proof that React abandoned a render.
7. Make every read capable of replacing an expired node.
If backward compatibility requires speculative per-render scopes, document that the debounce is heuristic and retain the recovery behavior that can replace a scope which expires before commit. That model can prevent leaks, but it should not be presented as exact React component-instance lifecycle tracking.
+335
View File
@@ -0,0 +1,335 @@
# React Fast Refresh for Effect View components
Date: 2026-07-22
## Executive summary
Implementing Fast Refresh for Effect View components is feasible, but it is not a one-line change to React Refresh's component detection.
The current API has two identities:
1. `Component.make` / `Component.makeUntraced` creates an Effect View descriptor.
2. `.use` later synthesizes the React function component that is actually mounted.
Vite's React Refresh transform sees the descriptor definition, while React reconciles the synthesized function. In addition, `.use` deliberately caches that function. A newly evaluated module therefore creates a new descriptor, but the mounted function continues to close over the old descriptor.
The recommended implementation is a bundler-neutral development refresh protocol in Effect View plus a Vite compiler adapter. The plugin should assign stable source IDs and hook signatures to Effect View definitions. The main library's protocol should retain the current descriptor, notify mounted instances after an update, preserve state when the signature is compatible, and remount when it is not. The Vite adapter should retain those cells in `import.meta.hot.data` and manage accept/invalidate behavior.
My feasibility assessment is:
- **Safe refresh with remount on every edit:** high confidence, moderate effort.
- **State-preserving refresh with React-like hook signature handling:** high confidence, moderate-to-high effort.
- **A runtime-only or export-detection-only fix:** not sufficient.
- **Bundler-independent support in the first release:** not recommended; establish the protocol with Vite first.
A production-quality Vite implementation is likely **1018 engineer-days**, including the runtime bridge, transform, lifecycle tests, examples, and documentation. A remounting proof of concept should take **24 days**.
## Scope examined
The implementation target is `effect-fc-next` (Effect 4 beta), which is
expected to become `effect-view`. The legacy `effect-fc` package is not
supported by the Vite plugin.
## How Effect View rendering works today
`Component.make` creates a function-shaped descriptor with a `body` property and `ComponentPrototype`; it does not create the React component that will be mounted. See [`packages/effect-fc-next/src/Component.ts`](packages/effect-fc-next/src/Component.ts), around `make`, `makeUntraced`, and `ComponentImplPrototype`.
The relevant path is:
```text
source definition
-> Effect View descriptor (`body`, options, prototype traits)
-> `.use`
-> synthesized React function bound to an Effect runtime/context
-> optional `React.memo` / async transformation
-> mounted React fiber
```
In `effect-fc-next`, `asFunctionComponent` creates a closure over the descriptor
and Effect context. `.use` retains that synthesized function in `componentRef`
while the relevant Effect service identities remain unchanged, and
`withContext` renders the function returned by `.use`.
This caching is useful during ordinary rendering: without it, React would see a new component type and remount on every parent render. It is also why a newly evaluated module cannot replace the mounted implementation by itself.
## What the current Vite transform does
I inspected Vite's development transform for representative files with the repository's actual configuration and dependency versions.
For a class definition such as `TodosView`, the transform produced the equivalent of:
```js
var _s = $RefreshSig$()
export class TodosView extends _s(
Component.make("TodosView")(
_s(function* () {
_s()
// component body
}, "<signature>", false, () => [
Subscribable.useAll,
Component.useOnMount,
])
),
"<signature>",
false,
() => [Subscribable.useAll, Component.useOnMount],
) {}
```
The transform recognizes hook-shaped calls and calculates a signature, but it emits no `$RefreshReg$` call and no refresh boundary for the Effect View. The same was true for `const` definitions created with `Component.make` and for route components ending in `.pipe(Component.withRuntime(...))`.
This happens because `Component.make(...)` and Effect's `pipe(...)` are not React component patterns known to the transform. Class-style Effect Views also inherit from a non-React base, so React Refresh's runtime heuristic deliberately does not classify them as React classes.
Even if export registration were forced, registering the descriptor would not be enough. The descriptor is not the type stored in the mounted React fiber; the lazily synthesized function is.
Consequently, edits currently propagate through ordinary Vite HMR invalidation. Whether they eventually update through an importer or cause a page reload depends on the surrounding module graph and router integration, but React Refresh cannot directly reconcile the edited Effect View family.
## Runtime experiment
The initial feasibility study used the legacy implementation for a focused
jsdom/React identity experiment. Its descriptor-caching result also applies to
`effect-fc-next`, but the legacy package is not an implementation target:
1. Render an Effect View containing `React.useState(0)`.
2. Increment it to `old:1`.
3. Create a replacement descriptor with a body rendering `new:<count>`.
4. Rerender the existing entry component.
5. Copy the replacement `body` onto the descriptor retained by the mounted component and rerender again.
Observed output:
```text
after local state update: old:1
new descriptor, old mounted entry: old:1
mutated descriptor, stable entry: new:1
```
This proves two things:
- Module reevaluation alone cannot update a mounted Effect View because its synthesized function retained the old descriptor.
- Updating the retained implementation and scheduling a render can apply new code while preserving React state.
The experiment was temporary and left no probe files in the repository.
## Required semantics
A complete implementation should provide the same safety contract developers expect from Fast Refresh:
- Apply edits without reloading the page.
- Preserve React state when the hook signature is compatible.
- Remount when hooks are added, removed, reordered, or otherwise become incompatible.
- Recover after a syntax or render error.
- Support both `const` and class definition styles.
- Support local/non-exported child Views, not only module exports.
- Support `make`, `makeUntraced`, `withOptions`, `Memoized.memoized`, async traits, and `withRuntime` / `withContext` entrypoints.
- Work when one View is materialized under multiple Effect service contexts.
- Preserve Effect scopes on compatible edits and close them exactly once on a reset/remount.
- Offer an explicit reset escape hatch equivalent to a refresh-reset directive.
## Recommended design
### 1. Add an Effect View refresh transform
Ship a Vite plugin, `@effect-view/vite-plugin`, placed before `react()`:
```ts
plugins: [
effectViewPlugin(),
react(),
]
```
It should recognize:
- `Component.make(...)`
- `Component.makeUntraced(...)`
- class declarations extending either factory result
- definitions followed by Effect `pipe` transformations
- aliased imports from `effect-fc-next`
For each definition it should inject development-only metadata containing:
- A stable ID based on normalized module path plus local binding.
- A hook signature derived from the generator/body.
- The HMR context or a small generated accept handler.
- Optional reset metadata.
Detection must be binding-aware rather than matching text. Otherwise unrelated `Component.make` functions, renamed imports, and namespace aliases will cause false positives or missed Views.
The plugin must instrument local Views as well as exports. React Refresh works on component families, not only refresh-boundary exports, and most nested Views in this repository are consumed through `.use`.
### 2. Add a development-only hot cell protocol to Effect View
The main library should expose the bundler-neutral cell contract from its `Refreshable` module and the component shell should consume it directly:
```ts
interface HotViewCell {
current: Component.Any
revision: number
resetRevision: number
signature: string
subscribe(listener: () => void): () => void
}
```
On module reevaluation, the new descriptor updates `cell.current`. If the signature is unchanged, `revision` changes. If the signature changes, `resetRevision` changes as well.
Keeping the cell rather than only mutating the old descriptor is important for class inheritance and traits. Class-style Views inherit `body` and options through the generated base class, while memoized and async Views alter prototype behavior. A cell can point to the complete new descriptor without attempting to copy an unknown prototype graph onto the old one.
Bundler integrations should depend on this public protocol rather than define a structurally duplicated symbol and cell. The Vite adapter owns only Vite-specific storage in `import.meta.hot.data`, registration IDs, and accept/invalidate decisions.
### 3. Split the development component into a stable shell and keyed implementation
In development, the function materialized by `.use` should become a stable shell:
```text
stable shell
-> subscribes to HotViewCell
-> reads current descriptor and resetRevision
-> renders keyed implementation
-> runs useScope
-> runs the current Effect View body
-> owns the View's React hooks and Effect resources
```
On a compatible edit, the cell subscription rerenders the shell and the implementation keeps the same type/key, preserving state. On an incompatible edit, the key changes and React remounts the implementation safely.
This extra fiber and subscription should exist only in development builds. The production path can remain unchanged.
This design avoids depending on React Refresh's private family maps. It can coexist with the normal Vite React plugin, which remains responsible for standard React components and the error overlay. The Effect View plugin self-accepts only the modules it successfully instruments; unsupported patterns should fall back to normal HMR invalidation rather than accepting an update it cannot apply.
### 4. Reuse or reproduce hook signatures carefully
This is the hardest part of state-preserving support.
The current Vite/OXC transform already sees calls such as `React.useState`, `Component.useOnMount`, and `Subscribable.useAll`, but its computed signature is attached to the descriptor expression rather than the lazily created React function. There is no public runtime API for reading that signature back.
The robust choices are:
1. Run a small binding-aware AST pass that computes Effect View hook signatures and feeds them to the hot cell.
2. Integrate with a public transform hook if Vite/React exposes one in a future version.
Parsing generated OXC text to steal `_s(...)` arguments would be brittle and is not recommended.
An MVP may conservatively remount on every edit. The next step can preserve state only when the plugin can prove that the ordered hook signature is unchanged. False negatives cost state; false positives can violate the Rules of Hooks, so the algorithm must favor remounting.
The signature pass should cover:
- Direct React hooks.
- Effect View hooks named `useX` even when used through `yield*`.
- Imported custom hooks and their identities where possible.
- Hooks introduced by traits such as async rendering.
- An explicit force-reset directive.
### 5. Keep Effect lifecycle behavior explicit
Compatible refresh should retain existing `useOnMount` values and open scopes, just as React Fast Refresh retains hook state. Editing the acquisition code inside `useOnMount` should not silently rerun it unless the View resets.
On a reset, the existing `useScope` effect cleanup should close the old scope and its finalizers. Tests need to account for `finalizerExecutionDebounce` (100 ms by default), Strict Mode, and rapid consecutive edits. The implementation must not create a second close path in the HMR layer.
## Why smaller fixes are insufficient
| Option | Result | Assessment |
| --- | --- | --- |
| Teach Vite that `Component.make` is a component factory | Registers the descriptor, not the mounted synthesized function | Insufficient alone |
| Export every View or rename it to PascalCase | May improve boundary heuristics, but does not bridge the two identities | Insufficient |
| Wrap only route entrypoints with a normal React component | Can refresh the entry wrapper, but nested `.use` components still retain old implementations and state may remount | Partial workaround |
| Remove caching from `.use` | New type on every ordinary render; all child Views remount continuously | Incorrect |
| Mutate the old descriptor in a manual HMR handler | Demonstrably updates code and can preserve state, but lacks scheduling, hook safety, class/trait handling, and ergonomics | Useful prototype only |
| Register every synthesized function directly with React Refresh | Possible, but needs stable IDs per materialization, replacement creation for every Effect context, signature propagation, and private/runtime coupling | Viable but more coupled |
| Stable hot cell plus development shell | Explicitly bridges identities and controls preserve-versus-reset behavior | Recommended |
| Redesign Effect Views to be ordinary React component types | Makes React Refresh natural, but conflicts with context binding through `.use` and is a large API/architecture change | Not justified for this feature |
## Proposed delivery plan
### Phase 0: executable spike (24 days)
- Instrument one `const` View and one class View in the example app.
- Retain a hot cell in `import.meta.hot.data`.
- Refresh with a guaranteed remount.
- Verify edits through a nested `.use` View and a `withRuntime` / `withContext` route.
- Verify a finalizer runs exactly once on reset.
Exit criterion: editing render text updates without a page reload, and incompatible edits remount safely.
### Phase 1: Vite MVP (47 additional days)
- Implement binding-aware AST detection for all public construction styles.
- Add stable shell/keyed implementation support to the supported `effect-fc-next` Component implementation.
- Cover memoized and async traits.
- Add safe self-accept/fallback behavior.
- Add browser integration tests against the example app.
Exit criterion: all supported Effect View forms refresh reliably, initially with conservative remounting where signature information is unavailable.
### Phase 2: state preservation (47 additional days)
- Compute ordered hook signatures.
- Preserve local state for compatible edits.
- Reset for hook-order changes and the force-reset directive.
- Test custom hooks, multiple service contexts, syntax-error recovery, and rapid edits.
- Document expected `useOnMount` and scope behavior.
Exit criterion: the behavior matches React Fast Refresh closely enough that state preservation is predictable and hook-safe.
### Later: other bundlers
Because the main Effect View library owns the runtime metadata protocol, adapters for webpack/Rspack, Rolldown, or other environments can emit the same metadata without depending on Vite. Building those in parallel with the first Vite version would enlarge the test matrix before the semantics have settled.
## Test matrix
The feature should have real browser HMR tests; unit tests cannot fully validate React Refresh scheduling and module replacement.
Minimum cases:
- `const` and class View definitions.
- `make` and `makeUntraced`.
- Root entrypoint and nested `.use` child.
- A View imported through another module.
- Local, exported, default-exported, and renamed Views.
- Direct React state preserved after a render-only edit.
- State reset after adding/removing/reordering a hook.
- `useOnMount`, `useOnChange`, `useReactEffect`, and `useReactLayoutEffect` cleanup.
- Default and zero finalizer debounce.
- Memoized View with unchanged props.
- Async View and Suspense/error recovery.
- Two materializations of the same View under different Effect contexts.
- Reactive and `nonReactiveTags` service changes.
- TanStack Router code splitting used by the `example-next` application.
- Successive edits before the previous refresh finishes.
- Syntax error followed by recovery.
- Production build contains no HMR registry/subscription code.
## Risks and open questions
### Hook signature ownership
The plugin must decide which `useX` calls represent React hook state. Effect View intentionally makes React hooks appear inside generator bodies, so relying only on standard React source patterns will remain incomplete.
### Trait composition
`Memoized.memoized`, async behavior, `withOptions`, and future traits can replace `transformFunctionComponent` or alter prototypes. The hot cell should point to the newest complete descriptor, and the development shell must define whether a trait change is compatible or forces reset.
### Development tree shape
A stable shell plus keyed implementation adds one fiber in development. This is a reasonable tradeoff, but React DevTools naming should make the extra layer understandable.
### React/Vite version coupling
The current plugin stack uses Vite's OXC refresh transform and a bundled/simplified React Refresh runtime. Depending on private runtime functions or generated transform text would make the feature sensitive to Vite upgrades. The main Effect View package should therefore own the standalone metadata protocol, while the Vite plugin depends on and adapts it.
### Multiple materializations
One View definition can produce more than one function identity because `.use` is evaluated under different Effect service sets and parent instances. A solution based on direct React Refresh registration must track every materialization. The hot-cell subscription model naturally fans one update out to all mounted materializations.
### Resource expectations
Preserving state also preserves acquired resources. Developers will need a reset directive or a documented way to force a remount when they edit acquisition logic and want it rerun immediately.
## Recommendation
Proceed with a Vite-first proof of concept using a stable hot cell and a development-only stable shell/keyed implementation.
Do not begin by patching component-name heuristics or by registering the Effect View descriptor with React Refresh; those changes target the wrong identity. Also avoid coupling the initial implementation to private React Refresh family maps.
The first milestone should always remount safely. Once browser tests prove update delivery and Effect scope cleanup, add signature-aware state preservation. This order isolates the HMR transport/identity problem from the hook-compatibility problem and gives the project a useful, releasable intermediate result.
+1 -1
View File
@@ -1,6 +1,6 @@
# Effect FC Monorepo
[Effect-TS](https://effect.website/) integration for React 19+ that allows you to write function components using Effect generators.
[Effect-TS](https://effect.website/) integration for React 19.2+ that allows you to write function components using Effect generators.
This monorepo contains:
- [The `effect-fc` library](packages/effect-fc)
+3088 -256
View File
File diff suppressed because it is too large Load Diff
+9 -8
View File
@@ -1,26 +1,27 @@
{
"name": "@effect-fc/monorepo",
"packageManager": "bun@1.3.6",
"packageManager": "bun@1.3.14",
"private": true,
"workspaces": [
"./packages/*"
],
"scripts": {
"build": "turbo build",
"lint:tsc": "turbo lint:tsc",
"lint:biome": "turbo lint:biome",
"test": "turbo test",
"build": "turbo build",
"pack": "turbo pack",
"clean:cache": "turbo clean:cache",
"clean:dist": "turbo clean:dist",
"clean:modules": "turbo clean:modules && rm -rf node_modules"
},
"devDependencies": {
"@biomejs/biome": "^2.3.11",
"@effect/language-service": "^0.72.0",
"@types/bun": "^1.3.6",
"npm-check-updates": "^19.3.1",
"@biomejs/biome": "^2.4.16",
"@effect/language-service": "^0.86.2",
"@types/bun": "^1.3.14",
"npm-check-updates": "^22.2.1",
"npm-sort": "^0.0.4",
"turbo": "^2.7.5",
"typescript": "^5.9.3"
"turbo": "^2.9.16",
"typescript": "^6.0.3"
}
}
+20
View File
@@ -0,0 +1,20 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+17
View File
@@ -0,0 +1,17 @@
# effect-fc Docs
The documentation site is built with Docusaurus.
## Local Development
```bash
bun run --cwd packages/docs start
```
## Build
```bash
bun run --cwd packages/docs build
```
The static site is written to `packages/docs/build`.
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://biomejs.dev/schemas/latest/schema.json",
"root": false,
"extends": "//",
"files": {
"includes": ["./src/**"]
}
}
+457
View File
@@ -0,0 +1,457 @@
---
sidebar_position: 5
title: Forms
---
# Forms
Effect View forms are built from an Effect `Schema`. The schema is the source of
truth for the shape of the form, its validation rules, and the value your
application receives. The form layer supplies reactive state and lifecycle; it
does not replace your UI components.
A schema distinguishes the **encoded value** edited by the UI from the
**decoded value** used by the application. For example, an `<input>` edits an
age as a string, while the submit handler or application state receives a
number:
```tsx
import { Schema } from "effect"
const ProfileSchema = Schema.Struct({
displayName: Schema.String.check(
Schema.isMinLength(1, { message: "Enter a display name" }),
),
age: Schema.NumberFromString,
contact: Schema.Struct({
email: Schema.String.check(
Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, {
message: "Enter a valid email address",
}),
),
}),
})
```
That schema gives the form several useful properties:
- Validation stays next to the data definition instead of being duplicated in
components and submit handlers.
- Inputs can keep UI-friendly encoded values while business logic receives
decoded, typed values.
- Nested schema issue paths can be routed automatically to the matching
subform or field.
- Synchronous and effectful schema validation use the same form model.
- The same schema can validate a local draft or protect writes to shared state.
There are two concrete root form implementations. Choose one based on where a
valid decoded value should go:
| Implementation | Owns a local draft | What happens to a valid value |
| --- | --- | --- |
| `MutationForm` | Yes | It is passed to a mutation when `submit` runs. |
| `LensForm` | Yes | It is written automatically to a target `Lens`. |
## MutationForm: validate, then submit
Use `MutationForm` for registration, checkout, search, and other workflows with
an explicit submit action. It owns the encoded draft, continuously decodes it
with the schema, and exposes the last valid decoded value. Calling `submit`
runs the mutation only when the form can commit.
```tsx
import { Effect } from "effect"
import { Component, MutationForm, View } from "effect-view"
const CreateProfileView = Component.make("CreateProfile")(function* () {
const form = yield* Component.useOnMount(() =>
MutationForm.service({
schema: ProfileSchema,
initialEncodedValue: {
displayName: "",
age: "",
contact: { email: "" },
},
f: ([profile]) =>
Effect.log(
`Creating ${profile.displayName}, age ${profile.age}`,
),
}),
)
const [canCommit, isCommitting] = yield* View.useAll([
form.canCommit,
form.isCommitting,
])
const runPromise = yield* Component.useRunPromise()
// Focused inputs are added in "Focus into subforms" below.
return (
<button
disabled={!canCommit || isCommitting}
onClick={() => void runPromise(form.submit)}
>
{isCommitting ? "Creating..." : "Create profile"}
</button>
)
})
```
Notice that `age` starts as a string because it is an encoded input value. The
mutation receives the schema's decoded profile, so `profile.age` is a number.
Schema transformations happen before the mutation and schema issues prevent an
invalid draft from being submitted.
`MutationForm.service` also starts initial validation in the current scope. Use
it inside `Component.useOnMount`, a scoped service, or another Effect scope so
its validation and mutation work is cleaned up with its owner.
## LensForm: validate, then synchronize
Use `LensForm` for settings panels, inspectors, and edit screens where valid
changes should update existing state without a final submit. Its target holds
decoded application data; the form derives an encoded draft from that target
and keeps the two synchronized in both directions.
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, LensForm, View } from "effect-view"
const EditProfileView = Component.make("EditProfile")(function* () {
const [form, profile] = yield* Component.useOnMount(() =>
Effect.gen(function* () {
const profile = Lens.fromSubscriptionRef(
yield* SubscriptionRef.make({
displayName: "Ada",
age: 37,
contact: { email: "ada@example.com" },
}),
)
const form = yield* LensForm.service({
schema: ProfileSchema,
target: profile,
})
return [form, profile] as const
}),
)
const [savedProfile, isCommitting] = yield* View.useAll([
profile,
form.isCommitting,
])
// Focused inputs are added in "Focus into subforms" below.
return (
<output>
{isCommitting
? "Saving..."
: `${savedProfile.displayName} is ${savedProfile.age}`}
</output>
)
})
```
Here the target contains `age: 37`, while the form exposes the encoded value
`age: "37"` to an input. A valid edit is decoded and written to `profile`.
Invalid input remains in the form so the user can correct it, but it never
reaches the target. If another part of the application updates the target,
`LensForm` encodes that value back into the draft.
Pass `initialEncodedValue` only when the first draft should differ from the
encoded target. Otherwise `LensForm.service` obtains the initial draft by
encoding the target through the schema.
## Example: local date input, UTC domain value
The encoded/decoded distinction is especially useful for dates. An HTML
`datetime-local` input produces a wall-clock string such as
`"2026-07-22T14:30"`. It contains no time-zone or UTC offset, while application
state and APIs usually need an unambiguous UTC instant.
A schema can own that entire conversion. The following schema interprets the
input in the current time zone and decodes it to `DateTime.Utc`:
```tsx title="src/DateTimeUtcFromZonedInput.ts"
import { DateTime, Effect, Option, ParseResult, Schema } from "effect"
class DateTimeUtcFromZoned extends Schema.transformOrFail(
Schema.DateTimeZonedFromSelf,
Schema.DateTimeUtcFromSelf,
{
strict: true,
decode: (input) => ParseResult.succeed(DateTime.toUtc(input)),
encode: DateTime.setZoneCurrent,
},
) {}
export class DateTimeUtcFromZonedInput extends Schema.transformOrFail(
Schema.String,
DateTimeUtcFromZoned,
{
strict: true,
decode: (input, _options, ast) =>
Effect.flatMap(DateTime.CurrentTimeZone, (timeZone) =>
Option.match(
DateTime.makeZoned(input, {
timeZone,
adjustForTimeZone: true,
}),
{
onSome: ParseResult.succeed,
onNone: () =>
ParseResult.fail(
new ParseResult.Type(
ast,
input,
"Enter a valid date and time",
),
),
},
),
),
encode: (value) =>
ParseResult.succeed(
DateTime.formatIsoZoned(value).slice(0, 16),
),
},
) {}
```
Use it like any other field schema. The form and input work with a string, but
the mutation receives UTC:
```tsx
import { DateTime, Effect, Schema } from "effect"
import { Component, Form, MutationForm, View } from "effect-view"
import { DateTimeUtcFromZonedInput } from "./DateTimeUtcFromZonedInput"
const AppointmentSchema = Schema.Struct({
startsAt: DateTimeUtcFromZonedInput,
})
const AppointmentView = Component.make("Appointment")(function* () {
const [form, startsAtField] = yield* Component.useOnMount(() =>
Effect.gen(function* () {
const form = yield* MutationForm.service({
schema: AppointmentSchema,
initialEncodedValue: { startsAt: "" },
f: ([appointment]) =>
Effect.log(
`Saving ${DateTime.formatIso(appointment.startsAt)}`,
),
})
return [form, Form.focusObjectOn(form, "startsAt")] as const
}),
)
const startsAt = yield* Form.useInput(startsAtField)
const [canCommit] = yield* View.useAll([form.canCommit])
const runPromise = yield* Component.useRunPromise()
return (
<form
onSubmit={(event) => {
event.preventDefault()
void runPromise(form.submit)
}}
>
<input
type="datetime-local"
value={startsAt.value}
onChange={(event) =>
startsAt.setValue(event.currentTarget.value)
}
/>
<button disabled={!canCommit}>Save appointment</button>
</form>
)
})
```
The schema requires `DateTime.CurrentTimeZone`; provide
`DateTime.layerCurrentZoneLocal` in the application runtime. If the current
zone is `Europe/Paris`, for example, entering `2026-07-22T14:30` decodes to the
UTC instant `2026-07-22T12:30:00.000Z`.
Encoding works in the other direction. A `LensForm` whose target contains that
UTC instant presents `2026-07-22T14:30` to the local input. The component never
manually parses dates, applies offsets, or maintains a second representation;
the schema defines both directions and the form keeps them synchronized.
## Focus into subforms
The root `MutationForm` or `LensForm` represents the complete schema. UI
components usually need a smaller form representing one field, so they do not
have to receive or understand the entire root form. **Focusing** creates that
smaller form.
Every root form and every focused subform implements the same `Form.Form`
interface. There is no separate field abstraction: an individual field is
simply a `Form` focused on that part of its parent.
```tsx
const displayNameField = Form.focusObjectOn(form, "displayName")
const ageField = Form.focusObjectOn(form, "age")
const contactForm = Form.focusObjectOn(form, "contact")
const emailField = Form.focusObjectOn(contactForm, "email")
```
`displayNameField`, `ageField`, and `emailField` can each be passed to the input
component responsible for that field. Focusing can also be repeated:
`contactForm` represents the complete contact section, and `emailField`
represents its email field.
A focused form exposes only the relevant:
- `encodedValue`: the UI-facing value that can be edited.
- `value`: the decoded value as an `Option`.
- `issues`: the schema issues for that subform.
Validation and commit state remain connected to the root form. An input can
show its own issues while still observing the root form's `isValidating`,
`canCommit`, and `isCommitting` state.
Use the focusing helper that matches the value being represented:
```tsx
const property = Form.focusObjectOn(form, "contact")
const item = Form.focusArrayAt(itemsForm, 0)
const tupleMember = Form.focusTupleAt(tupleForm, 1)
const chunkItem = Form.focusChunkAt(chunkForm, 0)
```
Schema issue paths are focused at the same time. A component receiving
`emailField` gets its email issues directly instead of searching through every
issue on the root form.
## Bind a subform to an input
`Form.useInput` is the liaison between an Effect form and a React controlled
component. It reads the subform's encoded value and returns the familiar React
`{ value, setValue }` interface. Calling `setValue` updates the form, which in
turn runs the schema pipeline and updates validation state.
```tsx
const input = yield* Form.useInput(emailField, {
debounce: "250 millis",
})
return (
<input
value={input.value}
onChange={(event) => input.setValue(event.currentTarget.value)}
/>
)
```
The debounce is useful for text inputs, which can otherwise update the form and
run schema validation on every keystroke. The displayed value still updates
immediately; propagation to the form waits until the user pauses typing.
Use `Form.useOptionalInput` when the encoded field is an Effect `Option`. It
returns `value` and `setValue` together with `enabled` and `setEnabled`, making
it suitable for an optional input that the user can toggle on and off.
`useInput` and `useOptionalInput` can be used directly, but they are primarily
building blocks for your own reusable input components. A component library
can wrap them to consistently handle labels, validation issues, validating
indicators, disabled state, accessibility, styling, and a standard debounce.
Because both hooks accept a `Form.Form`, the same input components work with
subforms from both `MutationForm` and `LensForm`.
```tsx title="TextFieldFormInputView.tsx"
import { Callout, Flex, Spinner, TextField } from "@radix-ui/themes"
import { Array, Option, Struct } from "effect"
import { Component, Form, View } from "effect-view"
import type * as React from "react"
export declare namespace TextFieldFormInputView {
export interface Props<
out P extends readonly PropertyKey[],
A,
ER,
EW,
> extends Omit<TextField.RootProps, "form">,
Form.useInput.Options {
readonly form: Form.Form<P, A, string, ER, EW>
}
export type Signature = <
P extends readonly PropertyKey[],
A,
ER,
EW,
>(
props: Props<P, A, ER, EW>,
) => React.ReactNode
}
export const TextFieldFormInputView = Component.make(
"TextFieldFormInputView",
)(function* (
props: TextFieldFormInputView.Props<
readonly PropertyKey[],
any,
any,
any
>,
) {
const input = yield* Form.useInput(props.form, props)
const [issues, isValidating, isCommitting] = yield* View.useAll([
props.form.issues,
props.form.isValidating,
props.form.isCommitting,
])
return (
<Flex direction="column" gap="1">
<TextField.Root
value={input.value}
onChange={(event) => input.setValue(event.target.value)}
disabled={isCommitting}
{...Struct.omit(props, ["form", "debounce"])}
>
{isValidating && (
<TextField.Slot side="right">
<Spinner />
</TextField.Slot>
)}
{props.children}
</TextField.Root>
{Option.match(Array.head(issues), {
onSome: (issue) => (
<Callout.Root>
<Callout.Text>{issue.message}</Callout.Text>
</Callout.Root>
),
onNone: () => null,
})}
</Flex>
)
}).pipe(
Component.withSignature<TextFieldFormInputView.Signature>(),
)
```
## The common Form model
Both root implementations and every focused subform implement `Form.Form`.
They expose the schema pipeline as reactive Lenses and Views:
| Member | Meaning |
| --- | --- |
| `encodedValue` | Writable input-shaped state. |
| `value` | The decoded value as an `Option`; `None` until decoding succeeds. |
| `issues` | Standard Schema issues scoped to this form's path. |
| `isValidating` | Whether schema decoding is currently running. |
| `canCommit` | Whether the root has a valid value and is ready to commit. |
| `isCommitting` | Whether a mutation or target write is in progress. |
The form model itself is Effect code. Effect View adds the React-facing hooks,
including `Form.useInput` and `Form.useOptionalInput`, while your own component
library remains responsible for rendering controls and layout.
+514
View File
@@ -0,0 +1,514 @@
---
sidebar_position: 1
title: Getting Started
---
# Getting Started
`effect-view` lets a React function component be described as an Effect
program. Inside a component you can yield services, create scoped resources,
subscribe to Effect-powered state, and turn Effects into React callbacks. At a
React boundary, that description becomes a normal function component.
The core model has four pieces:
1. `ReactRuntime` builds the Effect services available to the UI.
2. `Component.make` defines an Effect View component.
3. `Component.withContext` converts an Effect View component into a normal
React component at an application or router boundary.
4. Effect View children are composed through their `.use` Effect.
## Install
For a web application, install Effect View with Effect 4 and React 19.2 or
newer:
```bash npm2yarn
npm install effect-view effect@beta react react-dom
```
```bash npm2yarn
npm install --save-dev @types/react @types/react-dom
```
Effect View is not tied to React DOM. For React Native or another renderer,
install that renderer instead of `react-dom` and keep the rest of the setup the
same.
## Create the runtime
`ReactRuntime` owns a managed Effect runtime. Define it at module scope from the
layers needed by the UI:
```tsx title="src/runtime.ts"
import { Layer } from "effect"
import { FetchHttpClient } from "effect/unstable/http"
import { ReactRuntime } from "effect-view"
const AppLive = Layer.empty.pipe(
Layer.provideMerge(FetchHttpClient.layer),
)
export const runtime = ReactRuntime.make(AppLive)
```
Keep the runtime stable. Creating it during a React render would create new
managed resources and a new React context on every render.
## Provide the runtime
Place `ReactRuntime.Provider` above every Effect View entrypoint. The provider
builds the runtime layer, makes its Effect context available through React, and
disposes the managed runtime when the provider unmounts.
Runtime construction can suspend, so give the provider a fallback:
```tsx title="src/main.tsx"
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { ReactRuntime } from "effect-view"
import { App } from "./App"
import { runtime } from "./runtime"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ReactRuntime.Provider
runtime={runtime}
fallback={<p>Starting application...</p>}
>
<App />
</ReactRuntime.Provider>
</StrictMode>,
)
```
With a router, keep the provider above the router provider:
```tsx
<ReactRuntime.Provider runtime={runtime} fallback={<p>Starting...</p>}>
<RouterProvider router={router} />
</ReactRuntime.Provider>
```
If runtime layer construction can fail, place an appropriate React error
boundary above `ReactRuntime.Provider` as well.
## Write your first component
`Component.make` defines a component body using the same generator style as
`Effect.gen` and `Effect.fn`. Providing a name creates a tracing span and also
sets the React DevTools display name:
```tsx title="src/HelloView.tsx"
import { Effect } from "effect"
import { Component } from "effect-view"
export const HelloView = Component.make("HelloView")(
function* (props: { readonly name: string }) {
const message = yield* Effect.succeed(`Hello, ${props.name}`)
return <h1>{message}</h1>
},
)
```
Use `Component.makeUntraced("HelloView")` when you want the display name but do
not want an automatic tracing span.
`HelloView` is an Effect View component description, not yet a normal React
component. Convert it at the point where plain React, a router, or a third-party
library needs a function component:
```tsx title="src/Hello.tsx"
import { Component } from "effect-view"
import { HelloView } from "./HelloView"
import { runtime } from "./runtime"
export const Hello = HelloView.pipe(
Component.withContext(runtime.context),
)
```
It can now be rendered by ordinary React:
```tsx title="src/App.tsx"
import { Hello } from "./Hello"
export function App() {
return <Hello name="Effect" />
}
```
`Component.withContext` reads the context populated by the matching
`ReactRuntime.Provider`. It does not build or provide the runtime by itself.
## Compose Effect View components
Inside another Effect View component, yield a child's `.use` Effect. This binds
the child to the current Effect context and returns a component that can be used
in JSX:
```tsx title="src/GreetingCardView.tsx"
import { Component } from "effect-view"
import { HelloView } from "./HelloView"
export const GreetingCardView = Component.make("GreetingCard")(
function* () {
const Hello = yield* HelloView.use
return (
<section>
<Hello name="Effect" />
<p>Both components use the same Effect context.</p>
</section>
)
},
)
```
Only apply `Component.withContext` when crossing from Effect View into plain
React. Applying it to every nested component is unnecessary and makes it harder
to provide local services to a subtree.
## Synchronous and asynchronous components
A regular Effect View component runs its body during React render. That Effect
must complete synchronously: yielding a service, reading synchronous state, or
creating a scoped object is fine; sleeping, fetching, or awaiting a promise is
not.
Use `Async.async` when render genuinely depends on an asynchronous Effect. The
component then suspends and accepts React Suspense props such as `fallback`:
```tsx title="src/UserView.tsx"
import { Async, Component, Memoized } from "effect-view"
import { loadUser } from "./api"
export const UserView = Component.make("UserView")(
function* (props: { readonly userId: string }) {
const user = yield* Component.useOnChange(
() => loadUser(props.userId),
[props.userId],
)
return <h2>{user.name}</h2>
},
).pipe(
Async.async,
Async.withOptions({ defaultFallback: <p>Loading user...</p> }),
Memoized.memoized,
)
```
Use it from an Effect View parent in the usual way:
```tsx
const User = yield* UserView.use
return <User userId={selectedUserId} />
```
`Memoized.memoized` prevents an unrelated parent re-render from restarting an
async child whose props have not changed. A changed `userId` creates a new
dependency scope, cleans up the previous one, and runs `loadUser` again.
An async component's rejected Effect is handled by the nearest React error
boundary. Suspense handles waiting, not failures.
For server data that should be cached, refreshed, and shared, prefer the
[Query module](./query) over a raw async component.
## Use Effect services
Components can yield Effect service tags directly. Their required service type
becomes part of the component type, so the final runtime or a local layer must
provide it:
```tsx title="src/GreetingService.ts"
import { Context, Layer } from "effect"
export class GreetingService extends Context.Service<
GreetingService,
{ readonly greet: (name: string) => string }
>()("GreetingService") {
static readonly layer = Layer.succeed(GreetingService, {
greet: (name) => `Hello, ${name}`,
})
}
```
```tsx title="src/GreetingView.tsx"
import { Component } from "effect-view"
import { GreetingService } from "./GreetingService"
export const GreetingView = Component.make("Greeting")(
function* (props: { readonly name: string }) {
const greeting = yield* GreetingService
return <p>{greeting.greet(props.name)}</p>
},
)
```
Add `GreetingService.layer` to the application runtime, or provide it only to a
subtree as shown later on this page.
Effect service instances are reactive at component boundaries. If the supplied
context changes to contain a different service instance, dependent Effect View
components are recreated so they read the new environment and restart their
scoped lifecycle.
## Understand lifecycle hooks
Effect View hooks are still React hooks internally. Call them unconditionally
at the top level of the component body, in a consistent order, and never inside
branches, loops, event handlers, or nested callbacks.
### The component root scope
Every rendered Effect View component gets a root `Scope.Scope`. Effect View
creates it when the component instance is rendered, provides it to the entire
component body, and closes it when that React component unmounts.
Effects yielded directly from the body therefore see the root scope. This also
means that `Effect.addFinalizer`, `Effect.acquireRelease`, and
`Effect.forkScoped` can be used naturally inside component setup:
```tsx
import { Effect } from "effect"
import { Component } from "effect-view"
const ResourceView = Component.make("Resource")(function* () {
const resource = yield* Component.useOnMount(() =>
Effect.acquireRelease(
openResource,
(resource) => closeResource(resource),
),
)
return <p>{resource.name}</p>
})
```
`useOnMount` does **not** create or provide another scope. It runs its Effect
with the context already available in the component body, so the resource above
is owned by the component's root scope.
`useOnChange`, `useReactEffect`, and `useReactLayoutEffect` each create a scope
that can be replaced without closing the component root scope.
The main lifecycle choices are:
| Hook | What it does | Scope seen by setup | Scope closes when |
| --- | --- | --- | --- |
| Component body | Produces the component's rendered value | Component root scope | The component unmounts |
| `useOnMount` | Computes and caches a value for the component instance | The same component root scope | The component unmounts |
| `useOnChange` | Recomputes a cached value when dependencies change | A new dependency scope | Dependencies change or the component unmounts |
| `useReactEffect` | Runs a post-commit side effect | A new effect scope | Dependencies change or the component unmounts |
| `useReactLayoutEffect` | Runs a layout effect before the browser paints | A new layout-effect scope | Dependencies change or the component unmounts |
| `useLayer` | Builds and provides a layer context | A dependency scope created through `useOnChange` | The layer reference changes or the component unmounts |
`useRunSync`, `useRunPromise`, `useCallbackSync`, and `useCallbackPromise` do
not create lifecycle scopes either. They capture the component context, so an
Effect invoked through them sees the component root scope unless it explicitly
provides another one.
### useOnMount
`Component.useOnMount` computes a value during the initial render and caches it
for later renders. It uses the component root scope, so its resources live
until the component unmounts.
```tsx title="src/LocalStateView.tsx"
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, View } from "effect-view"
export const LocalStateView = Component.make("LocalState")(
function* () {
const count = yield* Component.useOnMount(() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.log("LocalState disposed"),
)
return Lens.fromSubscriptionRef(
yield* SubscriptionRef.make(0),
)
}),
)
const [value] = yield* View.useAll([count])
return <p>Count: {value}</p>
},
)
```
In a regular component, the setup Effect must be synchronous because it runs
during render. In a component enhanced with `Async.async`, it may be
asynchronous and will suspend the component.
### useOnChange
`Component.useOnChange` computes and caches a value, then recomputes it when its
dependencies change. Each dependency set gets its own scope, which closes when
the dependencies change or the component unmounts.
```tsx
const label = yield* Component.useOnChange(
() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.log(`Stopped viewing ${props.userId}`),
)
return `Viewing user ${props.userId}`
}),
[props.userId],
)
```
Dependency arrays follow normal React semantics. Include every reactive value
read by the setup Effect.
### useReactEffect and useReactLayoutEffect
`Component.useReactEffect` runs side effects after React commits, while
`Component.useReactLayoutEffect` runs before the browser paints. Each hook owns
a scope that closes when its dependencies change or the component unmounts.
Setup must complete synchronously, but it can fork asynchronous work into the
hook scope:
```tsx
yield* Component.useReactEffect(
() => Effect.forkScoped(listenForNotifications(props.userId)),
[props.userId],
)
```
React Strict Mode may intentionally repeat development-only render and effect
setup. Initializers and resource acquisition should therefore be safe to run
more than once; production retains the normal component lifetime semantics.
## Run Effects from event handlers
React event handlers are plain functions. Use Effect View runners to execute an
Effect with the component's current context and scope:
```tsx
const runPromise = yield* Component.useRunPromise()
return (
<button onClick={() => void runPromise(saveUser(user))}>
Save
</button>
)
```
Use `Component.useRunSync` only for Effects known to complete synchronously.
Use `Component.useRunPromise` for Effects that may suspend, sleep, fetch, or
otherwise continue asynchronously.
When a callback is passed to a memoized child or used as a dependency, use the
callback variants to preserve its identity:
```tsx
const save = yield* Component.useCallbackPromise(
(nextUser: User) => saveUser(nextUser),
[saveUser],
)
return <SaveButton onSave={() => void save(user)} />
```
`useCallbackSync` and `useCallbackPromise` follow the same dependency rules as
`React.useCallback`, while also supplying the Effect context when invoked.
## Use React normally
Effect View components can use regular React hooks, refs, context, event
handlers, and JSX composition:
```tsx
import { Component } from "effect-view"
import * as React from "react"
const CounterView = Component.make("Counter")(function* () {
const [count, setCount] = React.useState(0)
const buttonRef = React.useRef<HTMLButtonElement>(null)
return (
<button
ref={buttonRef}
onClick={() => setCount((count) => count + 1)}
>
Count: {count}
</button>
)
})
```
Prefer regular React state for simple, component-local UI concerns. Use
`Lens`/`View` when state needs Effect integration, subscriptions, focusing, or
sharing. The [State Management guide](./state-management) covers that model.
## Provide services to a subtree
Use `Component.useLayer` when only one Effect View subtree needs extra
services. It builds the layer in a scope and returns the resulting Effect
context:
```tsx title="src/GreetingPageView.tsx"
import { Effect } from "effect"
import { Component } from "effect-view"
import { GreetingView } from "./GreetingView"
import { GreetingService } from "./GreetingService"
export const GreetingPageView = Component.make("GreetingPage")(
function* () {
const context = yield* Component.useLayer(GreetingService.layer)
const Greeting = yield* GreetingView.use.pipe(
Effect.provide(context),
)
return <Greeting name="Effect" />
},
)
```
Keep the layer reference stable. Define static layers outside the component or
memoize a layer that depends on props with `React.useMemo`; a new layer object
causes reconstruction and scoped cleanup.
Layer construction runs during render through `useOnChange`. A layer with
asynchronous acquisition requires the component to be enhanced with
`Async.async`. Resources built by the layer are released when the owning
component unmounts or the layer reference changes.
## Common pitfalls
- Effect View hooks obey React's Rules of Hooks even though they are called
with `yield*`.
- Do not yield an asynchronous Effect from a regular component body. Use
`Async.async`, Query, a Mutation callback, or a post-commit scoped fiber.
- `Component.withContext` needs a matching `ReactRuntime.Provider` above it.
- Apply `withContext` at React boundaries, not between Effect View components.
- Keep runtimes and layers stable instead of creating them on every render.
- Use `useRunPromise` rather than `useRunSync` for asynchronous event work.
- Suspense fallbacks handle waiting; React error boundaries handle failed
component Effects.
## Where to go next
- [State Management](./state-management) explains `Lens`, `View`, local state,
and focused state.
- [Query](./query) adds reactive keys, caching, refresh, and invalidation to
Effect-based server reads.
- [Mutation](./mutation) models user-triggered Effect operations and their
`AsyncResult` state.
- [Forms](./forms) builds schema-driven editable state with `MutationForm` and
`LensForm`.
The repeatable pattern is small: provide one runtime, define components as
Effect programs, cross into plain React with `Component.withContext`, and use
`.use` everywhere inside the Effect View tree.
+270
View File
@@ -0,0 +1,270 @@
---
sidebar_position: 4
title: Mutation
---
# Mutation
The Mutation module is Effect View's counterpart to TanStack Query mutations.
It models user-triggered asynchronous work such as saving a profile, deleting a
record, uploading a file, or sending a command to an API.
The familiar concepts are present, but the operation itself is an Effect:
| TanStack Mutation concept | Effect View equivalent |
| --- | --- |
| Mutation variables | The input key `K` |
| `mutationFn` | `f: (key: K) => Effect<A, E, R>` |
| Mutation result | `mutation.state`, a `View<AsyncResult<A, E>>` |
| `isPending` | `result.waiting` |
| `mutateAsync` | `mutation.mutate(key)` |
| Start without awaiting | `mutation.mutateView(key)` |
Unlike a Query, a Mutation has no cache, reactive key, or automatic execution.
It runs only when `mutate` or `mutateView` is called. This makes it suitable for
commands, while Query remains the model for cached server state.
## Create a mutation
Create a mutation in a component scope with `Mutation.make`. Its function can
be any Effect, including one that requires services from the application
runtime:
```tsx
import { Effect } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import { Component, Mutation, View } from "effect-view"
import { sendInvite } from "./api"
interface InviteInput {
readonly email: string
readonly role: "member" | "admin"
}
const InviteButtonView = Component.make("InviteButton")(
function* (props: { readonly email: string }) {
const mutation = yield* Component.useOnMount(() =>
Mutation.make({
f: (input: InviteInput) => sendInvite(input),
}),
)
const [result] = yield* View.useAll([mutation.state])
const runSync = yield* Component.useRunSync()
return (
<section>
<button
disabled={result.waiting}
onClick={() =>
runSync(mutation.mutateView({
email: props.email,
role: "member",
}))
}
>
{result.waiting ? "Sending..." : "Send invite"}
</button>
{AsyncResult.match(result, {
onInitial: () => null,
onFailure: ({ cause }) => (
<p>Could not send invite: {cause.toString()}</p>
),
onSuccess: ({ value }) => (
<p>Invite sent to {value.email}</p>
),
})}
</section>
)
},
)
```
`Mutation.make` captures the current Effect context. If `sendInvite` requires
an HTTP client, authentication service, tracer, or another service, provide it
to the runtime or component layer before creating the mutation. The click
handler does not need to reconstruct those dependencies.
The mutation also belongs to the creation scope. Any mutation fibers still
running when that scope closes are interrupted automatically.
## Understand AsyncResult
`mutation.state` starts as `Initial` with `waiting: false`. Starting a mutation
changes it to a waiting state, then publishes either `Success` or `Failure`:
```tsx
const [result] = yield* View.useAll([mutation.state])
return AsyncResult.match(result, {
onInitial: ({ waiting }) =>
waiting ? <p>Starting...</p> : <p>Ready.</p>,
onFailure: ({ cause, previousSuccess, waiting }) => (
<div>
<p>{cause.toString()}</p>
{previousSuccess._tag === "Some" && (
<p>Last saved value: {previousSuccess.value.value.name}</p>
)}
{waiting && <p>Trying again...</p>}
</div>
),
onSuccess: ({ value, waiting }) => (
<div>
<p>Saved {value.name}</p>
{waiting && <p>Saving a newer value...</p>}
</div>
),
})
```
The `waiting` flag is independent from the result tag. After one successful
call, starting another keeps the successful value and sets `waiting: true`.
If that next call fails, the failure can retain the earlier success in
`previousSuccess`. Components can therefore keep useful feedback visible
during retries or repeated submissions.
A failure contains an Effect `Cause<E>`, not only `E`. Typed failures, defects,
and interruption information remain available for logging or presentation.
## Choose mutate or mutateView
Both methods start the same mutation effect. They differ in what the caller
waits for:
| Method | Return value | Best suited to |
| --- | --- | --- |
| `mutate(key)` | The final `Success` or `Failure` | Effect workflows that need the outcome. |
| `mutateView(key)` | A live `View<AsyncResult<A, E>>` | UI callbacks that should return after starting the work. |
Use `mutate` with an asynchronous component runner when later logic depends on
the final result:
```tsx
const runPromise = yield* Component.useRunPromise()
const save = () =>
void runPromise(
Effect.gen(function* () {
const result = yield* mutation.mutate(input)
if (AsyncResult.isSuccess(result)) {
yield* Effect.log(`Saved record ${result.value.id}`)
}
}),
)
```
The mutation Effect does not fail with `E`. It captures the operation's `Exit`
and returns a final `AsyncResult.Success` or `AsyncResult.Failure`. Inspect or
match that value when control flow depends on the outcome.
Use `mutateView` when the UI only needs to start the operation and react to its
state:
```tsx
const runSync = yield* Component.useRunSync()
const startSave = () => {
const state = runSync(mutation.mutateView(input))
// `state` is a View for this specific call.
}
```
`mutateView` starts the scoped work and returns immediately with a per-call
View. The shared `mutation.state` is also updated as that call progresses.
## Track the latest call
In addition to `state`, a mutation exposes reactive metadata:
| Member | Meaning |
| --- | --- |
| `state` | The latest mutation state published to the shared View. |
| `latestKey` | The most recently supplied input as an `Option<K>`. |
| `latestFinalResult` | The latest completed success or failure as an `Option`. |
| `fiber` | The most recently started mutation fiber as an `Option`. |
Subscribe to any of them with `View.useAll`:
```tsx
const [result, latestInput, latestFinal] = yield* View.useAll([
mutation.state,
mutation.latestKey,
mutation.latestFinalResult,
])
```
The input is called a `key` in the generic API, but it is equivalent to
mutation variables in TanStack Query. It can be a primitive, tuple, struct, or
any other value accepted by the mutation function.
## Concurrent mutations
Starting a mutation does not automatically interrupt an earlier mutation.
Calls may overlap, and each call has its own state View. This is useful for
independent operations such as uploading several files.
When calls overlap, `mutation.state` reflects updates published by all calls;
the last update to arrive wins. Use the View returned by `mutateView` when each
concurrent operation needs its own progress indicator:
```tsx
const upload = (file: File) =>
Effect.gen(function* () {
const uploadState = yield* mutation.mutateView(file)
// Store or pass `uploadState` to the row rendering this file.
return uploadState
})
```
For a single submit button, disabling it while `mutation.state.waiting` is
usually enough to prevent accidental overlap. For “latest request wins”
behavior, model that policy explicitly or use Query when the operation is
actually a reactive read.
## Update queries after a mutation
Mutations do not invalidate Query caches automatically. Compose invalidation
with the mutation result so the relationship remains explicit and typed:
```tsx
const saveAndRefresh = (input: UpdatePostInput) =>
Effect.gen(function* () {
const result = yield* updatePost.mutate(input)
if (AsyncResult.isSuccess(result)) {
yield* posts.invalidateCacheEntry(["post", result.value.id] as const)
yield* posts.refreshView
}
return result
})
```
This is the Effect equivalent of an `onSuccess` callback that invalidates a
TanStack Query. Because it is ordinary Effect composition, the workflow can
also include tracing, transactions, retries, notifications, or parallel cache
updates without introducing a separate callback API.
Remember that Query invalidation removes cached data but does not refetch by
itself. Follow it with `refreshView` when the current screen should update
immediately.
## The Effect touch
Mutation follows the ergonomics of TanStack mutations while retaining Effect's
execution model:
- The mutation function has the full `Effect<A, E, R>` type.
- Required services are captured from the creation context.
- Failures are represented as `Cause<E>`, including defects and interruption.
- Fibers are scoped, so component unmounting cleans up in-flight operations.
- `mutate` composes directly inside larger Effect workflows.
- `mutateView` exposes call-specific progress as a View for React or Effect
consumers.
- Retry schedules, timeouts, tracing, logging, metrics, schema validation, and
concurrency controls can be applied with normal Effect operators.
Mutation is therefore a small bridge: TanStack-style mutation state on one
side, and an ordinary, typed Effect program on the other.
+288
View File
@@ -0,0 +1,288 @@
---
sidebar_position: 3
title: Query
---
# Query
The Query module is Effect View's take on TanStack Query. It provides the same
kind of server-state workflow—reactive query keys, cached results, stale times,
background refreshes, window-focus refetching, and cache invalidation—but the
query function is an `Effect` and the observable state is a `View`.
If you already know TanStack Query, the main concepts translate directly:
| TanStack Query concept | Effect View equivalent |
| --- | --- |
| `QueryClient` | The `QueryClient` Effect service |
| `queryKey` | A reactive key supplied as a `View<K>` |
| `queryFn` | `f: (key: K) => Effect<A, E, R>` |
| `useQuery` result | `query.state`, a `View<QueryState<K, A, E>>` |
| `isFetching` | `result.waiting` |
| `refetch` | `query.refresh` or `query.refreshView` |
| `invalidateQueries` | `query.invalidateCache` or `invalidateCacheEntry` |
The goal is familiar query behavior without leaving Effect's model. Query
functions keep their typed success, error, and service channels. They can use
services from the runtime, be composed with schema decoding and retry policies,
and are interrupted automatically when their scope ends or a new key supersedes
the current request.
## Provide a QueryClient
Queries share successful results through a `QueryClient`. Add its layer to the
application runtime once, alongside the services used by your query effects:
```tsx title="src/runtime.ts"
import { Layer } from "effect"
import { FetchHttpClient } from "effect/unstable/http"
import { QueryClient, ReactRuntime } from "effect-view"
const AppLive = Layer.empty.pipe(
Layer.provideMerge(QueryClient.layer({
defaultStaleTime: "30 seconds",
defaultRefreshOnWindowFocus: true,
cacheGcTime: "5 minutes",
})),
Layer.provideMerge(FetchHttpClient.layer),
)
export const runtime = ReactRuntime.make(AppLive)
```
The client owns the cache and its cleanup lifecycle. Individual queries can
override `staleTime` and `refreshOnWindowFocus`; otherwise they inherit the
client defaults.
## Create a reactive query
A query is driven by a `View` rather than by a value read during one React
render. Whenever that key changes, `Query.service` checks the cache and starts
the query effect when necessary.
```tsx
import { Effect, Schema, SubscriptionRef } from "effect"
import { HttpClient } from "effect/unstable/http"
import { Component, Lens, Query, View } from "effect-view"
const Post = Schema.Struct({
id: Schema.Int,
title: Schema.String,
body: Schema.String,
})
const PostView = Component.make("Post")(function* () {
const [postId, query] = yield* Component.useOnMount(() =>
Effect.gen(function* () {
const key = Lens.fromSubscriptionRef(
yield* SubscriptionRef.make(["post", 1 as number] as const),
)
const query = yield* Query.service({
key,
staleTime: "1 minute",
f: ([, id]) =>
HttpClient.HttpClient.pipe(
Effect.andThen((client) =>
client.get(`https://example.com/posts/${id}`),
),
Effect.andThen((response) => response.json),
Effect.andThen(Schema.decodeUnknownEffect(Post)),
),
})
return [Lens.focusTupleAt(key, 1), query] as const
}),
)
const [state] = yield* View.useAll([query.state])
const [id, setId] = yield* Lens.useState(postId)
return (
<section>
<select
value={id}
onChange={(event) => setId(Number(event.currentTarget.value))}
>
<option value={1}>Post 1</option>
<option value={2}>Post 2</option>
</select>
<pre>{state.result._tag}</pre>
</section>
)
})
```
The tuple key plays the same role as `['post', id]` in TanStack Query. Keys use
Effect equality by default, so structurally equal Effect data types work well
as query keys. Supply `keyEquivalence` when the key needs different equality
semantics.
`Query.service` creates the query and starts watching its key in the current
scope. Creating it in `Component.useOnMount` keeps one query instance—and one
stable query function identity—for the component's lifetime.
## Render AsyncResult
`query.state` contains both the current key and an `AsyncResult`:
```ts
interface QueryState<K, A, E> {
readonly key: K
readonly result: AsyncResult.AsyncResult<A, E>
}
```
Subscribe with `View.useAll`, then match the result explicitly:
```tsx
import { AsyncResult } from "effect/unstable/reactivity"
const [state] = yield* View.useAll([query.state])
return AsyncResult.match(state.result, {
onInitial: ({ waiting }) =>
waiting ? <p>Loading...</p> : <p>Not loaded.</p>,
onFailure: ({ cause, previousSuccess, waiting }) => (
<section>
<p>Request failed: {cause.toString()}</p>
{previousSuccess._tag === "Some" && (
<p>Last post: {previousSuccess.value.value.title}</p>
)}
{waiting && <p>Trying again...</p>}
</section>
),
onSuccess: ({ value, waiting }) => (
<article>
{waiting && <small>Refreshing...</small>}
<h2>{value.title}</h2>
<p>{value.body}</p>
</article>
),
})
```
The `waiting` flag separates “do I have a result?” from “is work currently in
flight?”. During a background refresh, a successful result remains successful
and keeps its value while `waiting` becomes `true`. A failed refresh can retain
its `previousSuccess`. This avoids replacing useful content with an empty
loading screen every time data is refreshed.
Failures contain an Effect `Cause<E>`, preserving typed failures, defects, and
interruption information instead of flattening everything into an untyped
exception.
## Change the query key
The key is reactive state, so changing it is enough to fetch the corresponding
resource. There is no separate dependency array to keep synchronized:
```tsx
const [id, setId] = yield* Lens.useState(postId)
return (
<label>
Post
<select
value={id}
onChange={(event) => setId(Number(event.currentTarget.value))}
>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
</select>
</label>
)
```
When the key changes, the previous in-flight request is interrupted. The query
then reuses a fresh cached success or starts the effect for the new key.
## Refresh and invalidate
Refresh resolves the latest key again. A fresh cached result can satisfy it
immediately; a stale or missing result runs the query effect while preserving
previous data as background state. Invalidation removes cached data, so the
next fetch for that key must run the effect again.
```tsx
const runSync = yield* Component.useRunSync()
return (
<div>
<button onClick={() => runSync(query.refreshView)}>
Refresh current post
</button>
<button onClick={() => runSync(query.invalidateCacheEntry(["post", id] as const))}>
Invalidate current post
</button>
<button onClick={() => runSync(query.invalidateCache)}>
Invalidate all posts from this query
</button>
</div>
)
```
The methods come in two styles:
| Method | Behavior |
| --- | --- |
| `fetch(key)` | Fetch a specific key and wait for its final state. |
| `fetchView(key)` | Start fetching and immediately return a live state `View`. |
| `refresh` | Resolve the current key again and wait for its final state. |
| `refreshView` | Resolve the current key again and immediately return a live state `View`. |
| `invalidateCacheEntry(key)` | Remove the cached success for one key. |
| `invalidateCache` | Remove every cached success associated with this query function. |
The `*View` variants are convenient in synchronous UI callbacks: they return
after the scoped request has started, while the returned View and `query.state`
continue to publish progress. The non-View variants are useful in Effect
workflows that need to wait for the final success or failure state.
Invalidating does not itself refetch. Follow it with `refreshView`, change the
key, or allow a later fetch to repopulate the cache.
## Staleness and cache lifetime
`staleTime` controls how long a successful result can satisfy a fetch without
running the effect again. A stale entry remains available as previous data
while the query refreshes it.
`cacheGcTime` is configured on `QueryClient`. Entries that have not been
accessed are eventually removed after their stale period plus the configured
garbage-collection time.
By default, the client enables refresh on browser window focus. Set it globally
or override it for one query:
```tsx
const query = yield* Query.service({
key,
f: loadPost,
staleTime: "10 seconds",
refreshOnWindowFocus: false,
})
```
Window focus resolves the current key again, subject to the same freshness
check. The browser integration is ignored in non-browser environments.
## The Effect touch
The API emulates TanStack Query's server-state ergonomics, but query execution
remains ordinary Effect code:
- `f` has the full `Effect<A, E, R>` type, including required services.
- The query captures its Effect context when it is created, so callbacks do not
need to manually reconstruct dependencies.
- Effects can use `Schema`, retry schedules, tracing, logging, metrics,
cancellation, and any other Effect operator before becoming query state.
- Request fibers belong to the creation scope and are interrupted on unmount,
key replacement, or scope closure.
- Results are `View`s, so the same state can drive React through `View.useAll`
or participate in Effect streams and application logic outside React.
- Failures retain `Cause<E>` rather than losing Effect's error model.
`Query` is therefore best understood as a TanStack Query-shaped coordinator
for Effect programs: it handles when and whether to run them, while Effect
continues to describe what the work requires and how it behaves.
+274
View File
@@ -0,0 +1,274 @@
---
sidebar_position: 2
title: State Management
---
# State Management
`Lens` is the main type used for state management in `effect-view`.
A Lens is an effectful handle to a piece of state. It can read the current value,
subscribe to changes, and write updates back to the underlying source. A Lens
can point at a whole state object or focus on one nested field inside it.
`effect-view` re-exports the `Lens` and `View` modules from
[`effect-lens`](https://github.com/Thiladev/effect-lens) for convenience. The
core data model and transformation APIs belong to `effect-lens`, so check the
[`effect-lens` documentation](https://github.com/Thiladev/effect-lens/tree/master/packages/effect-lens) for the full Lens/View API.
The usual pattern is to create state with Effect primitives such as
`SubscriptionRef`, turn that primitive into a Lens with a matching constructor
such as `Lens.fromSubscriptionRef`, and bind Lens values into components with
`View.useAll`.
`View` is the read-only side of this model. Every Lens is also a View.
## Where To Store State
State can live pretty much anywhere as a `Lens` or `View`: in a
service, in a layer, in a component scope, or alongside plain React state. Pick
the owner based on who needs the state. Once you have a Lens/View
handle, pass it around however you like, including through React props.
If state is shared by multiple components or belongs to application logic, store
it in an Effect service:
```tsx
import { Context, Effect, Layer, SubscriptionRef } from "effect"
import { Component, Lens, View } from "effect-view"
class CounterState extends Context.Service<
CounterState,
{ readonly count: Lens.Lens<number> }
>()("CounterState") {
static readonly layer = Layer.effect(
CounterState,
Effect.gen(function*() {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
return { count } as const
}),
)
}
const CounterValueView = Component.make("CounterValue")(function*() {
const state = yield* CounterState
const [count] = yield* View.useAll([state.count])
return <p>Count: {count}</p>
})
```
If state belongs to a single Effect View component instance, or to a shallow
hierarchy of subcomponents that receive it through props, create it with
`Component.useOnMount`:
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, View } from "effect-view"
const LocalCounterView = Component.make("LocalCounter")(function*() {
const state = yield* Component.useOnMount(() =>
Effect.gen(function*() {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
return { count } as const
}),
)
const [count] = yield* View.useAll([state.count])
return <p>Count: {count}</p>
})
```
For simple UI state that is not shared and does not need Effect integration,
prefer regular React state. A local "show details" toggle is usually better as
`React.useState(false)` than as a Lens.
## View.useAll
A `View<A>` is reactive state with a current value and a stream of changes. Use
`View.useAll` whenever a component needs to bind View values into render output.
`Lens` is a `View`, so this is also the default way to read Lens values
from a component.
```tsx
import { Context, Effect, Layer, SubscriptionRef } from "effect"
import { Component, Lens, View } from "effect-view"
class CounterState extends Context.Service<
CounterState,
{
readonly count: Lens.Lens<number>
readonly doubled: View.View<number>
}
>()("CounterState") {
static readonly layer = Layer.effect(
CounterState,
Effect.gen(function*() {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
const doubled = View.map(count, (n) => n * 2)
return { count, doubled } as const
}),
)
}
const CounterReadOnlyView = Component.make("CounterReadOnly")(
function* () {
const state = yield* CounterState
const [count, doubled] = yield* View.useAll([
state.count,
state.doubled,
])
return <p>Count: {count}, doubled: {doubled}</p>
},
)
```
`View.useAll` reads the current values during render and uses scoped subscriptions to update React state when changes arrive.
When you need to modify state, write to the Lens with `Lens.set` or `Lens.update`:
```tsx
const CounterControlsView = Component.make("CounterControls")(
function* () {
const state = yield* CounterState
const [count] = yield* View.useAll([state.count])
const increment = yield* Component.useCallbackSync(
() => Lens.update(state.count, (n) => n + 1),
[],
)
const reset = yield* Component.useCallbackSync(
() => Lens.set(state.count, 0),
[],
)
return (
<section>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={reset}>Reset</button>
</section>
)
},
)
```
## Lens.useState
`Lens.useState` is useful when React needs the familiar `[value, setValue]`
tuple, backed by a Lens. Reach for it when the JSX API expects a synchronous
setter, especially controlled inputs such as text fields, checkboxes, selects,
or third-party components with `value` / `onChange` props.
If a component only needs to display the value, prefer `View.useAll`.
`Lens.useState` is for places where reading and writing need to be wired
together in React's local-state shape.
```tsx
import { Context, Effect, Layer, SubscriptionRef } from "effect"
import { Component, Lens } from "effect-view"
class FormState extends Context.Service<
FormState,
{ readonly name: Lens.Lens<string> }
>()("FormState") {
static readonly layer = Layer.effect(
FormState,
Effect.gen(function*() {
const name = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(""))
return { name } as const
}),
)
}
const NameInputView = Component.make("NameInput")(function* () {
const state = yield* FormState
const [name, setName] = yield* Lens.useState(state.name)
return (
<input
value={name}
onChange={(event) => setName(event.currentTarget.value)}
/>
)
})
```
`Lens.useState` returns the current value and a React-compatible setter. Calling
the setter writes through the Lens, so every other component subscribed to the
same Lens sees the update.
## Focused Lenses
Use focused Lenses when a component should work with one part of a larger state
object. A focused Lens is still a Lens, so it can be read with
`View.useAll` or used with `Lens.useState` when React needs a
read/write tuple.
```tsx
import { Context, Effect, Layer, SubscriptionRef } from "effect"
import { Component, Lens, View } from "effect-view"
interface UserProfile {
readonly name: string
readonly email: string
readonly role: string
}
class ProfileState extends Context.Service<
ProfileState,
{
readonly profile: Lens.Lens<UserProfile>
readonly name: Lens.Lens<string>
readonly role: Lens.Lens<string>
}
>()("ProfileState") {
static readonly layer = Layer.effect(
ProfileState,
Effect.gen(function*() {
const profile = Lens.fromSubscriptionRef(
yield* SubscriptionRef.make<UserProfile>({
name: "",
email: "",
role: "reader",
}),
)
const name = Lens.focusObjectOn(profile, "name")
const role = Lens.focusObjectOn(profile, "role")
return { profile, name, role } as const
}),
)
}
const ProfileNameView = Component.make("ProfileName")(function*() {
const state = yield* ProfileState
const [name, setName] = yield* Lens.useState(state.name)
const [role] = yield* View.useAll([state.role])
return (
<label>
Name
<input
value={name}
onChange={(event) => setName(event.currentTarget.value)}
/>
<span>Role: {role}</span>
</label>
)
})
```
Updating the focused `name` Lens through `Lens.useState` updates the parent
`profile` Lens. The focused `role` Lens is only read, so it stays on the simpler
`View.useAll` path.
For focusing into nested state, deriving lenses, custom write behavior, and the
complete API, refer to the
[`effect-lens` documentation](https://github.com/Thiladev/effect-lens/tree/master/packages/effect-lens).
+142
View File
@@ -0,0 +1,142 @@
import type * as Preset from "@docusaurus/preset-classic"
import type { Config } from "@docusaurus/types"
import { themes as prismThemes } from "prism-react-renderer"
// This runs in Node.js - Don't use client-side code here (browser APIs, JSX...)
const config: Config = {
title: "Effect View",
tagline: "Write React function components with Effect",
favicon: "img/favicon.ico",
// Future flags, see https://docusaurus.io/docs/api/docusaurus-config#future
future: {
v4: true, // Improve compatibility with the upcoming Docusaurus v4
},
// Set the production url of your site here
url: "https://thiladev.github.io",
// Set the /<baseUrl>/ pathname under which your site is served
// For GitHub pages deployment, it is often '/<projectName>/'
baseUrl: "/effect-view/",
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: "Thiladev", // Usually your GitHub org/user name.
projectName: "effect-view", // Usually your repo name.
onBrokenLinks: "throw",
// Even if you don't use internationalization, you can use this field to set
// useful metadata like html lang. For example, if your site is Chinese, you
// may want to replace "en" with "zh-Hans".
i18n: {
defaultLocale: "en",
locales: ["en"],
},
presets: [
[
"classic",
{
docs: {
sidebarPath: "./sidebars.ts",
editUrl:
"https://github.com/Thiladev/effect-view/tree/main/packages/docs/",
lastVersion: "current",
versions: {
current: {
label: "effect-view v1",
},
"effect-fc-1.0": {
label: "effect-fc 1.0",
path: "effect-fc/1.0",
},
},
},
blog: false,
theme: {
customCss: "./src/css/custom.css",
},
} satisfies Preset.Options,
],
],
themeConfig: {
// Replace with your project's social card
colorMode: {
respectPrefersColorScheme: true,
},
navbar: {
title: "Effect View",
logo: {
alt: "Effect View logo",
src: "img/logo.svg",
},
items: [
{
type: "docSidebar",
sidebarId: "docsSidebar",
position: "left",
label: "Docs",
},
{
type: "docsVersionDropdown",
position: "right",
},
{
href: "https://github.com/Thiladev/effect-view",
label: "GitHub",
position: "right",
},
],
},
footer: {
style: "dark",
links: [
{
title: "Docs",
items: [
{
label: "Getting Started",
to: "/docs/getting-started",
},
],
},
{
title: "Project",
items: [
{
label: "GitHub",
href: "https://github.com/Thiladev/effect-view",
},
{
label: "Example App",
href: "https://github.com/Thiladev/effect-view/tree/main/packages/example",
},
],
},
{
title: "Ecosystem",
items: [
{
label: "Effect",
href: "https://effect.website/",
},
{
label: "React",
href: "https://react.dev/",
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} Effect View contributors. Built with Docusaurus.`,
},
prism: {
theme: prismThemes.github,
darkTheme: prismThemes.dracula,
},
} satisfies Preset.ThemeConfig,
}
export default config
+50
View File
@@ -0,0 +1,50 @@
{
"name": "docs",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids",
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "3.10.1",
"@docusaurus/faster": "^3.10.1",
"@docusaurus/preset-classic": "3.10.1",
"@mdx-js/react": "^3.1.1",
"clsx": "^2.1.1",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.5",
"react-dom": "^19.2.5"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.10.1",
"@docusaurus/tsconfig": "3.10.1",
"@docusaurus/types": "3.10.1",
"@types/react": "^19.2.15",
"@types/react-dom": "^19.2.3",
"typescript": "~6.0.3"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=20.0"
}
}
+15
View File
@@ -0,0 +1,15 @@
import type { SidebarsConfig } from "@docusaurus/plugin-content-docs"
// This runs in Node.js - Don't use client-side code here (browser APIs, JSX...)
const sidebars: SidebarsConfig = {
docsSidebar: [
"getting-started",
"state-management",
"query",
"mutation",
"forms",
],
}
export default sidebars
+37
View File
@@ -0,0 +1,37 @@
:root {
--ifm-color-primary: #0b6f74;
--ifm-color-primary-dark: #096469;
--ifm-color-primary-darker: #085e63;
--ifm-color-primary-darkest: #074d51;
--ifm-color-primary-light: #0d7a7f;
--ifm-color-primary-lighter: #0e8085;
--ifm-color-primary-lightest: #109096;
--ifm-background-color: #fffaf1;
--ifm-code-font-size: 95%;
--ifm-font-family-base:
"Avenir Next", "Segoe UI", "Helvetica Neue", sans-serif;
--docusaurus-highlighted-code-line-bg: rgba(11, 111, 116, 0.1);
}
.button--primary {
--ifm-button-background-color: #0b6f74;
--ifm-button-border-color: #0b6f74;
}
.button--secondary {
--ifm-button-background-color: #f4a636;
--ifm-button-border-color: #f4a636;
--ifm-button-color: #1f2526;
}
[data-theme="dark"] {
--ifm-color-primary: #7ad6d4;
--ifm-color-primary-dark: #5cccca;
--ifm-color-primary-darker: #4cc6c4;
--ifm-color-primary-darkest: #34aaa8;
--ifm-color-primary-light: #98e0de;
--ifm-color-primary-lighter: #a8e6e4;
--ifm-color-primary-lightest: #d5f4f3;
--ifm-background-color: #111c1f;
--docusaurus-highlighted-code-line-bg: rgba(122, 214, 212, 0.18);
}
+652
View File
@@ -0,0 +1,652 @@
.page {
--home-ink: #102f31;
--home-muted: #506a6c;
--home-teal: #08777b;
--home-teal-bright: #16a3a1;
--home-amber: #e99526;
--home-paper: #fffdf8;
--home-card: rgba(255, 255, 255, 0.76);
--home-line: rgba(16, 47, 49, 0.12);
min-height: calc(100vh - var(--ifm-navbar-height));
overflow: hidden;
position: relative;
background:
radial-gradient(circle at 8% 5%, rgba(14, 145, 148, 0.2), transparent 28rem),
radial-gradient(circle at 92% 14%, rgba(240, 159, 48, 0.2), transparent 27rem),
linear-gradient(145deg, #f7f2e7 0%, #edf8f6 48%, #fff8ed 100%);
color: var(--home-ink);
}
.gridBackdrop {
background-image:
linear-gradient(rgba(16, 47, 49, 0.045) 1px, transparent 1px),
linear-gradient(90deg, rgba(16, 47, 49, 0.045) 1px, transparent 1px);
background-size: 48px 48px;
inset: 0;
mask-image: linear-gradient(to bottom, black, transparent 62%);
pointer-events: none;
position: absolute;
}
.hero {
align-items: center;
display: grid;
gap: clamp(3rem, 6vw, 6rem);
grid-template-columns: minmax(0, 0.88fr) minmax(560px, 1.12fr);
min-height: min(820px, calc(100vh - var(--ifm-navbar-height)));
padding-bottom: 6rem;
padding-top: 6rem;
position: relative;
z-index: 1;
}
.heroCopy {
max-width: 650px;
}
.eyebrow,
.sectionKicker {
align-items: center;
color: var(--home-teal);
display: flex;
font-size: 0.76rem;
font-weight: 850;
gap: 0.65rem;
letter-spacing: 0.18em;
margin: 0 0 1.35rem;
text-transform: uppercase;
}
.pulse {
background: var(--home-teal-bright);
border-radius: 50%;
box-shadow: 0 0 0 5px rgba(22, 163, 161, 0.14);
height: 0.55rem;
width: 0.55rem;
}
.hero h1 {
color: var(--home-ink);
font-size: clamp(3.4rem, 6.4vw, 6.4rem);
font-weight: 780;
letter-spacing: -0.075em;
line-height: 0.92;
margin: 0;
}
.hero h1 span {
background: linear-gradient(105deg, var(--home-teal) 5%, #1a9793 48%, var(--home-amber));
background-clip: text;
color: transparent;
display: inline;
-webkit-background-clip: text;
}
.lede {
color: var(--home-muted);
font-size: clamp(1.08rem, 1.55vw, 1.32rem);
line-height: 1.65;
margin: 2rem 0 0;
max-width: 630px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
margin-top: 2.3rem;
}
.primaryAction,
.secondaryAction,
.ctaAction {
align-items: center;
border-radius: 999px;
display: inline-flex;
font-weight: 750;
gap: 0.8rem;
justify-content: center;
padding: 0.88rem 1.35rem;
text-decoration: none !important;
transition: transform 160ms ease, box-shadow 160ms ease, background 160ms ease;
}
.primaryAction {
background: var(--home-ink);
box-shadow: 0 12px 28px rgba(16, 47, 49, 0.2);
color: #f6fffd;
}
.primaryAction:hover {
box-shadow: 0 16px 36px rgba(16, 47, 49, 0.28);
color: #fff;
transform: translateY(-2px);
}
.secondaryAction {
background: rgba(255, 255, 255, 0.58);
border: 1px solid var(--home-line);
color: var(--home-ink);
}
.secondaryAction:hover {
background: rgba(255, 255, 255, 0.9);
color: var(--home-teal);
transform: translateY(-2px);
}
.install {
align-items: center;
color: var(--home-muted);
display: flex;
font-size: 0.84rem;
gap: 0.7rem;
margin-top: 1.4rem;
}
.install span {
color: var(--home-amber);
font-family: var(--ifm-font-family-monospace);
font-weight: 800;
}
.install code {
background: transparent;
border: 0;
color: inherit;
padding: 0;
}
.codeStage {
min-width: 0;
perspective: 1200px;
position: relative;
}
.codeGlow {
background: linear-gradient(115deg, rgba(11, 133, 136, 0.48), rgba(238, 156, 40, 0.38));
filter: blur(55px);
inset: 8% 5%;
opacity: 0.55;
position: absolute;
}
.codeWindow {
background: #101b1e;
border: 1px solid rgba(166, 225, 220, 0.2);
border-radius: 1.25rem;
box-shadow:
0 34px 90px rgba(18, 49, 52, 0.3),
0 2px 0 rgba(255, 255, 255, 0.06) inset;
overflow: hidden;
position: relative;
transform: rotateY(-2deg) rotateX(1deg);
}
.windowBar {
align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
color: #b6c9c9;
display: grid;
font-family: var(--ifm-font-family-monospace);
font-size: 0.73rem;
grid-template-columns: 1fr auto 1fr;
padding: 0.78rem 1rem;
}
.windowDots {
display: flex;
gap: 0.38rem;
}
.windowDots span {
background: #4f6d6e;
border-radius: 50%;
height: 0.55rem;
width: 0.55rem;
}
.windowDots span:first-child {
background: #ef8d5b;
}
.windowDots span:nth-child(2) {
background: #e9bc50;
}
.windowDots span:last-child {
background: #65bd92;
}
.windowStatus {
color: #74d2cd;
justify-self: end;
}
.codeWindow :global(.theme-code-block) {
border-radius: 0;
box-shadow: none;
margin: 0;
}
.codeWindow :global(.theme-code-block pre) {
background: #101b1e !important;
color: #d7e5e4 !important;
font-size: 0.78rem;
line-height: 1.62;
max-height: none;
padding: 1.45rem 1.6rem !important;
}
.codeWindow :global(.token-line),
.codeWindow :global(.token.plain),
.codeWindow :global(.token.imports),
.codeWindow :global(.token.maybe-class-name),
.codeWindow :global(.token.punctuation),
.codeWindow :global(.token.operator),
.codeWindow :global(.token.plain-text),
.codeWindow :global(.token.property-access) {
color: #d7e5e4 !important;
}
.codeWindow :global(.token.keyword) {
color: #c792ea !important;
}
.codeWindow :global(.token.string) {
color: #c3e88d !important;
}
.codeWindow :global(.token.function),
.codeWindow :global(.token.method) {
color: #82aaff !important;
}
.codeWindow :global(.token.tag) {
color: #f07178 !important;
}
.codeWindow :global(.token.builtin) {
color: #ffcb6b !important;
}
.codeLegend {
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #a9bcbc;
display: grid;
font-size: 0.7rem;
grid-template-columns: repeat(3, 1fr);
}
.codeLegend span {
padding: 0.8rem 0.9rem;
text-align: center;
}
.codeLegend span + span {
border-left: 1px solid rgba(255, 255, 255, 0.08);
}
.codeLegend b {
color: #e8a94b;
font-family: var(--ifm-font-family-monospace);
margin-right: 0.25rem;
}
.featuresSection {
padding-bottom: 7rem;
padding-top: 4rem;
position: relative;
z-index: 1;
}
.sectionHeading {
display: grid;
gap: 0 3rem;
grid-template-columns: minmax(0, 1.25fr) minmax(280px, 0.75fr);
margin-bottom: 2.8rem;
}
.sectionHeading .sectionKicker {
grid-column: 1 / -1;
}
.sectionHeading h2,
.cta h2 {
color: var(--home-ink);
font-size: clamp(2.25rem, 4vw, 4rem);
letter-spacing: -0.055em;
line-height: 1;
margin: 0;
}
.sectionHeading > p:last-child {
align-self: end;
color: var(--home-muted);
font-size: 1.03rem;
line-height: 1.65;
margin: 0;
}
.featureGrid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.featureCard {
background: var(--home-card);
border: 1px solid var(--home-line);
border-radius: 1.35rem;
color: inherit;
display: flex;
flex-direction: column;
min-height: 310px;
overflow: hidden;
padding: 1.45rem;
position: relative;
text-decoration: none !important;
transition: border-color 180ms ease, box-shadow 180ms ease, transform 180ms ease;
}
.featureCard::before {
background: linear-gradient(90deg, var(--home-teal-bright), var(--home-amber));
content: "";
height: 3px;
left: 1.45rem;
opacity: 0;
position: absolute;
right: 1.45rem;
top: 0;
transform: scaleX(0.5);
transition: opacity 180ms ease, transform 180ms ease;
}
.featureCard:hover {
border-color: rgba(8, 119, 123, 0.35);
box-shadow: 0 24px 60px rgba(28, 65, 66, 0.12);
color: inherit;
transform: translateY(-5px);
}
.featureCard:hover::before {
opacity: 1;
transform: scaleX(1);
}
.cardTopline {
align-items: center;
display: flex;
justify-content: space-between;
}
.featureIcon {
align-items: center;
background: rgba(8, 119, 123, 0.1);
border: 1px solid rgba(8, 119, 123, 0.12);
border-radius: 0.8rem;
color: var(--home-teal);
display: flex;
font-family: var(--ifm-font-family-monospace);
font-size: 1rem;
font-weight: 850;
height: 2.7rem;
justify-content: center;
width: 2.7rem;
}
.cardIndex {
color: rgba(16, 47, 49, 0.32);
font-family: var(--ifm-font-family-monospace);
font-size: 0.72rem;
}
.featureCard h3 {
color: var(--home-ink);
font-size: 1.25rem;
letter-spacing: -0.025em;
margin: 2rem 0 0.7rem;
}
.featureCard > p {
color: var(--home-muted);
font-size: 0.94rem;
line-height: 1.65;
margin: 0;
}
.cardFooter {
align-items: center;
display: flex;
justify-content: space-between;
margin-top: auto;
padding-top: 1.5rem;
}
.cardFooter code {
background: rgba(8, 119, 123, 0.08);
border: 0;
color: var(--home-teal);
font-size: 0.7rem;
padding: 0.35rem 0.5rem;
}
.cardFooter > span {
color: var(--home-amber);
font-size: 1.1rem;
transition: transform 180ms ease;
}
.featureCard:hover .cardFooter > span {
transform: translate(3px, -3px);
}
.ctaWrap {
padding-bottom: 7rem;
position: relative;
z-index: 1;
}
.cta {
align-items: center;
background:
radial-gradient(circle at 90% 20%, rgba(233, 149, 38, 0.22), transparent 20rem),
linear-gradient(125deg, #12383a, #10292c);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 1.75rem;
box-shadow: 0 28px 80px rgba(16, 47, 49, 0.2);
display: flex;
gap: 3rem;
justify-content: space-between;
overflow: hidden;
padding: clamp(2rem, 5vw, 4rem);
}
.cta .sectionKicker {
color: #79d5d1;
}
.cta h2 {
color: #f7fffd;
}
.cta p:last-child {
color: #b9cccc;
line-height: 1.65;
margin: 1rem 0 0;
max-width: 650px;
}
.ctaAction {
background: #f0a13b;
color: #162d2e;
flex: 0 0 auto;
}
.ctaAction:hover {
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.24);
color: #102526;
transform: translateY(-2px);
}
:global([data-theme="dark"]) .page {
--home-ink: #e9f7f5;
--home-muted: #a9bfbd;
--home-teal: #79d5d1;
--home-teal-bright: #5bc8c5;
--home-amber: #f1ad4e;
--home-card: rgba(20, 42, 45, 0.76);
--home-line: rgba(174, 221, 218, 0.14);
background:
radial-gradient(circle at 8% 5%, rgba(33, 154, 154, 0.17), transparent 28rem),
radial-gradient(circle at 92% 14%, rgba(209, 130, 31, 0.13), transparent 27rem),
linear-gradient(145deg, #0f1b1e 0%, #102426 48%, #161e1e 100%);
}
:global([data-theme="dark"]) .gridBackdrop {
background-image:
linear-gradient(rgba(174, 221, 218, 0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(174, 221, 218, 0.04) 1px, transparent 1px);
}
:global([data-theme="dark"]) .secondaryAction {
background: rgba(19, 43, 46, 0.75);
}
:global([data-theme="dark"]) .secondaryAction:hover {
background: rgba(27, 57, 60, 0.95);
}
:global([data-theme="dark"]) .primaryAction {
background: #dff8f5;
color: #123638;
}
:global([data-theme="dark"]) .primaryAction:hover {
color: #0b282a;
}
:global([data-theme="dark"]) .cardIndex {
color: rgba(220, 242, 239, 0.35);
}
@media screen and (max-width: 1180px) {
.hero {
gap: 3rem;
grid-template-columns: minmax(0, 0.85fr) minmax(500px, 1.15fr);
}
.hero h1 {
font-size: clamp(3.2rem, 6vw, 5rem);
}
}
@media screen and (max-width: 996px) {
.hero {
grid-template-columns: minmax(0, 1fr);
padding-bottom: 4rem;
padding-top: 4.5rem;
}
.heroCopy,
.codeStage,
.codeWindow,
.codeWindow :global(.theme-code-block) {
min-width: 0;
width: 100%;
}
.heroCopy {
max-width: 760px;
}
.codeStage {
margin: 0 auto;
max-width: 760px;
width: 100%;
}
.codeWindow {
transform: none;
}
.featureGrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media screen and (max-width: 700px) {
.hero {
box-sizing: border-box;
margin-left: 0;
margin-right: 0;
max-width: 100vw;
padding-left: 1.15rem;
padding-right: 1.15rem;
width: 100vw;
}
.heroCopy,
.codeStage {
max-width: calc(100vw - 2.3rem);
}
.hero h1 {
font-size: clamp(3rem, 15vw, 4.3rem);
}
.sectionHeading {
grid-template-columns: 1fr;
}
.sectionHeading > p:last-child {
margin-top: 1.25rem;
}
.featureGrid {
grid-template-columns: 1fr;
}
.featureCard {
min-height: 275px;
}
.codeLegend {
grid-template-columns: 1fr;
}
.codeLegend span + span {
border-left: 0;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.windowStatus {
display: none;
}
.windowBar {
grid-template-columns: 1fr auto;
}
.codeWindow :global(.theme-code-block pre) {
font-size: 0.69rem;
overflow-x: auto;
padding: 1.1rem !important;
}
.cta {
align-items: flex-start;
flex-direction: column;
}
}
@media (prefers-reduced-motion: reduce) {
.featureCard,
.featureCard::before,
.cardFooter > span,
.primaryAction,
.secondaryAction,
.ctaAction {
transition: none;
}
}
+205
View File
@@ -0,0 +1,205 @@
import Link from "@docusaurus/Link"
import CodeBlock from "@theme/CodeBlock"
import Layout from "@theme/Layout"
import clsx from "clsx"
import type { ReactNode } from "react"
import styles from "./index.module.css"
const componentExample = `import { Effect } from "effect"
import { Async, Component } from "effect-view"
import { Users } from "./services"
export const UserCard = Component.make("UserCard")(
function* ({ userId }: { userId: string }) {
const users = yield* Users
const user = yield* Component.useOnChange(
() => users.find(userId),
[userId],
)
yield* Component.useReactEffect(
() => Effect.forkScoped(users.watch(userId)),
[userId],
)
return (
<article>
<h2>{user.name}</h2>
<p>{user.email}</p>
</article>
)
},
).pipe(Async.async)`
const features = [
{
icon: "fx",
title: "Components are Effect programs",
description:
"Yield Effects and services directly from a component body, then return ordinary JSX. Types track every dependency all the way to the runtime boundary.",
tag: "Component.make",
to: "/docs/getting-started#write-your-first-component",
},
{
icon: "R",
title: "One typed runtime",
description:
"Build your application Layer once. Components access HTTP clients, repositories, configuration, tracing, and your own services without React context plumbing.",
tag: "ReactRuntime",
to: "/docs/getting-started#create-the-runtime",
},
{
icon: "S",
title: "Scopes follow React",
description:
"Every component owns an Effect Scope. Resources, subscriptions, and fibers are finalized when their component or dependency lifecycle ends.",
tag: "Scope.Scope",
to: "/docs/getting-started#the-component-root-scope",
},
{
icon: "↔",
title: "Reactive state without a new universe",
description:
"Lens and View connect Effect state to React. Focus large models into small writable values and subscribe only where rendering needs them.",
tag: "Lens + View",
to: "/docs/state-management",
},
{
icon: "Q",
title: "TanStack-shaped server state",
description:
"Reactive keys, caching, stale times, background refresh, mutations, and invalidation—with typed Effect services, Causes, and scoped fibers underneath.",
tag: "Query + Mutation",
to: "/docs/query",
},
{
icon: "Σ",
title: "Forms driven by Schema",
description:
"Keep input-friendly encoded values while application code receives validated, decoded types. Focus one root into reusable field-sized subforms.",
tag: "MutationForm + LensForm",
to: "/docs/forms",
},
] as const
export default function Home(): ReactNode {
return (
<Layout
title="Effect View"
description="Write React function components as typed Effect programs"
>
<main className={styles.page}>
<div className={styles.gridBackdrop} aria-hidden="true" />
<section className={clsx("container", styles.hero)}>
<div className={styles.heroCopy}>
<div className={styles.eyebrow}>
<span className={styles.pulse} />
Effect View for React 19
</div>
<h1>
React components,
<span> powered by Effect.</span>
</h1>
<p className={styles.lede}>
Bring typed services, scoped resources, reactive state, server
queries, and schema-driven forms into React without hiding either
framework.
</p>
<div className={styles.actions}>
<Link className={styles.primaryAction} to="/docs/getting-started">
Start building
<span aria-hidden="true"></span>
</Link>
<Link
className={styles.secondaryAction}
to="https://github.com/Thiladev/effect-view"
>
View on GitHub
</Link>
</div>
<div className={styles.install}>
<span aria-hidden="true">$</span>
<code>npm install effect-view effect@beta</code>
</div>
</div>
<div className={styles.codeStage}>
<div className={styles.codeGlow} aria-hidden="true" />
<div className={styles.codeWindow}>
<div className={styles.windowBar}>
<div className={styles.windowDots} aria-hidden="true">
<span />
<span />
<span />
</div>
<span>UserCard.tsx</span>
<span className={styles.windowStatus}>Effect + JSX</span>
</div>
<CodeBlock language="tsx">{componentExample}</CodeBlock>
<div className={styles.codeLegend}>
<span><b>01</b> Yield services</span>
<span><b>02</b> Own the lifecycle</span>
<span><b>03</b> Return JSX</span>
</div>
</div>
</div>
</section>
<section className={clsx("container", styles.featuresSection)}>
<div className={styles.sectionHeading}>
<p className={styles.sectionKicker}>Why Effect View</p>
<h2>One model from render to resources.</h2>
<p>
Effect View adds the pieces React deliberately leaves open while
preserving the React component model you already know.
</p>
</div>
<div className={styles.featureGrid}>
{features.map((feature, index) => (
<Link
className={styles.featureCard}
to={feature.to}
key={feature.title}
>
<div className={styles.cardTopline}>
<span className={styles.featureIcon}>{feature.icon}</span>
<span className={styles.cardIndex}>
{String(index + 1).padStart(2, "0")}
</span>
</div>
<h3>{feature.title}</h3>
<p>{feature.description}</p>
<div className={styles.cardFooter}>
<code>{feature.tag}</code>
<span aria-hidden="true"></span>
</div>
</Link>
))}
</div>
</section>
<section className={clsx("container", styles.ctaWrap)}>
<div className={styles.cta}>
<div>
<p className={styles.sectionKicker}>Ready when React is</p>
<h2>Start with one Effect component.</h2>
<p>
Add a runtime, cross the React boundary once, and grow into the
rest of the toolkit only when you need it.
</p>
</div>
<Link className={styles.ctaAction} to="/docs/getting-started">
Read the guide <span aria-hidden="true"></span>
</Link>
</div>
</section>
</main>
</Layout>
)
}
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

+47
View File
@@ -0,0 +1,47 @@
<svg
width="128"
height="128"
viewBox="0 0 128 128"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<title>Effect View</title>
<defs>
<linearGradient id="surface" x1="14" y1="10" x2="116" y2="122" gradientUnits="userSpaceOnUse">
<stop stop-color="#16A3A1" />
<stop offset="0.58" stop-color="#08777B" />
<stop offset="1" stop-color="#102F31" />
</linearGradient>
<radialGradient id="warmth" cx="0" cy="0" r="1" gradientTransform="translate(112 111) rotate(-135) scale(65)">
<stop stop-color="#F0A13B" stop-opacity="0.85" />
<stop offset="1" stop-color="#F0A13B" stop-opacity="0" />
</radialGradient>
<filter id="shadow" x="-20%" y="-20%" width="140%" height="150%">
<feDropShadow dx="0" dy="3" stdDeviation="2.5" flood-color="#062426" flood-opacity="0.22" />
</filter>
<clipPath id="tile">
<rect width="128" height="128" rx="30" />
</clipPath>
</defs>
<g clip-path="url(#tile)">
<rect width="128" height="128" fill="url(#surface)" />
<circle cx="112" cy="111" r="65" fill="url(#warmth)" />
<path d="M-8 30L55 -4H128V10L-8 83V30Z" fill="white" fill-opacity="0.055" />
</g>
<rect x="1" y="1" width="126" height="126" rx="29" stroke="white" stroke-opacity="0.14" stroke-width="2" />
<g transform="translate(24 24) scale(2.5)" fill="white" filter="url(#shadow)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M29.8022 24.317C30.2747 24.05 30.4361 23.4582 30.1636 22.9953C29.891 22.5329 29.2873 22.3741 28.8148 22.6411L15.9211 29.9362L3.07463 22.6683C2.60281 22.4012 1.999 22.5594 1.72597 23.0225C1.45347 23.4854 1.61541 24.077 2.08741 24.3441L15.3897 31.8698C15.5053 31.9353 15.6327 31.9771 15.7645 31.9929C15.8963 32.0087 16.0299 31.9981 16.1576 31.9617C16.278 31.9433 16.3941 31.9031 16.5002 31.8431L29.8022 24.317Z" />
<path fill-rule="evenodd" clip-rule="evenodd" d="M31.1298 16.6012C31.1974 16.1929 31.0061 15.7675 30.6177 15.5488L16.555 7.63105C16.4443 7.56873 16.3234 7.52682 16.198 7.50732C16.0631 7.46888 15.922 7.45758 15.7827 7.47405C15.6434 7.49053 15.5088 7.53446 15.3865 7.60332L1.32289 15.5214C0.913972 15.7518 0.723686 16.2117 0.824499 16.6391C0.780205 16.9913 0.91787 17.3598 1.32768 17.5916L15.3904 25.5478C15.5127 25.6169 15.6475 25.661 15.7869 25.6776C15.9263 25.6942 16.0675 25.6829 16.2026 25.6445C16.3297 25.6253 16.4522 25.583 16.5642 25.5197L30.6275 17.563C31.0408 17.329 31.1776 16.9562 31.1298 16.6012ZM28.2266 16.5591L15.9459 9.64453L3.67206 16.5554L15.9528 23.5034L28.2266 16.5591Z" />
<path fill-rule="evenodd" clip-rule="evenodd" d="M31.3429 10.6097C31.8677 10.3131 32.0476 9.65608 31.7442 9.14178C31.4416 8.62819 30.7712 8.45201 30.2464 8.74854L15.9269 16.8501L1.66063 8.77876C1.13584 8.48152 0.465408 8.65787 0.162793 9.172C-0.14053 9.68541 0.0391253 10.3432 0.564095 10.6397L15.337 18.9976C15.4654 19.0702 15.607 19.1165 15.7534 19.1339C15.8998 19.1514 16.0482 19.1395 16.19 19.0991C16.3236 19.0791 16.4524 19.0347 16.5701 18.9681L31.3429 10.6097Z" />
<path d="M2.7403 9.6795L15.8991 1.62024L29.0577 9.67879L15.8989 17.2013L2.7403 9.6795Z" />
<path fill-rule="evenodd" clip-rule="evenodd" d="M31.3255 8.49027C31.8513 8.78627 32.0333 9.44279 31.7325 9.95692C31.4307 10.4707 30.7603 10.6474 30.2344 10.3514L15.9128 2.28787L1.64317 10.3224C1.11731 10.6184 0.44688 10.4415 0.145328 9.92794C-0.15587 9.41381 0.0262664 8.75729 0.55159 8.46129L15.325 0.143725C15.4534 0.0713274 15.5949 0.0251207 15.7412 0.00776107C15.8875 -0.00959854 16.0358 0.00223134 16.1775 0.0425706C16.3093 0.0631109 16.4364 0.107185 16.5526 0.172702L31.3255 8.49027Z" />
</g>
<g filter="url(#shadow)">
<path d="M43 61.5C48.8 54.1 55.8 50.5 64 50.5C72.2 50.5 79.2 54.1 85 61.5C79.2 68.9 72.2 72.5 64 72.5C55.8 72.5 48.8 68.9 43 61.5Z" fill="#102F31" />
<circle cx="64" cy="61.5" r="7.5" fill="#F0A13B" />
<circle cx="66.5" cy="59" r="2.2" fill="white" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

+9
View File
@@ -0,0 +1,9 @@
{
// This file is not used in compilation. It is here just for a nice editor experience.
"extends": "@docusaurus/tsconfig",
"compilerOptions": {
"baseUrl": ".",
"ignoreDeprecations": "6.0"
},
"exclude": [".docusaurus", "build"]
}
@@ -0,0 +1,168 @@
---
sidebar_position: 3
title: Forms
---
# Forms
The form modules provide an Effect-first model for editable, schema-validated
state. They are not a visual component library. Instead, they give you
Lenses/Subscribables for form values, validation issues, and commit state, so
you can build the UI with whatever components your app already uses.
The base `Form` type represents a field. A field tracks both the raw encoded
value used by inputs and the decoded value produced by an Effect `Schema`:
- `encodedValue`: a `Lens` containing the raw input value.
- `value`: a `Subscribable` containing the decoded value as an `Option`.
- `issues`: a `Subscribable` containing schema validation issues for that field.
- `canCommit`, `isValidating`, and `isCommitting`: `Subscribable` flags for UI
state.
There are two root form flavors:
- `SubmittableForm`: owns local encoded form state, validates it, and submits a
decoded value through a mutation.
- `SynchronizedForm`: wraps an existing target `Lens` and writes valid changes
back to that target.
Most apps create one of those root forms, then focus it into fields with
`Form.focusObjectOn`, `Form.focusArrayAt`, or the other focusing helpers.
The core form model is Effect code and can technically be used outside
Effect-FC. Effect-FC adds the React-facing hooks, such as `Form.useInput`, that
make those forms convenient to bind to components.
## Field Inputs
Use `Form.useInput` to connect a `Form` field to a controlled input. It returns
a React-style `{ value, setValue }` pair and writes changes back to the field's
`encodedValue` Lens.
```tsx
import { Component, Form, Subscribable } from "effect-fc"
const TextInputView = Component.make("TextInput")(
function* (props: {
readonly form: Form.Form<readonly PropertyKey[], string, string>
readonly label: string
}) {
const input = yield* Form.useInput(props.form, {
debounce: "250 millis",
})
const [issues] = yield* Subscribable.useAll([props.form.issues])
return (
<label>
{props.label}
<input
value={input.value}
onChange={(event) => input.setValue(event.currentTarget.value)}
/>
{issues.map((issue) => (
<small key={issue.path.join(".")}>
{issue.message}
</small>
))}
</label>
)
},
)
```
Use `Form.useOptionalInput` for `Option` fields. It returns the same value/setter
pair plus `enabled` and `setEnabled`, which is useful for optional inputs that
can be toggled on and off.
## Submittable Forms
Use `SubmittableForm` when the user edits local encoded form state, validates it
with a schema, and then submits a decoded value.
```tsx
import { Effect, Schema } from "effect"
import { Component, Form, SubmittableForm, Subscribable } from "effect-fc"
import { TextInputView } from "./TextInputView"
const RegisterSchema = Schema.Struct({
email: Schema.String,
password: Schema.String,
})
class RegisterFormState extends Effect.Service<RegisterFormState>()(
"RegisterFormState",
{
scoped: Effect.gen(function* () {
const form = yield* SubmittableForm.service({
schema: RegisterSchema,
initialEncodedValue: {
email: "",
password: "",
},
f: ([value]) =>
Effect.log(`Registering ${value.email}`),
})
return {
form,
email: Form.focusObjectOn(form, "email"),
password: Form.focusObjectOn(form, "password"),
} as const
}),
},
) {}
const RegisterFormView = Component.make("RegisterForm")(
function* () {
const state = yield* RegisterFormState
const [canCommit, isCommitting] = yield* Subscribable.useAll([
state.form.canCommit,
state.form.isCommitting,
])
const runPromise = yield* Component.useRunPromise()
const TextInput = yield* TextInputView.use
return (
<form
onSubmit={(event) => {
event.preventDefault()
void runPromise(state.form.submit)
}}
>
<TextInput label="Email" form={state.email} />
<TextInput label="Password" form={state.password} />
<button disabled={!canCommit}>
{isCommitting ? "Submitting..." : "Submit"}
</button>
</form>
)
},
)
```
`SubmittableForm.service` starts validation in the form's scope. The form keeps
its encoded input state, decoded value, validation issues, submit mutation, and
commit flags available as Lenses/Subscribables.
## Synchronized Forms
Use `SynchronizedForm` when a form should edit an existing target `Lens`.
Instead of submitting a final value, valid encoded changes are synchronized back
to the target Lens.
This is useful for edit screens where the form is a validated view over existing
state. Use `SubmittableForm` for "submit this draft" flows, and
`SynchronizedForm` for "keep this target state synchronized when valid" flows.
## Focusing Fields
Forms can be focused just like Lenses:
```tsx
const emailField = Form.focusObjectOn(form, "email")
const firstItemField = Form.focusArrayAt(form, 0)
```
Focused fields keep the parent form's validation and commit state, but narrow
`encodedValue`, `value`, and `issues` to the field path. This lets each input
component receive only the field it needs.
@@ -0,0 +1,415 @@
---
sidebar_position: 1
title: Getting Started
---
# Getting Started
`effect-fc` lets React components be written as Effect programs. Inside a
component body you can yield services, run Effects, subscribe to Effect-powered
state, and still export a normal React function component at the edge of your
app.
## Install
Install `effect-fc` alongside `effect` and React 19.2 or newer:
```bash npm2yarn
npm install effect-fc effect react
```
```bash npm2yarn
npm install --save-dev @types/react
```
`effect-fc` is not opinionated about the React platform. Use it with web,
native, custom renderers, or any environment where React components can run.
Then install the platform-specific React packages for your target.
For web apps, install React DOM:
```bash npm2yarn
npm install react-dom
```
```bash npm2yarn
npm install --save-dev @types/react-dom
```
## Create A Runtime
An Effect-FC app needs an Effect runtime. Build one from the services your UI
needs, then share it with React through `ReactRuntime.Provider`.
For an empty app, `Layer.empty` is enough:
```tsx title="src/runtime.ts"
import { Layer } from "effect"
import { ReactRuntime } from "effect-fc"
export const runtime = ReactRuntime.make(Layer.empty)
```
As your app grows, add services to the layer:
```tsx title="src/runtime.ts"
import { FetchHttpClient } from "@effect/platform"
import { Layer } from "effect"
import { ReactRuntime } from "effect-fc"
const AppLive = Layer.empty.pipe(
Layer.provideMerge(FetchHttpClient.layer),
)
export const runtime = ReactRuntime.make(AppLive)
```
## Provide The Runtime
At the React root, wrap your app with `ReactRuntime.Provider`:
```tsx title="src/main.tsx"
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { ReactRuntime } from "effect-fc"
import { App } from "./App"
import { runtime } from "./runtime"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ReactRuntime.Provider runtime={runtime}>
<App />
</ReactRuntime.Provider>
</StrictMode>,
)
```
`ReactRuntime.Provider` also works with routers. Keep it above your router
provider so route components can be converted with the same runtime context.
## Write Your First Component
Use `Component.make` when you want automatic tracing spans, or
`Component.makeUntraced` when you only want the component behavior. This creates
an Effect-FC component, not a plain React component yet.
The Effect run during render must be synchronous. Effect-FC follows React's
render model, so component bodies should produce JSX without waiting on async
work. Use lifecycle hooks, callbacks, queries, or other Effect-FC helpers for
async work that happens outside render.
```tsx title="src/HelloView.tsx"
import { Effect } from "effect"
import { Component } from "effect-fc"
export const HelloView = Component.make("HelloView")(function* (props: {
readonly name: string
}) {
const message = yield* Effect.succeed(`Hello, ${props.name}`)
return <h1>{message}</h1>
})
```
At this point `HelloView` can yield Effects, services, and scoped lifecycle
work, but React cannot render it directly.
## Apply A Runtime
Use `Component.withRuntime` at the boundary where an Effect-FC component needs
to become a regular React function component.
```tsx title="src/Hello.tsx"
import { Component } from "effect-fc"
import { HelloView } from "./HelloView"
import { runtime } from "./runtime"
export const Hello = HelloView.pipe(
Component.withRuntime(runtime.context),
)
```
`Hello` is now a normal React component:
```tsx title="src/App.tsx"
import { Hello } from "./Hello"
export function App() {
return <Hello name="Effect" />
}
```
## Use Effect-FC Components Together
Inside an Effect-FC component, other Effect-FC components are available through
their `.use` effect. Yield `.use` to get a React component for the current
runtime context, then render it like JSX.
```tsx title="src/GreetingCardView.tsx"
import { Component } from "effect-fc"
import { HelloView } from "./HelloView"
export const GreetingCardView = Component.make("GreetingCard")(
function* () {
const Hello = yield* HelloView.use
return (
<section>
<Hello name="Effect" />
<p>This component is still running inside Effect-FC.</p>
</section>
)
},
)
```
Use `Component.withRuntime` only when you leave the Effect-FC tree and need a
normal React component again:
```tsx title="src/GreetingCard.tsx"
import { Component } from "effect-fc"
import { GreetingCardView } from "./GreetingCardView"
import { runtime } from "./runtime"
export const GreetingCard = GreetingCardView.pipe(
Component.withRuntime(runtime.context),
)
```
## Component Lifecycle
Every Effect-FC component instance exposes an Effect `Scope`. Effects that need
`Scope.Scope` can use that component scope to register finalizers, fork scoped
work, or acquire scoped resources.
The component scope is created when React mounts the component and closes when
React unmounts it. When the scope closes, Effect runs the finalizers registered
inside that scope.
Finalizers are forked when the scope closes, so cleanup logic can run
asynchronous Effects even though the component body itself must stay
synchronous.
```tsx title="src/MountedMessageView.tsx"
import { Console, Effect } from "effect"
import { Component } from "effect-fc"
export const MountedMessageView = Component.make("MountedMessage")(
function* () {
const message = yield* Component.useOnMount(() =>
Effect.gen(function* () {
yield* Console.log("MountedMessage mounted")
yield* Effect.addFinalizer(() =>
Console.log("MountedMessage unmounted"),
)
return "This value was loaded on mount."
}),
)
return <p>{message}</p>
},
)
```
Use `Component.useOnMount` when the component needs a value produced by an
Effect during its first render. The value is then cached for the component
instance. You can also use it to set up scoped component logic, subscriptions,
or resources that should live for the lifetime of that component instance.
Use `Component.useOnChange` when render needs the value computed by
scoped work that depends on changing inputs. When a dependency changes, React
re-renders the component and the hook computes the next value during that
render.
```tsx
import { Console, Effect } from "effect"
import { Component } from "effect-fc"
const UserPanelView = Component.make("UserPanel")(
function* (props: { readonly userId: string }) {
const label = yield* Component.useOnChange(
() =>
Effect.gen(function* () {
yield* Console.log(`Preparing view for ${props.userId}`)
yield* Effect.addFinalizer(() =>
Console.log(`Cleaning up ${props.userId}`),
)
return `Viewing user ${props.userId}`
}),
[props.userId],
)
return <p>{label}</p>
},
)
```
In this example, each `userId` gets its own scope. When `userId` changes,
Effect-FC closes the previous scope, runs its finalizers, and creates a new
scope for the next load. Unlike `useOnMount`, `useOnChange` does not expose the
component's root scope directly. It creates and provides its own scope for that
dependency window. Some other Effect-FC hooks follow the same pattern when they
need a lifecycle that is narrower than the whole component instance.
## Useful Effect-FC Hooks
Unlike plain React hooks, Effect-FC hooks return Effects. Use `yield*` to run
them inside the component body.
The most common Effect-FC hooks are:
- `Component.useOnMount`: run an Effect once during the component's first render
after mount, and return its value. The Effect must be synchronous.
```tsx
const initialData = yield* Component.useOnMount(() => loadInitialData)
```
- `Component.useOnChange`: when a dependency changes, React re-renders the
component and the Effect is run again inside the component body. It returns
the latest value, so the Effect must be synchronous too.
```tsx
const label = yield* Component.useOnChange(() => formatUserLabel(id), [id])
```
- `Component.useReactEffect`: Effect-powered `React.useEffect` for side effects
that do not need to compute render output or trigger a re-render. The Effect
must be synchronous and can register scoped finalizers.
```tsx
yield* Component.useReactEffect(
() => Effect.forkScoped(subscribeToUser(id)),
[id],
)
```
- `Component.useReactLayoutEffect`: Effect-powered `React.useLayoutEffect` with scoped
finalizers.
```tsx
yield* Component.useReactLayoutEffect(() => measure(ref), [])
```
- `Component.useRunSync` and `Component.useRunPromise`: run Effects from React
event handlers.
```tsx
const runPromise = yield* Component.useRunPromise()
return (
<button onClick={() => void runPromise(saveUser)}>
Save
</button>
)
```
- `Component.useCallbackSync` and `Component.useCallbackPromise`: create stable
React callbacks.
```tsx
const save = yield* Component.useCallbackPromise(
(user: User) => saveUser(user),
[],
)
return <button onClick={() => void save(user)}>Save</button>
```
## Use React Normally
An Effect-FC component is still a React function component. Anything you can do
in a regular React component can also be done in an Effect-FC component,
including React hooks, refs, event handlers, context, and JSX composition.
```tsx
import { Component } from "effect-fc"
import * as React from "react"
const CounterView = Component.make("Counter")(function* () {
const [count, setCount] = React.useState(0)
const buttonRef = React.useRef<HTMLButtonElement>(null)
return (
<button ref={buttonRef} onClick={() => setCount(count + 1)}>
Count: {count}
</button>
)
})
```
Use regular React hooks for local UI concerns, and reach for Effect-FC helpers
when the component needs Effect services, scopes, resources, or Effect-powered
callbacks.
## Use Tags
Components can yield Effect tags directly in the component body. There is no
need to memoize the service yourself; just yield the tag wherever the component
needs it.
```tsx title="src/Greeting.tsx"
const GreetingView = Component.make("Greeting")(function* (props: {
readonly name: string
}) {
const greeting = yield* GreetingService
return <p>{greeting.greet(props.name)}</p>
})
```
Service values in the runtime context are reactive by default. If a provided
service instance changes, Effect-FC unmounts and mounts again the components
that depend on that context, so they read the new service and restart their
scoped lifecycle with the new environment. For services that should not trigger
that behavior, pass their tags with `Component.withOptions({ nonReactiveTags:
[...] })`.
## Provide Services To A Subtree
Use `Component.useContextFromLayer` when an Effect-FC component should provide
extra services to another Effect-FC component. It turns a `Layer` into a runtime
context that can be provided to `.use`.
```tsx title="src/GreetingPageView.tsx"
import { Effect } from "effect"
import { Component } from "effect-fc"
import { GreetingView } from "./Greeting"
import { GreetingService } from "./services"
const GreetingLive = GreetingService.Default({
greet: (name: string) => `Welcome, ${name}`,
})
export const GreetingPageView = Component.make("GreetingPage")(function* () {
const context = yield* Component.useContextFromLayer(GreetingLive)
const Greeting = yield* Effect.provide(GreetingView.use, context)
return <Greeting name="Effect" />
})
```
The layer passed to `useContextFromLayer` should be stable. If a new layer value
is created on every render, Effect-FC has to build a new context, which can
cause unnecessary re-renders and scoped lifecycle restarts. Define static layers
outside the component, or memoize layers that depend on React props or state.
Layers built with `useContextFromLayer` are scoped to the component that builds
them. That means service construction can register scoped logic, acquire
resources, fork scoped fibers, and add finalizers that are tied to that
component's lifecycle.
## Where To Go Next
Once the runtime and component boundary are in place, the rest of the library
builds on the same idea:
- `Subscribable.useAll` reads Effect subscribables and rerenders when they
change.
- `Lens` connects React state and Effect `SubscriptionRef` values.
- `Query` and `Mutation` model async data and user-triggered operations.
- `Form`, `SubmittableForm`, and `SynchronizedForm` help build Effect-backed
forms.
The important pattern is small and repeatable: write Effect-FC components inside
the runtime, then use `Component.withRuntime` at React boundaries.
@@ -0,0 +1,245 @@
---
sidebar_position: 2
title: State Management
---
# State Management
`Lens` is the main type used for state management in `effect-fc`.
A Lens is an effectful handle to a piece of state. It can read the current value,
subscribe to changes, and write updates back to the underlying source. A Lens
can point at a whole state object or focus on one nested field inside it.
The usual pattern is to create state with Effect primitives such as
`SubscriptionRef`, turn that primitive into a Lens with a matching constructor
such as `Lens.fromSubscriptionRef`, and bind Lens values into components with
`Subscribable.useAll`.
`Subscribable` is the read-only side of this model. Every Lens is also a
Subscribable.
`effect-fc` re-exports the `Lens` and `Subscribable` modules from
[`effect-lens`](https://github.com/Thiladev/effect-lens) for convenience. The
core data model and transformation APIs belong to `effect-lens`, so check the
[`effect-lens` documentation](https://github.com/Thiladev/effect-lens/tree/master/packages/effect-lens) for the full Lens/Subscribable API.
## Where To Store State
State can live pretty much anywhere as a `Lens` or `Subscribable`: in a
service, in a layer, in a component scope, or alongside plain React state. Pick
the owner based on who needs the state. Once you have a Lens/Subscribable
handle, pass it around however you like, including through React props.
If state is shared by multiple components or belongs to application logic, store
it in an Effect service:
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, Subscribable } from "effect-fc"
class CounterState extends Effect.Service<CounterState>()("CounterState", {
effect: Effect.gen(function* () {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
return { count } as const
}),
}) {}
const CounterValueView = Component.make("CounterValue")(function* () {
const state = yield* CounterState
const [count] = yield* Subscribable.useAll([state.count])
return <p>Count: {count}</p>
})
```
If state belongs to a single Effect-FC component instance, or to a shallow
hierarchy of subcomponents that receive it through props, create it with
`Component.useOnMount`:
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, Subscribable } from "effect-fc"
const LocalCounterView = Component.make("LocalCounter")(function* () {
const state = yield* Component.useOnMount(() =>
Effect.gen(function* () {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
return { count } as const
}),
)
const [count] = yield* Subscribable.useAll([state.count])
return <p>Count: {count}</p>
})
```
For simple UI state that is not shared and does not need Effect integration,
prefer regular React state. A local "show details" toggle is usually better as
`React.useState(false)` than as a Lens.
## Subscribable.useAll
A `Subscribable<A>` is reactive state with a current value and a stream of
changes. Use `Subscribable.useAll` whenever a component needs to bind
subscribable values into render output.
`Lens` is a `Subscribable`, so this is also the default way to read Lens values
from a component.
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, Subscribable } from "effect-fc"
class CounterState extends Effect.Service<CounterState>()("CounterState", {
effect: Effect.gen(function* () {
const count = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(0))
const doubled = Subscribable.map(count, (n) => n * 2)
return { count, doubled } as const
}),
}) {}
const CounterReadOnlyView = Component.make("CounterReadOnly")(
function* () {
const state = yield* CounterState
const [count, doubled] = yield* Subscribable.useAll([
state.count,
state.doubled,
])
return <p>Count: {count}, doubled: {doubled}</p>
},
)
```
`Subscribable.useAll` reads the current values during render and uses scoped subscriptions to update React state when changes arrive.
When you need to modify state, write to the Lens with `Lens.set` or `Lens.update`:
```tsx
const CounterControlsView = Component.make("CounterControls")(
function* () {
const state = yield* CounterState
const [count] = yield* Subscribable.useAll([state.count])
const increment = yield* Component.useCallbackSync(
() => Lens.update(state.count, (n) => n + 1),
[],
)
const reset = yield* Component.useCallbackSync(
() => Lens.set(state.count, 0),
[],
)
return (
<section>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={reset}>Reset</button>
</section>
)
},
)
```
## Lens.useState
`Lens.useState` is useful when React needs the familiar `[value, setValue]`
tuple, backed by a Lens. Reach for it when the JSX API expects a synchronous
setter, especially controlled inputs such as text fields, checkboxes, selects,
or third-party components with `value` / `onChange` props.
If a component only needs to display the value, prefer `Subscribable.useAll`.
`Lens.useState` is for places where reading and writing need to be wired
together in React's local-state shape.
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens } from "effect-fc"
class FormState extends Effect.Service<FormState>()("FormState", {
effect: Effect.gen(function* () {
const name = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(""))
return { name } as const
}),
}) {}
const NameInputView = Component.make("NameInput")(function* () {
const state = yield* FormState
const [name, setName] = yield* Lens.useState(state.name)
return (
<input
value={name}
onChange={(event) => setName(event.currentTarget.value)}
/>
)
})
```
`Lens.useState` returns the current value and a React-compatible setter. Calling
the setter writes through the Lens, so every other component subscribed to the
same Lens sees the update.
## Focused Lenses
Use focused Lenses when a component should work with one part of a larger state
object. A focused Lens is still a Lens, so it can be read with
`Subscribable.useAll` or used with `Lens.useState` when React needs a
read/write tuple.
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens, Subscribable } from "effect-fc"
interface UserProfile {
readonly name: string
readonly email: string
readonly role: string
}
class ProfileState extends Effect.Service<ProfileState>()("ProfileState", {
effect: Effect.gen(function* () {
const profile = Lens.fromSubscriptionRef(
yield* SubscriptionRef.make<UserProfile>({
name: "",
email: "",
role: "reader",
}),
)
const name = Lens.focusObjectOn(profile, "name")
const role = Lens.focusObjectOn(profile, "role")
return { profile, name, role } as const
}),
}) {}
const ProfileNameView = Component.make("ProfileName")(function* () {
const state = yield* ProfileState
const [name, setName] = yield* Lens.useState(state.name)
const [role] = yield* Subscribable.useAll([state.role])
return (
<label>
Name
<input
value={name}
onChange={(event) => setName(event.currentTarget.value)}
/>
<span>Role: {role}</span>
</label>
)
})
```
Updating the focused `name` Lens through `Lens.useState` updates the parent
`profile` Lens. The focused `role` Lens is only read, so it stays on the simpler
`Subscribable.useAll` path.
For focusing into nested state, deriving lenses, custom write behavior, and the
complete API, refer to the
[`effect-lens` documentation](https://github.com/Thiladev/effect-lens/tree/master/packages/effect-lens).
@@ -0,0 +1,7 @@
{
"docsSidebar": [
"getting-started",
"state-management",
"forms"
]
}
+3
View File
@@ -0,0 +1,3 @@
[
"effect-fc-1.0"
]
+148
View File
@@ -0,0 +1,148 @@
<p align="center">
<a href="https://thila.dev/effect-view">
<img src="../docs/static/img/logo.svg" width="104" height="104" alt="Effect View logo" />
</a>
</p>
<h1 align="center">Effect View</h1>
<p align="center">
Write React components as typed Effect programs.
</p>
<p align="center">
<a href="https://www.npmjs.com/package/effect-view"><img src="https://img.shields.io/npm/v/effect-view?color=08777b" alt="npm version" /></a>
<a href="https://thila.dev/effect-view"><img src="https://img.shields.io/badge/docs-Effect_View-16a3a1" alt="Effect View documentation" /></a>
<a href="https://github.com/Thiladev/effect-view/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/effect-view?color=e99526" alt="MIT license" /></a>
</p>
<p align="center">
<strong><a href="https://thila.dev/effect-view">Read the documentation →</a></strong>
</p>
Effect View brings Effect's typed services, resource safety, concurrency, and
data modeling into React 19 without replacing React's component model. Yield
Effects and services from a component body, let scopes follow the React
lifecycle, and return ordinary JSX.
> **Effect v4 beta:** Effect View is built for the Effect v4 beta release. If
> your application uses Effect v3, use the legacy
> [`effect-fc` package](https://www.npmjs.com/package/effect-fc) instead.
```bash
npm install effect-view effect@beta react
```
Effect View does not depend on `react-dom`. Install the renderer used by your
application—for example, `react-dom` for the web:
```bash
npm install react-dom
```
You can use Effect View with React Native or any other React renderer instead.
## What it looks like
An Effect View component is an Effect program that produces JSX. It can create
scoped state, access services, and use React-facing hooks without leaving the
generator model:
```tsx
import { Effect, SubscriptionRef } from "effect"
import { Component, Lens } from "effect-view"
import { runtime } from "./runtime"
const CounterValueView = Component.make("CounterValue")(
function* ({ count }: { readonly count: Lens.Lens<number> }) {
yield* Component.useOnMount(() =>
Effect.addFinalizer(() =>
Effect.log("CounterValue unmounted"),
),
)
const [value, setValue] = yield* Lens.useState(count)
return (
<button onClick={() => setValue((n) => n + 1)}>
Count: {value}
</button>
)
},
)
const CounterView = Component.make("Counter")(function* () {
const count = yield* Component.useOnMount(() =>
Effect.map(
SubscriptionRef.make(0),
Lens.fromSubscriptionRef,
),
)
const CounterValue = yield* CounterValueView.use
return <CounterValue count={count} />
})
export const Counter = CounterView.pipe(
Component.withContext(runtime.context),
)
```
`CounterView` composes another Effect View component by yielding its `.use`
Effect, then renders the resulting component as ordinary JSX. The child can
access the current Effect context and receives its own component scope.
`Effect.addFinalizer` uses the scope already provided to the component body, so
the finalizer above runs when `CounterValue` unmounts.
At the outer boundary, `Counter` is still a normal React component and its Effect requirements remain
typed until they reach the runtime.
[Build the runtime and render your first component →](https://thila.dev/effect-view/docs/getting-started)
## Why Effect View
| | Capability | What it gives you |
| --- | --- | --- |
| **Effect components** | `Component.make` | Yield Effects and typed services directly, then return JSX. |
| **Managed lifecycles** | `Scope.Scope` | Finalizers, fibers, subscriptions, and resources close with their component or dependency lifecycle. |
| **One application runtime** | `ReactRuntime` | Build your Layer once and make its services available throughout the UI. |
| **Reactive state** | `Lens` and `View` | Focus large state models into small writable values and subscribe only where React needs them. |
| **Server state** | `Query` and `Mutation` | TanStack Query-style caching, invalidation, staleness, and mutations with typed Effects underneath. |
| **Schema-driven forms** | `MutationForm` and `LensForm` | Keep input-friendly encoded values while application code receives validated, decoded types. |
| **Async rendering** | `Async` and `Memoized` | Integrate asynchronous Effects with Suspense while retaining Effect errors and cancellation. |
## Designed for both ecosystems
Effect View does not hide Effect behind callbacks or recreate React around a
new rendering model. React still owns rendering, JSX, hooks, Suspense, and
events. Effect owns services, errors, resource safety, concurrency, streams,
and schemas. Effect View provides the lifecycle-aware boundary between them.
## Documentation
The complete documentation is available at **[thila.dev/effect-view](https://thila.dev/effect-view)**.
## Requirements
- React 19.2 or newer
- **Effect v4 beta** (`effect@beta`)
- TypeScript and `@types/react` for TypeScript projects
Effect View is renderer-independent and does not require `react-dom`.
## Project status
Effect View is currently beta software. The main APIs are available, but
breaking changes and rough edges are still possible before a stable release.
React Fast Refresh does not yet recognize Effect View component definitions, so
changes to them currently require a page reload; ordinary React components are
unaffected (currently being worked on).
Issues, ideas, and contributions are welcome on
[GitHub](https://github.com/Thiladev/effect-view).
## License
[MIT](https://github.com/Thiladev/effect-view/blob/main/LICENSE)
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://biomejs.dev/schemas/latest/schema.json",
"root": false,
"extends": "//",
"files": {
"includes": ["./src/**"]
}
}
+115
View File
@@ -0,0 +1,115 @@
{
"name": "effect-fc-next",
"description": "Write React function components with Effect",
"version": "0.1.0-beta.0",
"type": "module",
"files": [
"./README.md",
"./dist"
],
"license": "MIT",
"repository": {
"url": "git+https://github.com/Thiladev/effect-fc.git"
},
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./Async": {
"types": "./dist/Async.d.ts",
"default": "./dist/Async.js"
},
"./Component": {
"types": "./dist/Component.d.ts",
"default": "./dist/Component.js"
},
"./Form": {
"types": "./dist/Form.d.ts",
"default": "./dist/Form.js"
},
"./Lens": {
"types": "./dist/Lens.d.ts",
"default": "./dist/Lens.js"
},
"./LensForm": {
"types": "./dist/LensForm.d.ts",
"default": "./dist/LensForm.js"
},
"./Memoized": {
"types": "./dist/Memoized.d.ts",
"default": "./dist/Memoized.js"
},
"./Mutation": {
"types": "./dist/Mutation.d.ts",
"default": "./dist/Mutation.js"
},
"./MutationForm": {
"types": "./dist/MutationForm.d.ts",
"default": "./dist/MutationForm.js"
},
"./PubSub": {
"types": "./dist/PubSub.d.ts",
"default": "./dist/PubSub.js"
},
"./Query": {
"types": "./dist/Query.d.ts",
"default": "./dist/Query.js"
},
"./QueryClient": {
"types": "./dist/QueryClient.d.ts",
"default": "./dist/QueryClient.js"
},
"./ReactRuntime": {
"types": "./dist/ReactRuntime.d.ts",
"default": "./dist/ReactRuntime.js"
},
"./Refreshable": {
"types": "./dist/Refreshable.d.ts",
"default": "./dist/Refreshable.js"
},
"./ScopeRegistry": {
"types": "./dist/ScopeRegistry.d.ts",
"default": "./dist/ScopeRegistry.js"
},
"./SetStateAction": {
"types": "./dist/SetStateAction.d.ts",
"default": "./dist/SetStateAction.js"
},
"./Stream": {
"types": "./dist/Stream.d.ts",
"default": "./dist/Stream.js"
},
"./View": {
"types": "./dist/View.d.ts",
"default": "./dist/View.js"
}
},
"scripts": {
"lint:tsc": "tsc -b --noEmit",
"lint:biome": "biome lint",
"test": "vitest run",
"build": "tsc -b tsconfig.build.json",
"pack": "npm pack",
"clean:cache": "rm -rf .turbo *.tsbuildinfo",
"clean:dist": "rm -rf dist",
"clean:modules": "rm -rf node_modules"
},
"devDependencies": {
"@effect/platform-browser": "4.0.0-beta.98",
"@testing-library/react": "^16.3.0",
"effect": "4.0.0-beta.98",
"jsdom": "^26.1.0",
"vitest": "^3.2.4"
},
"peerDependencies": {
"@types/react": "^19.2.0",
"effect": "4.0.0-beta.98",
"react": "^19.2.0"
},
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"effect-lens": "^2.0.0-beta.1"
}
}
@@ -0,0 +1,63 @@
import { act, fireEvent, render, screen } from "@testing-library/react"
import { Effect, Layer } from "effect"
import * as React from "react"
import { describe, expect, it, vi } from "vitest"
import * as Async from "./Async.js"
import * as Component from "./Component.js"
import * as Memoized from "./Memoized.js"
import * as ReactRuntime from "./ReactRuntime.js"
describe("Async", () => {
it("does not rerun for an unrelated parent state update", async () => {
const load = vi.fn((_id: number) => Effect.never)
const renderPost = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const context = await runtime.runtime.context()
const Post = Component.make("Post")(function*(props: { readonly id: number }) {
renderPost()
const value = yield* Component.useOnChange(() => load(props.id), [props.id])
return <div>{value}</div>
}).pipe(
Async.async,
Memoized.memoized,
)
const Parent = Component.make("Parent")(function*() {
const [text, setText] = React.useState("")
const AsyncPost = yield* Post.use
return <>
<input
aria-label="text"
value={text}
onChange={event => setText(event.currentTarget.value)}
/>
<AsyncPost id={1} fallback={<div>loading</div>} />
</>
}).pipe(Component.withContext(runtime.context))
let view!: ReturnType<typeof render>
await act(async () => {
view = render(
<runtime.context.Provider value={context}>
<Parent />
</runtime.context.Provider>,
)
})
expect(screen.getByText("loading")).toBeTruthy()
expect(load).toHaveBeenCalledTimes(2)
const callsAfterLoad = load.mock.calls.length
const rendersAfterLoad = renderPost.mock.calls.length
await act(async () => {
fireEvent.change(screen.getByLabelText("text"), { target: { value: "a" } })
})
expect(load).toHaveBeenCalledTimes(callsAfterLoad)
expect(renderPost).toHaveBeenCalledTimes(rendersAfterLoad)
view.unmount()
await runtime.runtime.dispose()
})
})
+171
View File
@@ -0,0 +1,171 @@
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
import { type Context, Effect, type Equivalence, Function, Predicate, Scope } from "effect"
import * as React from "react"
import * as Component from "./Component.js"
export const AsyncTypeId: unique symbol = Symbol.for("@effect-fc/Async/Async")
export type AsyncTypeId = typeof AsyncTypeId
/**
* A trait for `Component`'s that allows them running asynchronous effects.
*/
export interface Async extends AsyncPrototype, AsyncOptions {}
export interface AsyncPrototype {
readonly [AsyncTypeId]: AsyncTypeId
}
/**
* Configuration options for `Async` components.
*/
export interface AsyncOptions {
/**
* The default fallback React node to display while the async operation is pending.
* Used if no fallback is provided to the component when rendering.
*/
readonly defaultFallback?: React.ReactNode
}
/**
* Props for `Async` components.
*/
export type AsyncProps = Omit<React.SuspenseProps, "children">
export const AsyncPrototype: AsyncPrototype = Object.freeze({
[AsyncTypeId]: AsyncTypeId,
makeFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Component.Signature>(
this: Component.Component<P, A, E, R, F> & Async,
contextRef: React.RefObject<Context.Context<Exclude<R, Scope.Scope>>>,
) {
const Inner = (props: { readonly promise: Promise<React.ReactNode> }) => React.use(props.promise)
return ({ fallback, name, ...props }: AsyncProps) => {
const promise = Effect.runPromiseWith(contextRef.current)(
Effect.flatMap(
Component.useScope([], this),
scope => Effect.provideService(this.body(props as P), Scope.Scope, scope),
)
)
return React.createElement(
React.Suspense,
{ fallback: fallback ?? this.defaultFallback, name },
React.createElement(Inner, { promise }),
)
}
},
} as const)
/**
* An equivalence function for comparing `AsyncProps` that ignores the `fallback` property.
* Used by default by async components with `Memoized.memoized` applied.
*/
export const defaultPropsEquivalence: Equivalence.Equivalence<AsyncProps> = (
self: Record<string, unknown>,
that: Record<string, unknown>,
) => {
if (self === that)
return true
for (const key in self) {
if (key === "fallback")
continue
if (!(key in that) || !Object.is(self[key], that[key]))
return false
}
for (const key in that) {
if (key === "fallback")
continue
if (!(key in self))
return false
}
return true
}
export const isAsync = (u: unknown): u is Async => Predicate.hasProperty(u, AsyncTypeId)
/**
* Converts a Component into an `Async` component that supports running asynchronous effects.
*
* Note: The component cannot have a prop named "promise" as it's reserved for internal use.
*
* @param self - The component to convert to an Async component
* @returns A new `Async` component with the same body, error, and context types as the input
*
* @example
* ```ts
* const MyAsyncComponent = MyComponent.pipe(
* Async.async,
* )
* ```
*/
export const async = <T extends Component.Component.Any>(
self: T & (
"promise" extends keyof Component.Component.Props<T>
? "The 'promise' prop name is restricted for Async components. Please rename the 'promise' prop to something else."
: T
)
): (
& Omit<T, keyof Component.Component.AsComponent<T>>
& Component.Component<
Component.Component.Props<T> & AsyncProps,
Component.Component.Success<T>,
Component.Component.Error<T>,
Component.Component.Context<T>,
Component.Component.DefaultSignature<Component.Component.Props<T> & AsyncProps, Component.Component.Success<T>>
>
& Async
) => Object.setPrototypeOf(
Object.assign(function() {}, self, { propsEquivalence: defaultPropsEquivalence }),
Object.freeze(Object.setPrototypeOf(
Object.assign({}, AsyncPrototype),
Object.getPrototypeOf(self),
)),
)
/**
* Applies options to an Async component, returning a new Async component with the updated configuration.
*
* Supports both curried and uncurried application styles.
*
* @param self - The Async component to apply options to (in uncurried form)
* @param options - The options to apply to the component
* @returns An Async component with the applied options
*
* @example
* ```ts
* // Curried
* const MyAsyncComponent = MyComponent.pipe(
* Async.async,
* Async.withOptions({ defaultFallback: <p>Loading...</p> }),
* )
*
* // Uncurried
* const MyAsyncComponent = Async.withOptions(
* Async.async(MyComponent),
* { defaultFallback: <p>Loading...</p> },
* )
* ```
*/
export const withOptions: {
<T extends Component.Component.Any & Async>(
options: Partial<AsyncOptions>
): (self: T) => T
<T extends Component.Component.Any & Async>(
self: T,
options: Partial<AsyncOptions>,
): T
} = Function.dual(2, <T extends Component.Component.Any & Async>(
self: T,
options: Partial<AsyncOptions>,
): T => Object.setPrototypeOf(
Object.assign(function() {}, self, options),
Object.getPrototypeOf(self),
))
@@ -0,0 +1,571 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"
import { Context, Effect, HashMap, Layer, SubscriptionRef } from "effect"
import * as React from "react"
import { afterEach, describe, expect, it, vi } from "vitest"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
import * as Refreshable from "./Refreshable.js"
import * as ScopeRegistry from "./ScopeRegistry.js"
class ValueService extends Context.Service<ValueService, { readonly value: string }>()("ValueService") {}
afterEach(() => {
vi.useRealTimers()
})
describe("Component", () => {
it("does not rerun useOnMount across rerenders after Strict Mode initialization", async () => {
const onMount = vi.fn(() => Effect.succeed("mounted"))
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const Probe = Component.makeUntraced("UseOnMountProbe")(function*() {
const value = yield* Component.useOnMount(onMount)
return <div>{value}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("mounted")
expect(onMount).toHaveBeenCalledTimes(2)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
expect(await screen.findByText("mounted")).toBeTruthy()
expect(onMount).toHaveBeenCalledTimes(2)
view.unmount()
await runtime.runtime.dispose()
})
it("recomputes useOnChange only when dependencies change", async () => {
const onChange = vi.fn((value: number) => Effect.succeed(`value:${value}`))
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const Probe = Component.makeUntraced("UseOnChangeProbe")(function*(props: { readonly value: number }) {
const result = yield* Component.useOnChange(() => onChange(props.value), [props.value], {
finalizerExecutionDebounce: 0,
})
return <div>{result}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value={1} />
</runtime.context.Provider>
)
await screen.findByText("value:1")
expect(onChange).toHaveBeenCalledTimes(2)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value={1} />
</runtime.context.Provider>
)
expect(await screen.findByText("value:1")).toBeTruthy()
expect(onChange).toHaveBeenCalledTimes(2)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value={2} />
</runtime.context.Provider>
)
await screen.findByText("value:2")
expect(onChange).toHaveBeenCalledTimes(4)
view.unmount()
await runtime.runtime.dispose()
})
it("closes the previous scope on dependency changes and unmount", async () => {
const cleanup = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const Probe = Component.makeUntraced("ScopeCleanupProbe")(function*(props: { readonly value: string }) {
const result = yield* Component.useOnChange(
() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
return props.value
}),
[props.value],
{ finalizerExecutionDebounce: 0 },
)
return <div>{result}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
expect(cleanup).not.toHaveBeenCalled()
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"))
expect(cleanup).toHaveBeenCalledTimes(1)
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"))
expect(cleanup).toHaveBeenCalledTimes(2)
await runtime.runtime.dispose()
})
it("runs useReactEffect setup and cleanup when dependencies change", async () => {
const lifecycle = vi.fn<(message: string) => void>()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const Probe = Component.makeUntraced("UseReactEffectProbe")(function*(props: { readonly value: string }) {
yield* Component.useReactEffect(() =>
Effect.gen(function*() {
yield* Effect.sync(() => lifecycle(`mount:${props.value}`))
yield* Effect.addFinalizer(() => Effect.sync(() => lifecycle(`cleanup:${props.value}`)))
}),
[props.value])
return <div>{props.value}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("mount:first"))
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("cleanup:first"))
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("mount:second"))
view.unmount()
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("cleanup:second"))
expect(lifecycle.mock.calls.map(([message]) => message)).toEqual([
"mount:first",
"cleanup:first",
"mount:first",
"cleanup:first",
"mount:second",
"cleanup:second",
])
await runtime.runtime.dispose()
})
it("keeps useCallbackSync stable until dependencies change", async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const seenCallbacks: Array<(value: number) => string> = []
const Probe = Component.makeUntraced("UseCallbackSyncProbe")(function*(props: { readonly prefix: string }) {
const callback = yield* Component.useCallbackSync(
(value: number) => Effect.succeed(`${props.prefix}:${value}`),
[props.prefix],
)
yield* Component.useOnMount(() => Effect.sync(() => {
seenCallbacks.push(callback)
}))
React.useEffect(() => {
seenCallbacks.push(callback)
}, [callback])
return <div>{callback(1)}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="a" />
</runtime.context.Provider>
)
await screen.findByText("a:1")
const initialLength = seenCallbacks.length
const initialCallback = seenCallbacks.at(-1)
expect(initialCallback?.(2)).toBe("a:2")
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="a" />
</runtime.context.Provider>
)
await screen.findByText("a:1")
expect(seenCallbacks).toHaveLength(initialLength)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="b" />
</runtime.context.Provider>
)
await screen.findByText("b:1")
await waitFor(() => expect(seenCallbacks.length).toBeGreaterThan(initialLength))
expect(seenCallbacks.at(-1)).not.toBe(initialCallback)
expect(seenCallbacks.at(-1)?.(2)).toBe("b:2")
view.unmount()
await runtime.runtime.dispose()
})
it("delays cleanup according to finalizerExecutionDebounce", async () => {
const cleanup = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const Probe = Component.makeUntraced("DebouncedCleanupProbe")(function*(props: { readonly value: string }) {
const result = yield* Component.useOnChange(
() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
return props.value
}),
[props.value],
{ finalizerExecutionDebounce: "20 millis" },
)
return <div>{result}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
expect(cleanup).not.toHaveBeenCalled()
await new Promise(resolve => setTimeout(resolve, 5))
expect(cleanup).not.toHaveBeenCalled()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"), { timeout: 100 })
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"), { timeout: 100 })
await runtime.runtime.dispose()
})
it("does not remount a component when only nonReactiveTags change", async () => {
const mounts = vi.fn()
const unmounts = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const SubComponent = Component.makeUntraced("NonReactiveSubComponent")(function*() {
const service = yield* ValueService
const [count, setCount] = React.useState(0)
yield* Component.useOnMount(() => Effect.gen(function*() {
yield* Effect.sync(() => mounts())
yield* Effect.addFinalizer(() => Effect.sync(() => unmounts()))
}))
return <button type="button" onClick={() => setCount(value => value + 1)}>{`${service.value}:${count}`}</button>
}).pipe(
Component.withOptions({
nonReactiveTags: [...Component.defaultOptions.nonReactiveTags, ValueService],
})
)
const Parent = Component.makeUntraced("NonReactiveParent")(function*(props: { readonly value: string }) {
const serviceLayer = React.useMemo(
() => Layer.succeed(ValueService, { value: props.value }),
[props.value],
)
const context = yield* Component.useLayer(serviceLayer, {
finalizerExecutionDebounce: 0,
})
const Child = yield* Effect.provide(SubComponent.use, context)
return <Child />
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Parent value="first" />
</runtime.context.Provider>
)
await screen.findByText("first:0")
const initialMounts = mounts.mock.calls.length
expect(initialMounts).toBeGreaterThan(0)
expect(unmounts).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole("button", { name: "first:0" }))
await screen.findByText("first:1")
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Parent value="second" />
</runtime.context.Provider>
)
await screen.findByText("second:1")
expect(mounts).toHaveBeenCalledTimes(initialMounts)
expect(unmounts).not.toHaveBeenCalled()
view.unmount()
await waitFor(() => expect(unmounts).toHaveBeenCalledTimes(1))
await runtime.runtime.dispose()
})
it("does not commit effects or retain registered scopes for a discarded Suspense render", async () => {
const setup = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
const pending = new Promise<void>(() => {})
const Probe = Component.makeUntraced("DiscardedSuspenseProbe")(function*() {
yield* Component.useReactEffect(() => Effect.sync(setup), [])
React.use(pending)
return <div>committed</div>
}).pipe(
Component.withOptions({ scopeCommitTimeout: "10 millis" }),
Component.withContext(runtime.context)
)
let view!: ReturnType<typeof render>
await act(async () => {
view = render(
<React.Suspense fallback={<div>fallback</div>}>
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
</React.Suspense>
)
})
try {
await screen.findByText("fallback")
expect(setup).not.toHaveBeenCalled()
await waitFor(() => expect(HashMap.size(Effect.runSync(SubscriptionRef.get(scopeRegistry.ref)))).toBe(0))
}
finally {
view.unmount()
await runtime.runtime.dispose()
}
})
it("keeps committed scopes alive without heartbeats", async () => {
const acquisitions = vi.fn()
const releases = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
const Probe = Component.makeUntraced("CommittedScopeProbe")(function*() {
yield* Component.useOnMount(() => Effect.gen(function*() {
yield* Effect.sync(acquisitions)
yield* Effect.addFinalizer(() => Effect.sync(releases))
}))
return <div>committed</div>
}).pipe(
Component.withOptions({
finalizerExecutionDebounce: "10 millis",
scopeCommitTimeout: "10 millis",
}),
Component.withContext(runtime.context),
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("committed")
await waitFor(() => expect(releases).toHaveBeenCalledTimes(acquisitions.mock.calls.length - 1))
await new Promise(resolve => setTimeout(resolve, 30))
expect(HashMap.size(Effect.runSync(SubscriptionRef.get(scopeRegistry.ref)))).toBe(1)
expect(releases).toHaveBeenCalledTimes(acquisitions.mock.calls.length - 1)
view.unmount()
await waitFor(() => expect(releases).toHaveBeenCalledTimes(acquisitions.mock.calls.length))
await waitFor(() => expect(HashMap.size(Effect.runSync(SubscriptionRef.get(scopeRegistry.ref)))).toBe(0))
await runtime.runtime.dispose()
})
it("does not expire a scope while a descendant is suspended past the finalizer debounce", async () => {
const runtime = ReactRuntime.make(Layer.empty)
let resolve!: () => void
const pending = new Promise<void>(complete => {
resolve = complete
})
const Suspended = () => {
React.use(pending)
return <div>committed</div>
}
let view!: ReturnType<typeof render>
await act(async () => {
view = render(
<ReactRuntime.Provider runtime={runtime} fallback={<div>fallback</div>}>
<Suspended />
</ReactRuntime.Provider>
)
})
try {
await screen.findByText("fallback")
await new Promise(resolve => setTimeout(resolve, 150))
await act(async () => {
resolve()
await pending
})
await screen.findByText("committed")
}
finally {
view.unmount()
await runtime.runtime.dispose()
}
})
it("clears ScopeRegistry after a suspended render retries, commits, and unmounts", async () => {
const lifecycle = vi.fn<(message: string) => void>()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
let resolve!: () => void
const pending = new Promise<void>(complete => {
resolve = complete
})
const Probe = Component.makeUntraced("RetriedSuspenseProbe")(function*() {
React.use(pending)
yield* Component.useReactEffect(() => Effect.gen(function*() {
yield* Effect.sync(() => lifecycle("mount"))
yield* Effect.addFinalizer(() => Effect.sync(() => lifecycle("cleanup")))
}), [])
return <div>committed</div>
}).pipe(
Component.withOptions({ scopeCommitTimeout: "10 millis" }),
Component.withContext(runtime.context)
)
let view!: ReturnType<typeof render>
await act(async () => {
view = render(
<React.Suspense fallback={<div>fallback</div>}>
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
</React.Suspense>
)
})
try {
await screen.findByText("fallback")
await act(async () => {
resolve()
await pending
})
await screen.findByText("committed")
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("mount"))
view.unmount()
await waitFor(() => expect(HashMap.size(Effect.runSync(SubscriptionRef.get(scopeRegistry.ref)))).toBe(0))
expect(lifecycle.mock.calls.filter(([message]) => message === "mount")).toHaveLength(2)
expect(lifecycle.mock.calls.filter(([message]) => message === "cleanup")).toHaveLength(2)
}
finally {
view.unmount()
await runtime.runtime.dispose()
}
})
it("refreshes a registered body while preserving or resetting local state", async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
const makeProbe = (label: string) => Component.makeUntraced("RefreshProbe")(function*() {
const [count, setCount] = React.useState(0)
return <button type="button" onClick={() => setCount(value => value + 1)}>{label}:{count}</button>
})
const original = makeProbe("old")
const cell = Refreshable.makeCell(original, "hooks", false)
Refreshable.attach(original, cell)
const Probe = Component.withContext(original, runtime.context)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
fireEvent.click(await screen.findByRole("button"))
expect(screen.getByRole("button").textContent).toBe("old:1")
await act(async () => {
cell.update(makeProbe("compatible"), "hooks", false)
await Promise.resolve()
})
expect(screen.getByRole("button").textContent).toBe("compatible:1")
await act(async () => {
cell.update(makeProbe("reset"), "changed-hooks", false)
await Promise.resolve()
})
expect(screen.getByRole("button").textContent).toBe("reset:0")
view.unmount()
await runtime.runtime.dispose()
})
})
File diff suppressed because it is too large Load Diff
+276
View File
@@ -0,0 +1,276 @@
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Array, type Cause, Chunk, type Duration, Effect, Equal, Function, identity, Option, Pipeable, Predicate, type Scope, Stream, SubscriptionRef } from "effect"
import type * as React from "react"
import * as Component from "./Component.js"
import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const FormTypeId: unique symbol = Symbol.for("@effect-fc/Form/Form")
export type FormTypeId = typeof FormTypeId
export interface Form<out P extends readonly PropertyKey[], out A, in out I = A, out ER = never, out EW = never>
extends Pipeable.Pipeable {
readonly [FormTypeId]: FormTypeId
readonly path: P
readonly value: View.View<Option.Option<A>, ER, never>
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>
readonly issues: View.View<readonly StandardSchemaV1.Issue[], never, never>
readonly isValidating: View.View<boolean, ER, never>
readonly canCommit: View.View<boolean, never, never>
readonly isCommitting: View.View<boolean, never, never>
}
export class FormImpl<out P extends readonly PropertyKey[], out A, in out I = A, out ER = never, out EW = never>
extends Pipeable.Class implements Form<P, A, I, ER, EW> {
readonly [FormTypeId]: FormTypeId = FormTypeId
constructor(
readonly path: P,
readonly value: View.View<Option.Option<A>, ER, never>,
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>,
readonly issues: View.View<readonly StandardSchemaV1.Issue[], never, never>,
readonly isValidating: View.View<boolean, never, never>,
readonly canCommit: View.View<boolean, never, never>,
readonly isCommitting: View.View<boolean, never, never>,
) {
super()
}
}
export const isForm = (u: unknown): u is Form<readonly PropertyKey[], unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, FormTypeId)
const filterIssuesByPath = (
issues: readonly StandardSchemaV1.Issue[],
path: readonly PropertyKey[],
): readonly StandardSchemaV1.Issue[] => Array.filter(issues, issue => {
const issuePath = issue.path
if (!issuePath) return false
return issuePath.length >= path.length && Array.every(path, (p, i) => p === issuePath[i])
})
export const focusObjectOn: {
<P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
self: Form<P, A, I, ER, EW>,
key: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW>
<P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
key: K,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, K], A[K], I[K], ER, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
self: Form<P, A, I, ER, EW>,
key: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, key] as const
return new FormImpl(
path,
View.mapOption(form.value, a => a[key]),
Lens.focusObjectOn(form.encodedValue, key),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export const focusArrayAt: {
<P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
self: Form<P, A, I, ER, EW>,
index: number,
): Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementError, EW | Cause.NoSuchElementError>
<P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
index: number,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementError, EW | Cause.NoSuchElementError>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
self: Form<P, A, I, ER, EW>,
index: number,
): Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementError, EW | Cause.NoSuchElementError> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOptionEffect(form.value, value => Effect.fromOption(Array.get(value, index))),
Lens.focusArrayAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export const focusTupleAt: {
<P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
self: Form<P, A, I, ER, EW>,
index: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW>
<P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
index: K,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, K], A[K], I[K], ER, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
self: Form<P, A, I, ER, EW>,
index: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOption(form.value, Array.getUnsafe(index)),
Lens.focusTupleAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export const focusChunkAt: {
<P extends readonly PropertyKey[], A, I, ER, EW>(
self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>,
index: number,
): Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementError, EW>
<P extends readonly PropertyKey[], A, I, ER, EW>(
index: number,
): (self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>) => Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementError, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A, I, ER, EW>(
self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>,
index: number,
): Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementError, EW> => {
const form = self as FormImpl<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOptionEffect(form.value, value => Effect.fromOption(Chunk.get(value, index))),
Lens.focusChunkAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export namespace useInput {
export interface Options {
readonly debounce?: Duration.Input
}
export interface Success<T> {
readonly value: T
readonly setValue: React.Dispatch<React.SetStateAction<T>>
}
}
export const useInput = Effect.fnUntraced(function* <P extends readonly PropertyKey[], A, I, ER, EW>(
form: Form<P, A, I, ER, EW>,
options?: useInput.Options,
): Effect.fn.Return<useInput.Success<I>, ER, Scope.Scope> {
const internalValueLens = yield* Component.useOnChange(() => Effect.gen(function*() {
const internalValueLens = yield* Lens.get(form.encodedValue).pipe(
Effect.flatMap(SubscriptionRef.make),
Effect.map(Lens.fromSubscriptionRef),
)
yield* Effect.forkScoped(Effect.all([
Stream.runForEach(
Stream.drop(Lens.changes(form.encodedValue), 1),
upstreamEncodedValue => Effect.when(
Lens.set(internalValueLens, upstreamEncodedValue),
Effect.map(Lens.get(internalValueLens), internalValue => !Equal.equals(upstreamEncodedValue, internalValue)),
),
),
Stream.runForEach(
Lens.changes(internalValueLens).pipe(
Stream.drop(1),
Stream.changesWith(Equal.asEquivalence()),
options?.debounce ? Stream.debounce(options.debounce) : identity,
),
internalValue => Lens.set(form.encodedValue, internalValue),
),
], { concurrency: "unbounded", discard: true }))
return internalValueLens
}), [form, options?.debounce])
const [value, setValue] = yield* Lens.useState(internalValueLens)
return { value, setValue }
})
export namespace useOptionalInput {
export interface Options<T> extends useInput.Options {
readonly defaultValue: T
}
export interface Success<T> extends useInput.Success<T> {
readonly enabled: boolean
readonly setEnabled: React.Dispatch<React.SetStateAction<boolean>>
}
}
export const useOptionalInput = Effect.fnUntraced(function* <P extends readonly PropertyKey[], A, I, ER, EW>(
field: Form<P, A, Option.Option<I>, ER, EW>,
options: useOptionalInput.Options<I>,
): Effect.fn.Return<useOptionalInput.Success<I>, ER, Scope.Scope> {
const [enabledLens, internalValueLens] = yield* Component.useOnChange(() => Effect.gen(function*() {
const [enabledLens, internalValueLens] = yield* Effect.flatMap(
Lens.get(field.encodedValue),
Option.match({
onSome: v => Effect.all([
Effect.map(SubscriptionRef.make(true), Lens.fromSubscriptionRef),
Effect.map(SubscriptionRef.make(v), Lens.fromSubscriptionRef),
]),
onNone: () => Effect.all([
Effect.map(SubscriptionRef.make(false), Lens.fromSubscriptionRef),
Effect.map(SubscriptionRef.make(options.defaultValue), Lens.fromSubscriptionRef),
]),
}),
)
yield* Effect.forkScoped(Effect.all([
Stream.runForEach(
Stream.drop(Lens.changes(field.encodedValue), 1),
upstreamEncodedValue => Effect.when(
Option.match(upstreamEncodedValue, {
onSome: v => Effect.andThen(
Lens.set(enabledLens, true),
Lens.set(internalValueLens, v),
),
onNone: () => Effect.andThen(
Lens.set(enabledLens, false),
Lens.set(internalValueLens, options.defaultValue),
),
}),
Effect.map(
Effect.all([Lens.get(enabledLens), Lens.get(internalValueLens)]),
([enabled, internalValue]) => !Equal.equals(upstreamEncodedValue, enabled ? Option.some(internalValue) : Option.none()),
),
),
),
Stream.runForEach(
Lens.changes(enabledLens).pipe(
Stream.zipLatest(internalValueLens.changes),
Stream.drop(1),
Stream.changesWith(Equal.asEquivalence()),
options?.debounce ? Stream.debounce(options.debounce) : identity,
),
([enabled, internalValue]) => Lens.set(field.encodedValue, enabled ? Option.some(internalValue) : Option.none()),
),
], { concurrency: "unbounded" }))
return [enabledLens, internalValueLens] as const
}), [field, options.debounce])
const [enabled, setEnabled] = yield* Lens.useState(enabledLens)
const [value, setValue] = yield* Lens.useState(internalValueLens)
return { enabled, setEnabled, value, setValue }
})
+171
View File
@@ -0,0 +1,171 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react"
import { Effect, Layer, SubscriptionRef } from "effect"
import * as React from "react"
import { describe, expect, it } from "vitest"
import * as Component from "./Component.js"
import * as Lens from "./Lens.js"
import * as ReactRuntime from "./ReactRuntime.js"
const makeRuntime = async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
return {
runtime,
effectRuntime,
dispose: () => runtime.runtime.dispose(),
}
}
const expectDefined = <A,>(value: A | undefined): A => {
if (value === undefined)
throw new Error("Expected value to be defined")
return value
}
describe("Lens", () => {
it("useState stays in sync with lens updates in both directions", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const ref = await Effect.runPromise(SubscriptionRef.make(0))
const lens = Lens.fromSubscriptionRef(ref)
const Probe = Component.makeUntraced("LensUseStateProbe")(function*() {
const [value, setValue] = yield* Lens.useState(lens)
return (
<>
<div>{value}</div>
<button type="button" onClick={() => setValue(previous => previous + 1)}>increment</button>
</>
)
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("0")
await Effect.runPromise(Lens.set(lens, 5))
await screen.findByText("5")
fireEvent.click(screen.getByRole("button", { name: "increment" }))
await screen.findByText("6")
expect(await Effect.runPromise(Lens.get(lens))).toBe(6)
view.unmount()
await dispose()
})
it("useState respects the provided equivalence when subscribing to lens changes", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const ref = await Effect.runPromise(SubscriptionRef.make({ id: 1, label: "first" }))
const lens = Lens.fromSubscriptionRef(ref)
const Probe = Component.makeUntraced("LensUseStateEquivalenceProbe")(function*() {
const [value] = yield* Lens.useState(lens, {
equivalence: (self, that) => self.id === that.id,
})
return <div>{value.label}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first")
await Effect.runPromise(Lens.set(lens, { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first")).toBeTruthy())
expect(screen.queryByText("ignored")).toBeNull()
await Effect.runPromise(Lens.set(lens, { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
await dispose()
})
it("useFromReactState writes React state changes into the returned lens", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
let lens: Lens.Lens<string, never, never, never, never> | undefined
const Probe = Component.makeUntraced("LensUseFromReactStateProbe")(function*() {
const [value, setValue] = React.useState("hello")
const reactLens = yield* Lens.useFromReactState([value, setValue])
yield* Component.useOnMount(() => Effect.sync(() => {
lens = reactLens
}))
return <button type="button" onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("hello")
await waitFor(() => expect(lens).toBeDefined())
fireEvent.click(screen.getByRole("button", { name: "hello" }))
await screen.findByText("hello!")
await waitFor(async () => expect(await Effect.runPromise(Lens.get(expectDefined(lens)))).toBe("hello!"))
view.unmount()
await dispose()
})
it("useFromReactState respects equivalence when lens updates flow back into React state", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
let lens: Lens.Lens<{ readonly id: number; readonly label: string }, never, never, never, never> | undefined
const Probe = Component.makeUntraced("LensUseFromReactStateEquivalenceProbe")(function*() {
const [value, setValue] = React.useState({ id: 1, label: "first" })
const reactLens = yield* Lens.useFromReactState([value, setValue], {
equivalence: (self, that) => self.id === that.id,
})
yield* Component.useOnMount(() => Effect.sync(() => {
lens = reactLens
}))
return <div>{value.label}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first")
await waitFor(() => expect(lens).toBeDefined())
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first")).toBeTruthy())
expect(screen.queryByText("ignored")).toBeNull()
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
await dispose()
})
})
+62
View File
@@ -0,0 +1,62 @@
import { Effect, Equivalence, Stream, SubscriptionRef } from "effect"
import { Lens } from "effect-lens"
import * as React from "react"
import * as Component from "./Component.js"
import * as SetStateAction from "./SetStateAction.js"
export * from "effect-lens/Lens"
export declare namespace useState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useState = Effect.fnUntraced(function* <A, ER, EW, RR, RW>(
lens: Lens.Lens<A, ER, EW, RR, RW>,
options?: useState.Options<NoInfer<A>>,
): Effect.fn.Return<readonly [A, React.Dispatch<React.SetStateAction<A>>], ER | EW, RR | RW> {
const [reactStateValue, setReactStateValue] = React.useState(yield* Component.useOnMount(() => Lens.get(lens)))
yield* Component.useReactEffect(() => Effect.forkScoped(
Stream.runForEach(
Stream.changesWith(lens.changes, options?.equivalence ?? Equivalence.strictEqual()),
v => Effect.sync(() => setReactStateValue(v)),
)
), [lens])
const setValue = yield* Component.useCallbackSync(
(setStateAction: React.SetStateAction<A>) => Effect.tap(
Lens.updateAndGet(lens, prevState => SetStateAction.value(setStateAction, prevState)),
v => Effect.sync(() => setReactStateValue(v)),
),
[lens],
)
return [reactStateValue, setValue]
})
export declare namespace useFromReactState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useFromReactState = Effect.fnUntraced(function* <A>(
[value, setValue]: readonly [A, React.Dispatch<React.SetStateAction<A>>],
options?: useFromReactState.Options<NoInfer<A>>,
): Effect.fn.Return<Lens.Lens<A, never, never, never, never>> {
const lens = yield* Component.useOnMount(() => Effect.map(
SubscriptionRef.make(value),
Lens.fromSubscriptionRef,
))
yield* Component.useReactEffect(() => Effect.forkScoped(Stream.runForEach(
Stream.changesWith(lens.changes, options?.equivalence ?? Equivalence.strictEqual()),
v => Effect.sync(() => setValue(v)),
)), [setValue])
yield* Component.useReactEffect(() => Lens.set(lens, value), [value])
return lens
})
+206
View File
@@ -0,0 +1,206 @@
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Array, type Context, Effect, Equal, Fiber, Option, Pipeable, Predicate, Schema, SchemaIssue, type Scope, Semaphore, Stream, SubscriptionRef } from "effect"
import * as Form from "./Form.js"
import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const LensFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/LensForm")
export type LensFormTypeId = typeof LensFormTypeId
export interface LensForm<in out A, in out I = A, in out RD = never, in out RE = never, out TER = never, out TEW = never, in out TRR = never, in out TRW = never>
extends Form.Form<readonly [], A, I, TER, TER | TEW> {
readonly [LensFormTypeId]: LensFormTypeId
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>
readonly context: Context.Context<Scope.Scope | RD | RE | TRR | TRW>
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>
readonly validationFiber: View.View<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never>
readonly run: Effect.Effect<void, TER>
}
export class LensFormImpl<in out A, in out I = A, in out RD = never, in out RE = never, out TER = never, out TEW = never, in out TRR = never, in out TRW = never>
extends Pipeable.Class implements LensForm<A, I, RD, RE, TER, TEW, TRR, TRW> {
readonly [Form.FormTypeId]: Form.FormTypeId = Form.FormTypeId
readonly [LensFormTypeId]: LensFormTypeId = LensFormTypeId
readonly path = [] as const
readonly value: View.View<Option.Option<A>, never, never>
readonly encodedValue: Lens.Lens<I, TER, TER | TEW, never, never>
readonly isValidating: View.View<boolean, never, never>
readonly canCommit: View.View<boolean, never, never>
constructor(
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>,
readonly context: Context.Context<Scope.Scope | RD | RE | TRR | TRW>,
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>,
readonly internalEncodedValue: Lens.Lens<I, never, never, never, never>,
readonly issues: Lens.Lens<readonly StandardSchemaV1.Issue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never, never, never>,
readonly isCommitting: Lens.Lens<boolean, never, never>,
readonly runSemaphore: Semaphore.Semaphore,
) {
super()
this.value = Effect.succeed(this).pipe(
Effect.map(self => View.make({
get: Effect.provide(Effect.option(self.target.get), self.context),
get changes() {
return Stream.provideContext(
self.target.changes.pipe(
Stream.map(Option.some),
Stream.catch(() => Stream.make(Option.none())),
),
self.context,
)
},
})),
View.unwrap,
)
this.encodedValue = Effect.all([
Effect.succeed(this),
Effect.succeed(Lens.asLensImpl(this.internalEncodedValue)),
]).pipe(
Effect.map(([self, parent]) => Lens.make({
get: parent.get,
get changes() { return parent.changes },
commit: a => Effect.andThen(
Effect.flatMap(
parent.resolve,
resolved => resolved.commit(Effect.succeed(a)),
),
self.synchronizeEncodedValue(a),
),
lock: parent.lock,
})),
Lens.unwrap,
)
this.isValidating = Effect.succeed(this).pipe(
Effect.map(self => View.map(self.validationFiber, Option.isSome)),
View.unwrap,
)
this.canCommit = Effect.succeed(this).pipe(
Effect.map(self => View.map(
View.zipLatestAll(self.issues, self.validationFiber, self.isCommitting),
([issues, validationFiber, isCommitting]) => (
Array.isReadonlyArrayEmpty(issues) &&
Option.isNone(validationFiber) &&
!isCommitting
),
)),
View.unwrap,
)
}
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void, TER | TEW, never> {
return Lens.get(this.validationFiber).pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(Effect.forkScoped(
Effect.ensuring(
Schema.decodeEffect(this.schema, { errors: "all" })(encodedValue),
Lens.set(this.validationFiber, Option.none()),
)
)),
Effect.tap(fiber => Lens.set(this.validationFiber, Option.some(fiber))),
Effect.flatMap(Fiber.join),
Effect.flatMap(value => Effect.ensuring(
Lens.set(this.isCommitting, true).pipe(
Effect.andThen(Lens.set(this.issues, Array.empty())),
Effect.andThen(Lens.set(this.target, value)),
),
Lens.set(this.isCommitting, false),
)),
Effect.catchIf(
Schema.isSchemaError,
error => Lens.set(this.issues, SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues),
),
Effect.provide(this.context),
)
}
get run(): Effect.Effect<void, TER, never> {
return this.runSemaphore.withPermits(1)(Effect.provide(
Stream.runForEach(
Stream.drop(Lens.changes(this.target), 1),
targetValue => Schema.encodeEffect(this.schema, { errors: "all" })(targetValue).pipe(
Effect.flatMap(encodedValue => Effect.when(
Effect.andThen(
Lens.set(this.issues, Array.empty()),
Lens.set(this.internalEncodedValue, encodedValue),
),
Effect.map(
Lens.get(this.internalEncodedValue),
currentEncodedValue => !Equal.equals(encodedValue, currentEncodedValue),
),
)),
Effect.ignore,
),
),
this.context,
))
}
}
export const isLensForm = (u: unknown): u is LensForm<unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, LensFormTypeId)
export declare namespace make {
export interface Options<in out A, out I = A, out RD = never, out RE = never, out TER = never, out TEW = never, out TRR = never, out TRW = never> {
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>
readonly initialEncodedValue?: NoInfer<I>
}
}
export const make = Effect.fnUntraced(function* <A, I = A, RD = never, RE = never, TER = never, TEW = never, TRR = never, TRW = never>(
options: make.Options<A, I, RD, RE, TER, TEW, TRR, TRW>
): Effect.fn.Return<
LensForm<A, I, RD, RE, TER, TEW, TRR, TRW>,
Schema.SchemaError | TER,
Scope.Scope | RD | RE | TRR | TRW
> {
const initialEncodedValue = options.initialEncodedValue !== undefined
? options.initialEncodedValue
: yield* Effect.flatMap(
Lens.get(options.target),
Schema.encodeEffect(options.schema),
)
return new LensFormImpl(
options.schema,
yield* Effect.context<Scope.Scope | RD | RE | TRR | TRW>(),
options.target,
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(initialEncodedValue)),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly StandardSchemaV1.Issue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, Schema.SchemaError>>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(false)),
yield* Semaphore.make(1),
)
})
export declare namespace service {
export interface Options<in out A, out I = A, out RD = never, out RE = never, out TER = never, out TEW = never, out TRR = never, out TRW = never>
extends make.Options<A, I, RD, RE, TER, TEW, TRR, TRW> {}
}
export const service = <A, I = A, RD = never, RE = never, TER = never, TEW = never, TRR = never, TRW = never>(
options: service.Options<A, I, RD, RE, TER, TEW, TRR, TRW>
): Effect.Effect<
LensForm<A, I, RD, RE, TER, TEW, TRR, TRW>,
Schema.SchemaError | TER,
Scope.Scope | RD | RE | TRR | TRW
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)
+112
View File
@@ -0,0 +1,112 @@
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
import { type Equivalence, Function, Predicate } from "effect"
import * as React from "react"
import type * as Component from "./Component.js"
export const MemoizedTypeId: unique symbol = Symbol.for("@effect-fc/Memoized/Memoized")
export type MemoizedTypeId = typeof MemoizedTypeId
/**
* A trait for `Component`'s that uses `React.memo` to optimize re-renders based on prop equality.
*
* @template P The props type of the component
*/
export interface Memoized<P> extends MemoizedPrototype, MemoizedOptions<P> {}
export interface MemoizedPrototype {
readonly [MemoizedTypeId]: MemoizedTypeId
}
/**
* Configuration options for Memoized components.
*
* @template P The props type of the component
*/
export interface MemoizedOptions<P> {
/**
* An optional equivalence function for comparing component props.
* If provided, this function is used by React.memo to determine if props have changed.
* Returns `true` if props are equivalent (no re-render), `false` if they differ (re-render).
*/
readonly propsEquivalence?: Equivalence.Equivalence<P>
}
export const MemoizedPrototype: MemoizedPrototype = Object.freeze({
[MemoizedTypeId]: MemoizedTypeId,
transformFunctionComponent<P extends {}>(
this: Memoized<P>,
f: React.FC<P>,
) {
return React.memo(f, this.propsEquivalence)
},
} as const)
export const isMemoized = (u: unknown): u is Memoized<unknown> => Predicate.hasProperty(u, MemoizedTypeId)
/**
* Converts a Component into a `Memoized` component that optimizes re-renders using `React.memo`.
*
* @param self - The component to convert to a Memoized component
* @returns A new `Memoized` component with the same body, error, and context types as the input
*
* @example
* ```ts
* const MyMemoizedComponent = MyComponent.pipe(
* Memoized.memoized,
* )
* ```
*/
export const memoized = <T extends Component.Component.Any>(
self: T
): T & Memoized<Component.Component.Props<T>> => Object.setPrototypeOf(
Object.assign(function() {}, self),
Object.freeze(Object.setPrototypeOf(
Object.assign({}, MemoizedPrototype),
Object.getPrototypeOf(self),
)),
)
/**
* Applies options to a Memoized component, returning a new Memoized component with the updated configuration.
*
* Supports both curried and uncurried application styles.
*
* @param self - The Memoized component to apply options to (in uncurried form)
* @param options - The options to apply to the component
* @returns A Memoized component with the applied options
*
* @example
* ```ts
* // Curried
* const MyMemoizedComponent = MyComponent.pipe(
* Memoized.memoized,
* Memoized.withOptions({ propsEquivalence: (a, b) => a.id === b.id }),
* )
*
* // Uncurried
* const MyMemoizedComponent = Memoized.withOptions(
* Memoized.memoized(MyComponent),
* { propsEquivalence: (a, b) => a.id === b.id },
* )
* ```
*/
export const withOptions: {
<T extends Component.Component.Any & Memoized<any>>(
options: Partial<MemoizedOptions<Component.Component.Props<T>>>
): (self: T) => T
<T extends Component.Component.Any & Memoized<any>>(
self: T,
options: Partial<MemoizedOptions<Component.Component.Props<T>>>,
): T
} = Function.dual(2, <T extends Component.Component.Any & Memoized<any>>(
self: T,
options: Partial<MemoizedOptions<Component.Component.Props<T>>>,
): T => Object.setPrototypeOf(
Object.assign(function() {}, self, options),
Object.getPrototypeOf(self),
))
+153
View File
@@ -0,0 +1,153 @@
import { type Context, Effect, Equal, Exit, type Fiber, Option, Pipeable, Predicate, type Scope, Stream, SubscriptionRef } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const MutationTypeId: unique symbol = Symbol.for("@effect-fc/Mutation/Mutation")
export type MutationTypeId = typeof MutationTypeId
export interface Mutation<in out K, out A, out E = never, in out R = never>
extends Pipeable.Pipeable {
readonly [MutationTypeId]: MutationTypeId
readonly context: Context.Context<Scope.Scope | R>
readonly f: (key: K) => Effect.Effect<A, E, R>
readonly latestKey: View.View<Option.Option<K>>
readonly fiber: View.View<Option.Option<Fiber.Fiber<A, E>>>
readonly state: View.View<AsyncResult.AsyncResult<A, E>>
readonly latestFinalResult: View.View<Option.Option<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>>>
mutate(key: K): Effect.Effect<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>>
mutateView(key: K): Effect.Effect<View.View<AsyncResult.AsyncResult<A, E>>>
}
export const isMutation = (u: unknown): u is Mutation<unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, MutationTypeId)
export class MutationImpl<in out K, in out A, in out E = never, in out R = never>
extends Pipeable.Class implements Mutation<K, A, E, R> {
readonly [MutationTypeId]: MutationTypeId = MutationTypeId
constructor(
readonly context: Context.Context<Scope.Scope | R>,
readonly f: (key: K) => Effect.Effect<A, E, R>,
readonly latestKey: Lens.Lens<Option.Option<K>>,
readonly fiber: Lens.Lens<Option.Option<Fiber.Fiber<A, E>>>,
readonly state: Lens.Lens<AsyncResult.AsyncResult<A, E>>,
readonly latestFinalResult: Lens.Lens<Option.Option<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>>>,
) {
super()
}
mutate(key: K): Effect.Effect<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>> {
return Lens.set(this.latestKey, Option.some(key)).pipe(
Effect.andThen(this.start(key)),
Effect.flatMap(state => this.watch(state)),
Effect.provide(this.context),
)
}
mutateView(key: K): Effect.Effect<View.View<AsyncResult.AsyncResult<A, E>>> {
return Lens.set(this.latestKey, Option.some(key)).pipe(
Effect.andThen(this.start(key)),
Effect.tap(state => Effect.forkScoped(this.watch(state))),
Effect.provide(this.context),
)
}
start(key: K): Effect.Effect<
View.View<AsyncResult.AsyncResult<A, E>>,
never,
Scope.Scope | R
> {
return Effect.gen({ self: this }, function*() {
const previous = yield* Lens.get(this.latestFinalResult)
const state = Lens.fromSubscriptionRef(yield* SubscriptionRef.make<AsyncResult.AsyncResult<A, E>>(
Option.getOrElse(previous, () => AsyncResult.initial(false))
))
const fiber = yield* Effect.forkScoped(Effect.andThen(
Lens.update(state, AsyncResult.match({
onInitial: () => AsyncResult.initial(true),
onSuccess: v => AsyncResult.success(v.value, {
waiting: true,
}),
onFailure: v => AsyncResult.failure(v.cause, {
waiting: true,
previousSuccess: v.previousSuccess,
})
})),
Effect.onExit(this.f(key), exit => Lens.update(
state,
previous => Exit.match(exit, {
onSuccess: v => AsyncResult.success(v),
onFailure: c => AsyncResult.match(previous, {
onInitial: () => AsyncResult.failure(c),
onSuccess: v => AsyncResult.failure(c, {
previousSuccess: Option.some(v),
}),
onFailure: v => AsyncResult.failure(c, {
previousSuccess: v.previousSuccess,
})
}),
}),
).pipe(
Effect.andThen(Effect.all([
Effect.fiberId,
Lens.get(this.fiber),
])),
Effect.flatMap(([fiberId, fiber]) => Option.match(fiber, {
onSome: v => Equal.equals(fiberId, v.id)
? Lens.set(this.fiber, Option.none())
: Effect.void,
onNone: () => Effect.void,
})),
)),
))
yield* Lens.set(this.fiber, Option.some(fiber))
return state
})
}
watch(
state: View.View<AsyncResult.AsyncResult<A, E>>
): Effect.Effect<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>> {
return View.get(state).pipe(
Effect.andThen(initial => Stream.runFoldEffect(
View.changes(state),
() => initial,
(_, result) => Effect.as(Lens.set(this.state, result), result),
) as Effect.Effect<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>>),
Effect.tap(result => Lens.set(this.latestFinalResult, Option.some(result))),
)
}
}
export declare namespace make {
export interface Options<K = never, A = void, E = never, R = never> {
readonly f: (key: K) => Effect.Effect<A, E, R>
}
}
export const make = Effect.fnUntraced(function* <K = never, A = void, E = never, R = never>(
options: make.Options<K, A, E, R>
): Effect.fn.Return<
Mutation<K, A, E, R>,
never,
Scope.Scope | R
> {
return new MutationImpl(
yield* Effect.context<Scope.Scope | R>(),
options.f,
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<K>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, E>>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>>())),
)
})
+213
View File
@@ -0,0 +1,213 @@
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Array, Cause, type Context, Effect, Fiber, Option, Pipeable, Predicate, Schema, SchemaError, SchemaIssue, type Scope, Semaphore, SubscriptionRef } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import * as Form from "./Form.js"
import * as Lens from "./Lens.js"
import * as Mutation from "./Mutation.js"
import * as View from "./View.js"
export const MutationFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/MutationForm")
export type MutationFormTypeId = typeof MutationFormTypeId
export interface MutationForm<in out A, in out I = A, in out RD = never, in out RE = never, out MA = void, out ME = never, in out MR = never>
extends Form.Form<readonly [], A, I, never, never> {
readonly [MutationFormTypeId]: MutationFormTypeId
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>
readonly context: Context.Context<Scope.Scope | RD | RE>
readonly mutation: Mutation.Mutation<
readonly [value: A, form: MutationForm<A, I, RD, RE, unknown, unknown, unknown>],
MA, ME, MR
>
readonly validationFiber: View.View<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never>
readonly run: Effect.Effect<void>
readonly submit: Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, Cause.NoSuchElementError>
}
export class MutationFormImpl<in out A, in out I = A, in out RD = never, in out RE = never, out MA = void, out ME = never, in out MR = never>
extends Pipeable.Class implements MutationForm<A, I, RD, RE, MA, ME, MR> {
readonly [Form.FormTypeId]: Form.FormTypeId = Form.FormTypeId
readonly [MutationFormTypeId]: MutationFormTypeId = MutationFormTypeId
readonly path = [] as const
readonly encodedValue: Lens.Lens<I, never, never, never, never>
readonly isValidating: View.View<boolean, never, never>
readonly canCommit: View.View<boolean, never, never>
readonly isCommitting: View.View<boolean, never, never>
constructor(
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>,
readonly context: Context.Context<Scope.Scope | RD | RE>,
readonly mutation: Mutation.Mutation<
readonly [value: A, form: MutationForm<A, I, RD, RE, unknown, unknown, unknown>],
MA, ME, MR
>,
readonly value: Lens.Lens<Option.Option<A>, never, never, never, never>,
readonly internalEncodedValue: Lens.Lens<I, never, never, never, never>,
readonly issues: Lens.Lens<readonly StandardSchemaV1.Issue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never, never, never>,
readonly runSemaphore: Semaphore.Semaphore,
) {
super()
this.encodedValue = Effect.all([
Effect.succeed(this),
Effect.succeed(Lens.asLensImpl(this.internalEncodedValue)),
]).pipe(
Effect.map(([self, parent]) => Lens.make({
get: parent.get,
get changes() { return parent.changes },
commit: a => Effect.andThen(
Effect.flatMap(
parent.resolve,
resolved => resolved.commit(Effect.succeed(a)),
),
self.synchronizeEncodedValue(a),
),
lock: parent.lock,
})),
Lens.unwrap,
)
this.isValidating = Effect.succeed(this).pipe(
Effect.map(self => View.map(self.validationFiber, Option.isSome)),
View.unwrap,
)
this.canCommit = Effect.succeed(this).pipe(
Effect.map(self => View.map(
View.zipLatestAll(self.value, self.issues, self.validationFiber, self.mutation.state),
([value, issues, validationFiber, result]) => (
Option.isSome(value) &&
Array.isReadonlyArrayEmpty(issues) &&
Option.isNone(validationFiber) &&
!AsyncResult.isWaiting(result)
),
)),
View.unwrap,
)
this.isCommitting = Effect.succeed(this).pipe(
Effect.map(self => View.map(self.mutation.state, AsyncResult.isWaiting)),
View.unwrap,
)
}
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void, never, never> {
return Lens.get(this.validationFiber).pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(Effect.forkScoped(
Effect.ensuring(
Schema.decodeEffect(this.schema, { errors: "all" })(encodedValue),
Lens.set(this.validationFiber, Option.none()),
)
)),
Effect.tap(fiber => Lens.set(this.validationFiber, Option.some(fiber))),
Effect.flatMap(Fiber.join),
Effect.tap(() => Lens.set(this.issues, Array.empty())),
Effect.flatMap(value => Lens.set(this.value, Option.some(value))),
Effect.catchIf(
SchemaError.isSchemaError,
error => Lens.set(this.issues, SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues),
),
Effect.provide(this.context),
)
}
get run(): Effect.Effect<void, never, never> {
return Lens.get(this.encodedValue).pipe(
Effect.flatMap(v => Schema.decodeEffect(this.schema)(v)),
Effect.option,
Effect.flatMap(v => Lens.set(this.value, v)),
Effect.provide(this.context),
this.runSemaphore.withPermits(1),
)
}
get submit(): Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, Cause.NoSuchElementError, never> {
return Lens.get(this.value).pipe(
Effect.flatMap(Effect.fromOption),
Effect.flatMap(value => this.submitValue(value)),
)
}
submitValue(value: A): Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, never, never> {
return Effect.when(
Effect.tap(
this.mutation.mutate([value, this as any]),
result => AsyncResult.isFailure(result)
? Option.match(
Array.findFirst(
result.cause.reasons,
reason => Cause.isFailReason(reason) && SchemaError.isSchemaError(reason.error)
? Option.some(reason.error)
: Option.none(),
),
{
onSome: error => Lens.set(this.issues, SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues),
onNone: () => Effect.void,
},
)
: Effect.void,
),
View.get(this.canCommit),
)
}
}
export const isMutationForm = (u: unknown): u is MutationForm<unknown, unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, MutationFormTypeId)
export declare namespace make {
export interface Options<in out A, in out I = A, in out RD = never, in out RE = never, out MA = void, out ME = never, out MR = never>
extends Mutation.make.Options<
readonly [value: NoInfer<A>, form: MutationForm<NoInfer<A>, NoInfer<I>, NoInfer<RD>, NoInfer<RE>, unknown, unknown, unknown>],
MA, ME, MR
> {
readonly schema: Schema.ConstraintCodec<A, I, RD, RE>
readonly initialEncodedValue: NoInfer<I>
}
}
export const make = Effect.fnUntraced(function* <A, I = A, RD = never, RE = never, MA = void, ME = never, MR = never>(
options: make.Options<A, I, RD, RE, MA, ME, MR>
): Effect.fn.Return<
MutationForm<A, I, RD, RE, MA, ME, MR>,
never,
Scope.Scope | RD | RE | MR
> {
return new MutationFormImpl(
options.schema,
yield* Effect.context<Scope.Scope | RD | RE | MR>(),
yield* Mutation.make(options),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<A>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(options.initialEncodedValue)),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly StandardSchemaV1.Issue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, Schema.SchemaError>>())),
yield* Semaphore.make(1),
)
})
export declare namespace service {
export interface Options<in out A, in out I = A, in out RD = never, in out RE = never, out MA = void, out ME = never, out MR = never>
extends make.Options<A, I, RD, RE, MA, ME, MR> {}
}
export const service = <A, I = A, RD = never, RE = never, MA = void, ME = never, MR = never>(
options: service.Options<A, I, RD, RE, MA, ME, MR>
): Effect.Effect<
MutationForm<A, I, RD, RE, MA, ME, MR>,
never,
Scope.Scope | RD | RE | MR
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)
+17
View File
@@ -0,0 +1,17 @@
import { Effect, PubSub, type Scope } from "effect"
import type * as React from "react"
import * as Component from "./Component.js"
export * from "effect/PubSub"
export const useFromReactiveValues = Effect.fnUntraced(function* <const A extends React.DependencyList>(
values: A
): Effect.fn.Return<PubSub.PubSub<A>, never, Scope.Scope> {
const pubsub = yield* Component.useOnMount(() => Effect.acquireRelease(PubSub.unbounded<A>(), PubSub.shutdown))
yield* Component.useReactEffect(() => Effect.flatMap(
PubSub.isShutdown(pubsub),
shutdown => shutdown ? Effect.succeed(undefined) : Effect.asVoid(PubSub.publish(pubsub, values)),
), values)
return pubsub
})
+167
View File
@@ -0,0 +1,167 @@
import { Effect, type Scope, Stream } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import { describe, expect, it } from "vitest"
import * as Query from "./Query.js"
import * as QueryClient from "./QueryClient.js"
import * as View from "./View.js"
const runQueryTest = <A, E>(effect: Effect.Effect<A, E, QueryClient.QueryClient | Scope.Scope>) =>
Effect.runPromise(Effect.scoped(effect.pipe(
Effect.provide(QueryClient.layer()),
)))
const staticKey = <K>(key: K): View.View<K> => View.make({
get: Effect.succeed(key),
changes: Stream.make(key),
})
const expectSuccessValue = <A, E>(
state: Query.FinalQueryState<unknown, A, E>,
): A => {
expect(AsyncResult.isSuccess(state.result)).toBe(true)
if (!AsyncResult.isSuccess(state.result))
throw new Error(`Expected Success result, received ${state.result._tag}`)
return state.result.value
}
describe("Query", () => {
it("fetch caches successful results until they are invalidated or stale", async () => {
let calls = 0
const key = staticKey<readonly [number]>([1])
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(1)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:1")
})
it("refresh reruns the latest query key", async () => {
let calls = 0
const key = staticKey<readonly [number]>([1])
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "0 millis",
})
const first = yield* query.fetch([1])
yield* Effect.sleep("1 millis")
const refreshed = yield* query.refresh
return [first, refreshed] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("invalidateCacheEntry forces the next fetch for that key to rerun", async () => {
let calls = 0
const key = staticKey<readonly [number]>([1])
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
yield* query.invalidateCacheEntry([1])
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("invalidateCache clears cached entries for the query function", async () => {
let calls = 0
const key = staticKey<readonly [number]>([1])
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
yield* query.invalidateCache
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("service starts the key view automatically and records its latest final state", async () => {
let calls = 0
const key = staticKey<readonly [number]>([1])
const effect = Effect.gen(function*() {
const query = yield* Query.service({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const latestFinalState = yield* Effect.sleep("1 millis").pipe(
Effect.andThen(View.get(query.latestFinalState)),
Effect.flatMap(Effect.fromOption),
Effect.eventually,
Effect.timeout("1 second"),
)
return {
state: yield* View.get(query.state),
latestFinalState,
}
})
const result = await runQueryTest(effect)
expect(calls).toBe(1)
expect(result.state.key).toEqual([1])
expect(expectSuccessValue(result.latestFinalState)).toBe("value:1:1")
})
})
+463
View File
@@ -0,0 +1,463 @@
import { Cause, type Context, Duration, Effect, Equal, type Equivalence, Exit, Fiber, Option, Pipeable, Predicate, PubSub, Ref, type Scope, Semaphore, Stream, SubscriptionRef } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import * as Lens from "./Lens.js"
import * as QueryClient from "./QueryClient.js"
import * as View from "./View.js"
export const QueryTypeId: unique symbol = Symbol.for("@effect-fc/Query/Query")
export type QueryTypeId = typeof QueryTypeId
export interface Query<in out K, out A, out E = never, in out R = never>
extends Pipeable.Pipeable {
readonly [QueryTypeId]: QueryTypeId
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | R>
readonly key: View.View<K>
readonly keyEquivalence: Equivalence.Equivalence<K>
readonly f: (key: K) => Effect.Effect<A, E, R>
readonly staleTime: Duration.Duration
readonly refreshOnWindowFocus: boolean
readonly fiber: View.View<Option.Option<Fiber.Fiber<A, E>>>
readonly state: View.View<QueryState<K, A, E>>
readonly latestFinalState: View.View<Option.Option<FinalQueryState<K, A, E>>>
readonly run: Effect.Effect<void>
fetch(key: K): Effect.Effect<FinalQueryState<K, A, E>, Cause.NoSuchElementError>
fetchView(key: K): Effect.Effect<View.View<QueryState<K, A, E>>, Cause.NoSuchElementError>
readonly refresh: Effect.Effect<FinalQueryState<K, A, E>, Cause.NoSuchElementError>
readonly refreshView: Effect.Effect<View.View<QueryState<K, A, E>>, Cause.NoSuchElementError>
readonly invalidateCache: Effect.Effect<void>
invalidateCacheEntry(key: K): Effect.Effect<void>
}
export interface QueryState<out K, out A, out E = never> {
readonly key: K
readonly result: AsyncResult.AsyncResult<A, E>
}
export interface FinalQueryState<out K, out A, out E = never> {
readonly key: K
readonly result: AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>
}
export const isQuery = (u: unknown): u is Query<unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, QueryTypeId)
export class QueryImpl<in out K, in out A, in out E = never, in out R = never>
extends Pipeable.Class implements Query<K, A, E, R> {
readonly [QueryTypeId]: QueryTypeId = QueryTypeId
constructor(
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | R>,
readonly key: View.View<K>,
readonly keyEquivalence: Equivalence.Equivalence<K>,
readonly f: (key: K) => Effect.Effect<A, E, R>,
readonly staleTime: Duration.Duration,
readonly refreshOnWindowFocus: boolean,
readonly fiber: Lens.Lens<Option.Option<Fiber.Fiber<A, E>>>,
readonly state: Lens.Lens<QueryState<K, A, E>>,
readonly latestFinalState: Lens.Lens<Option.Option<FinalQueryState<K, A, E>>>,
readonly runSemaphore: Semaphore.Semaphore,
) {
super()
}
get run(): Effect.Effect<void> {
return Effect.all([
Stream.runForEach(
this.key.changes,
key => Effect.gen({ self: this }, function*() {
yield* this.interrupt
const latestFinalState = yield* Lens.get(this.latestFinalState)
const state = yield* this.startCached(
Option.isSome(latestFinalState) && this.keyEquivalence(key, latestFinalState.value.key)
? latestFinalState.value
: {
key,
result: AsyncResult.initial(false),
}
)
yield* Effect.forkScoped(this.watch(state))
}),
),
Effect.promise(() => import("@effect/platform-browser")).pipe(
Effect.flatMap(({ BrowserStream }) => this.refreshOnWindowFocus
? Stream.runForEach(
BrowserStream.fromEventListenerWindow("focus"),
() => this.refreshView,
)
: Effect.void
),
Effect.catchDefect(() => Effect.void),
),
], { concurrency: "unbounded" }).pipe(
Effect.ignore,
this.runSemaphore.withPermits(1),
Effect.provide(this.context),
)
}
get interrupt(): Effect.Effect<void> {
return Effect.flatMap(Lens.get(this.fiber), Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
}))
}
fetch(key: K): Effect.Effect<FinalQueryState<K, A, E>, Cause.NoSuchElementError> {
return Effect.gen({ self: this }, function*() {
yield* this.interrupt
const state = yield* this.startCached({
key,
result: AsyncResult.initial(false),
})
return yield* this.watch(state)
}).pipe(
Effect.provide(this.context),
)
}
fetchView(key: K): Effect.Effect<
View.View<QueryState<K, A, E>>,
Cause.NoSuchElementError
> {
return Effect.gen({ self: this }, function*() {
yield* this.interrupt
const state = yield* this.startCached({
key,
result: AsyncResult.initial(false),
})
yield* Effect.forkScoped(this.watch(state))
return state
}).pipe(
Effect.provide(this.context),
)
}
get refresh(): Effect.Effect<FinalQueryState<K, A, E>, Cause.NoSuchElementError> {
return Effect.gen({ self: this }, function*() {
yield* this.interrupt
const latestState = yield* Lens.get(this.state)
const latestFinalState = yield* Lens.get(this.latestFinalState)
const state = yield* this.startCached(
Option.isSome(latestFinalState) && this.keyEquivalence(latestState.key, latestFinalState.value.key)
? latestFinalState.value
: {
key: latestState.key,
result: AsyncResult.initial(false),
}
)
return yield* this.watch(state)
}).pipe(
Effect.provide(this.context),
)
}
get refreshView(): Effect.Effect<
View.View<QueryState<K, A, E>>,
Cause.NoSuchElementError
> {
return Effect.gen({ self: this }, function*() {
yield* this.interrupt
const latestState = yield* Lens.get(this.state)
const latestFinalState = yield* Lens.get(this.latestFinalState)
const state = yield* this.startCached(
Option.isSome(latestFinalState) && this.keyEquivalence(latestState.key, latestFinalState.value.key)
? latestFinalState.value
: {
key: latestState.key,
result: AsyncResult.initial(false),
}
)
yield* Effect.forkScoped(this.watch(state))
return state
}).pipe(
Effect.provide(this.context),
)
}
startCached(
previous: QueryState<K, A, E>,
): Effect.Effect<
View.View<QueryState<K, A, E>>,
Cause.NoSuchElementError,
Scope.Scope | QueryClient.QueryClient | R
> {
return Effect.flatMap(this.getCacheEntry(previous.key), Option.match({
onSome: entry => Effect.flatMap(
QueryClient.isQueryClientCacheEntryStale(entry),
isStale => isStale
? this.start({
key: previous.key,
result: entry.result as AsyncResult.AsyncResult<A, E>,
})
: Effect.succeed(View.make({
get: Effect.succeed({
key: previous.key,
result: entry.result as AsyncResult.AsyncResult<A, E>,
}),
get changes() {
return Stream.make({
key: previous.key,
result: entry.result as AsyncResult.AsyncResult<A, E>,
})
},
})),
),
onNone: () => this.start(previous),
}))
}
start(
previous: QueryState<K, A, E>,
): Effect.Effect<
View.View<QueryState<K, A, E>>,
never,
Scope.Scope | R
> {
return Effect.gen({ self: this }, function*() {
const state = yield* makeQueryStateLens(previous)
const fiber = yield* Effect.forkScoped(Effect.andThen(
Lens.update<QueryState<K, A, E>, never, never, never, never>(
state,
previous => AsyncResult.match(previous.result, {
onInitial: () => ({
key: previous.key,
result: AsyncResult.initial(true),
}),
onSuccess: result => ({
key: previous.key,
result: AsyncResult.success(result.value, {
waiting: true,
}),
}),
onFailure: result => ({
key: previous.key,
result: AsyncResult.failure(result.cause, {
waiting: true,
previousSuccess: result.previousSuccess,
}),
}),
}
)),
Effect.onExit(this.f(previous.key), exit => Effect.gen({ self: this }, function*() {
const fiberId = yield* Effect.fiberId
const fiber = yield* Lens.get(this.fiber)
if (Option.isSome(fiber) && fiberId === fiber.value.id)
yield* Lens.set(this.fiber, Option.none())
const finalState = (yield* Lens.updateAndGet<QueryState<K, A, E>, never, never, never, never>(
state,
previous => Exit.match(exit, {
onSuccess: v => ({
key: previous.key,
result: AsyncResult.success(v),
}),
onFailure: c => Cause.hasInterruptsOnly(c)
? previous
: AsyncResult.match(previous.result, {
onInitial: () => ({
key: previous.key,
result: AsyncResult.failure(c),
}),
onSuccess: v => ({
key: previous.key,
result: AsyncResult.failure(c, {
previousSuccess: Option.some(v),
}),
}),
onFailure: v => ({
key: previous.key,
result: AsyncResult.failure(c, {
previousSuccess: v.previousSuccess,
}),
}),
}),
}),
)) as FinalQueryState<K, A, E>
yield* Lens.set(this.latestFinalState, Option.some(finalState))
yield* PubSub.shutdown(state.pubsub)
}))
))
yield* Lens.set(this.fiber, Option.some(fiber))
return state
})
}
watch(
view: View.View<QueryState<K, A, E>>
): Effect.Effect<FinalQueryState<K, A, E>, never, QueryClient.QueryClient> {
return Effect.gen({ self: this }, function*() {
const initial = yield* View.get(view)
const final = yield* Stream.runFoldEffect(
View.changes(view),
() => initial,
(_, state) => Effect.as(Lens.set(this.state, state), state),
) as Effect.Effect<FinalQueryState<K, A, E>>
yield* Lens.set(this.latestFinalState, Option.some(final))
if (AsyncResult.isSuccess(final.result))
yield* this.setCacheEntry(final.key, final.result)
return final
})
}
makeCacheKey(key: K): QueryClient.QueryClientCacheKey {
return new QueryClient.QueryClientCacheKey(key, this.f as (key: unknown) => Effect.Effect<unknown, unknown, unknown>)
}
getCacheEntry(
key: K
): Effect.Effect<Option.Option<QueryClient.QueryClientCacheEntry>, never, QueryClient.QueryClient> {
return Effect.andThen(
Effect.all([
Effect.succeed(this.makeCacheKey(key)),
QueryClient.QueryClient,
]),
([key, client]) => client.getCacheEntry(key),
)
}
setCacheEntry(
key: K,
result: AsyncResult.Success<A, E>,
): Effect.Effect<QueryClient.QueryClientCacheEntry, never, QueryClient.QueryClient> {
return Effect.flatMap(
Effect.all([
Effect.succeed(this.makeCacheKey(key)),
QueryClient.QueryClient,
]),
([key, client]) => client.setCacheEntry(key, result, this.staleTime),
)
}
get invalidateCache(): Effect.Effect<void> {
return QueryClient.QueryClient.pipe(
Effect.andThen(client => client.invalidateCacheEntries(this.f as (key: unknown) => Effect.Effect<unknown, unknown, unknown>)),
Effect.provide(this.context),
)
}
invalidateCacheEntry(key: K): Effect.Effect<void> {
return Effect.all([
Effect.succeed(this.makeCacheKey(key)),
QueryClient.QueryClient,
]).pipe(
Effect.andThen(([key, client]) => client.invalidateCacheEntry(key)),
Effect.provide(this.context),
)
}
}
export declare namespace make {
export interface Options<K, A, E = never, R = never> {
readonly key: View.View<K>,
readonly keyEquivalence?: Equivalence.Equivalence<K>,
readonly f: (key: K) => Effect.Effect<A, E, R>
readonly staleTime?: Duration.Input
readonly refreshOnWindowFocus?: boolean
}
}
export const make = Effect.fnUntraced(function* <K, A, E = never, R = never>(
options: make.Options<K, A, E, R>
): Effect.fn.Return<
Query<K, A, E, R>,
Cause.NoSuchElementError,
Scope.Scope | QueryClient.QueryClient | R
> {
const client = yield* QueryClient.QueryClient
return new QueryImpl(
yield* Effect.context<Scope.Scope | QueryClient.QueryClient | R>(),
options.key,
options.keyEquivalence ?? Equal.asEquivalence(),
options.f,
options.staleTime ? yield* Effect.fromOption(Duration.fromInput(options.staleTime)) : client.defaultStaleTime,
options.refreshOnWindowFocus ?? client.defaultRefreshOnWindowFocus,
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, E>>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<QueryState<K, A, E>>({
key: yield* View.get(options.key),
result: AsyncResult.initial(false),
})),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<FinalQueryState<K, A, E>>())),
yield* Semaphore.make(1),
)
})
export const service = <K, A, E = never, R = never>(
options: make.Options<K, A, E, R>
): Effect.Effect<
Query<K, A, E, R>,
Cause.NoSuchElementError,
Scope.Scope | QueryClient.QueryClient | R
> => Effect.tap(
make(options),
query => Effect.forkScoped(query.run),
)
export class QueryStateLens<in out K, in out A, in out E = never>
extends Lens.LensImpl<QueryState<K, A, E>, never, never, never, never> {
constructor(
readonly ref: Ref.Ref<QueryState<K, A, E>>,
readonly pubsub: PubSub.PubSub<QueryState<K, A, E>>,
readonly semaphore: Semaphore.Semaphore,
) {
super()
}
get resolve(): Effect.Effect<Lens.LensImpl.Resolved<QueryState<K, A, E>>, never, never> {
return Effect.map(
Ref.get(this.ref),
value => ({
value,
commit: next => Effect.flatMap(
next,
value => Effect.andThen(
Ref.set(this.ref, value),
PubSub.publish(this.pubsub, value),
),
),
}),
)
}
get changes() { return Stream.fromPubSub(this.pubsub) }
get lock() { return Effect.succeed(this.semaphore.withPermit) }
}
export const makeQueryStateLens = <K, A, E = never>(
initial: QueryState<K, A, E>,
) => Effect.all([
Ref.make(initial),
PubSub.unbounded<QueryState<K, A, E>>({ replay: 1 }),
Semaphore.make(1),
]).pipe(
Effect.tap(([, pubsub]) => PubSub.publish(pubsub, initial)),
Effect.map(([ref, pubsub, semaphore]) => new QueryStateLens(ref, pubsub, semaphore)),
)
+183
View File
@@ -0,0 +1,183 @@
import { type Cause, Context, DateTime, Duration, Effect, Equal, Equivalence, Hash, HashMap, Layer, type Option, Pipeable, Predicate, Schedule, type Scope, Semaphore, SubscriptionRef } from "effect"
import type { AsyncResult } from "effect/unstable/reactivity"
import * as Lens from "./Lens.js"
import type * as View from "./View.js"
export const QueryClientServiceTypeId: unique symbol = Symbol.for("@effect-fc/QueryClient/QueryClientService")
export type QueryClientServiceTypeId = typeof QueryClientServiceTypeId
export interface QueryClientService extends Pipeable.Pipeable {
readonly [QueryClientServiceTypeId]: QueryClientServiceTypeId
readonly cache: View.View<HashMap.HashMap<QueryClientCacheKey, QueryClientCacheEntry>>
readonly cacheGcTime: Duration.Duration
readonly defaultStaleTime: Duration.Duration
readonly defaultRefreshOnWindowFocus: boolean
readonly run: Effect.Effect<void, Cause.NoSuchElementError>
getCacheEntry(key: QueryClientCacheKey): Effect.Effect<Option.Option<QueryClientCacheEntry>>
setCacheEntry(
key: QueryClientCacheKey,
result: AsyncResult.Success<unknown, unknown>,
staleTime: Duration.Duration,
): Effect.Effect<QueryClientCacheEntry>
invalidateCacheEntries(f: (key: unknown) => Effect.Effect<unknown, unknown, unknown>): Effect.Effect<void>
invalidateCacheEntry(key: QueryClientCacheKey): Effect.Effect<void>
}
export class QueryClient extends Context.Service<QueryClient, QueryClientService>()(
"@effect-fc/QueryClient/QueryClient"
) {}
export class QueryClientServiceImpl
extends Pipeable.Class
implements QueryClientService {
readonly [QueryClientServiceTypeId]: QueryClientServiceTypeId = QueryClientServiceTypeId
constructor(
readonly cache: Lens.Lens<HashMap.HashMap<QueryClientCacheKey, QueryClientCacheEntry>>,
readonly cacheGcTime: Duration.Duration,
readonly defaultStaleTime: Duration.Duration,
readonly defaultRefreshOnWindowFocus: boolean,
readonly runSemaphore: Semaphore.Semaphore,
) {
super()
}
get run(): Effect.Effect<void, Cause.NoSuchElementError> {
return this.runSemaphore.withPermits(1)(Effect.repeat(
Effect.flatMap(
DateTime.now,
now => Lens.update(this.cache, HashMap.filter(entry =>
Duration.isLessThan(
DateTime.distance(entry.lastAccessedAt, now),
Duration.sum(entry.staleTime, this.cacheGcTime),
)
)),
),
Schedule.spaced("30 second"),
))
}
getCacheEntry(key: QueryClientCacheKey): Effect.Effect<Option.Option<QueryClientCacheEntry>> {
return Effect.all([
DateTime.now,
Effect.flatMap(
Effect.map(Lens.get(this.cache), HashMap.get(key)),
Effect.fromOption,
),
]).pipe(
Effect.map(([now, entry]) => new QueryClientCacheEntry(entry.result, entry.staleTime, entry.createdAt, now)),
Effect.tap(entry => Lens.update(this.cache, HashMap.set(key, entry))),
Effect.option,
)
}
setCacheEntry(
key: QueryClientCacheKey,
result: AsyncResult.Success<unknown, unknown>,
staleTime: Duration.Duration,
): Effect.Effect<QueryClientCacheEntry> {
return DateTime.now.pipe(
Effect.map(now => new QueryClientCacheEntry(result, staleTime, now, now)),
Effect.tap(entry => Lens.update(this.cache, HashMap.set(key, entry))),
)
}
invalidateCacheEntries(f: (key: unknown) => Effect.Effect<unknown, unknown, unknown>): Effect.Effect<void> {
return Lens.update(this.cache, HashMap.filter((_, key) => !Equivalence.strictEqual()(key.f, f)))
}
invalidateCacheEntry(key: QueryClientCacheKey): Effect.Effect<void> {
return Lens.update(this.cache, HashMap.remove(key))
}
}
export const isQueryClientService = (u: unknown): u is QueryClientService => Predicate.hasProperty(u, QueryClientServiceTypeId)
export declare namespace make {
export interface Options {
readonly cacheGcTime?: Duration.Input
readonly defaultStaleTime?: Duration.Input
readonly defaultRefreshOnWindowFocus?: boolean
}
}
export const make = Effect.fnUntraced(function* (
options: make.Options = {}
): Effect.fn.Return<QueryClientService, Cause.NoSuchElementError, never> {
return new QueryClientServiceImpl(
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(HashMap.empty<QueryClientCacheKey, QueryClientCacheEntry>())),
yield* Effect.fromOption(Duration.fromInput(options.cacheGcTime ?? "5 minutes")),
yield* Effect.fromOption(Duration.fromInput(options.defaultStaleTime ?? "0 minutes")),
options.defaultRefreshOnWindowFocus ?? true,
yield* Semaphore.make(1),
)
})
export declare namespace service {
export interface Options extends make.Options {}
}
export const service = (
options?: service.Options
): Effect.Effect<QueryClientService, Cause.NoSuchElementError, Scope.Scope> => Effect.tap(
make(options),
client => Effect.forkScoped(client.run),
)
export const layer = (options?: service.Options) => Layer.effect(QueryClient, service(options))
export const QueryClientCacheKeyTypeId: unique symbol = Symbol.for("@effect-fc/QueryClient/QueryClientCacheKey")
export type QueryClientCacheKeyTypeId = typeof QueryClientCacheKeyTypeId
export class QueryClientCacheKey
extends Pipeable.Class
implements Pipeable.Pipeable, Equal.Equal {
readonly [QueryClientCacheKeyTypeId]: QueryClientCacheKeyTypeId = QueryClientCacheKeyTypeId
constructor(
readonly key: unknown,
readonly f: (key: unknown) => Effect.Effect<unknown, unknown, unknown>,
) {
super()
}
[Equal.symbol](that: Equal.Equal) {
return isQueryClientCacheKey(that) && Equal.equals(this.key, that.key) && Equivalence.strictEqual()(this.f, that.f)
}
[Hash.symbol]() {
return Hash.combine(Hash.hash(this.f))(Hash.hash(this.key))
}
}
export const isQueryClientCacheKey = (u: unknown): u is QueryClientCacheKey => Predicate.hasProperty(u, QueryClientCacheKeyTypeId)
export const QueryClientCacheEntryTypeId: unique symbol = Symbol.for("@effect-fc/QueryClient/QueryClientCacheEntry")
export type QueryClientCacheEntryTypeId = typeof QueryClientCacheEntryTypeId
export class QueryClientCacheEntry
extends Pipeable.Class
implements Pipeable.Pipeable {
readonly [QueryClientCacheEntryTypeId]: QueryClientCacheEntryTypeId = QueryClientCacheEntryTypeId
constructor(
readonly result: AsyncResult.Success<unknown, unknown>,
readonly staleTime: Duration.Duration,
readonly createdAt: DateTime.DateTime,
readonly lastAccessedAt: DateTime.DateTime,
) {
super()
}
}
export const isQueryClientCacheEntry = (u: unknown): u is QueryClientCacheEntry => Predicate.hasProperty(u, QueryClientCacheEntryTypeId)
export const isQueryClientCacheEntryStale = (
self: QueryClientCacheEntry
): Effect.Effect<boolean, Cause.NoSuchElementError> => Effect.map(
DateTime.now,
now => Duration.isGreaterThanOrEqualTo(DateTime.distance(self.createdAt, now), self.staleTime),
)
@@ -0,0 +1,73 @@
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
import { type Context, Effect, Layer, ManagedRuntime, Predicate } from "effect"
import * as React from "react"
import * as Component from "./Component.js"
import * as ScopeRegistry from "./ScopeRegistry.js"
export const ReactRuntimeTypeId: unique symbol = Symbol.for("@effect-fc/ReactRuntime/ReactRuntime")
export type ReactRuntimeTypeId = typeof ReactRuntimeTypeId
export interface ReactRuntime<R, ER> {
new(_: never): Record<string, never>
readonly [ReactRuntimeTypeId]: ReactRuntimeTypeId
readonly runtime: ManagedRuntime.ManagedRuntime<R, ER>
readonly context: React.Context<Context.Context<R>>
}
const ReactRuntimePrototype = Object.freeze({ [ReactRuntimeTypeId]: ReactRuntimeTypeId } as const)
export const preludeLayer: Layer.Layer<ScopeRegistry.ScopeRegistry> = ScopeRegistry.layer
export const isReactRuntime = (u: unknown): u is ReactRuntime<unknown, unknown> => Predicate.hasProperty(u, ReactRuntimeTypeId)
export const make = <R, ER>(
layer: Layer.Layer<R, ER>,
memoMap?: Layer.MemoMap,
): ReactRuntime<Layer.Success<typeof preludeLayer> | R, ER> => Object.setPrototypeOf(
Object.assign(function() {}, {
runtime: ManagedRuntime.make(
Layer.merge(preludeLayer, layer),
{ memoMap },
),
// biome-ignore lint/style/noNonNullAssertion: context initialization
context: React.createContext<Context.Context<Layer.Success<typeof preludeLayer> | R>>(null!),
}),
ReactRuntimePrototype,
)
export namespace Provider {
export interface Props<R, ER> extends React.SuspenseProps {
readonly runtime: ReactRuntime<R, ER>
readonly children?: React.ReactNode
}
}
export const Provider = <R, ER>(
{ runtime, children, ...suspenseProps }: Provider.Props<R, ER>
): React.ReactNode => {
const promise = React.useMemo(() => runtime.runtime.context(), [runtime])
return React.createElement(
React.Suspense,
suspenseProps,
React.createElement(ProviderInner<R, ER>, { runtime, promise, children }),
)
}
const ProviderInner = <R, ER>(
{ runtime, promise, children }: {
readonly runtime: ReactRuntime<R, ER>
readonly promise: Promise<Context.Context<R>>
readonly children?: React.ReactNode
}
): React.ReactNode => {
const context = React.use(promise)
Effect.runSyncWith(context)(Component.useOnChange(
() => Effect.addFinalizer(() => runtime.runtime.disposeEffect),
[runtime],
))
return React.createElement(runtime.context, { value: context }, children)
}
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from "vitest"
import type * as Component from "./Component.js"
import * as Refreshable from "./Refreshable.js"
describe("Refreshable", () => {
it("attaches a cell and notifies subscribers after a compatible update", async () => {
const first = {} as Component.Component.Any
const cell = Refreshable.makeCell(first, "hooks", false)
const listener = vi.fn()
expect(Refreshable.isRefreshable(first)).toBe(false)
const attached = Refreshable.attach(first, cell)
expect(attached).toBe(first)
expect(Refreshable.isRefreshable(first)).toBe(true)
expect(attached[Refreshable.RefreshableTypeId]).toBe(cell)
expect(Object.getPrototypeOf(attached).asFunctionComponent)
.toBe(Refreshable.RefreshablePrototype.asFunctionComponent)
cell.subscribe(listener)
const second = {} as Component.Component.Any
cell.update(second, "hooks", false)
expect(cell.current).toBe(second)
expect(cell.snapshot).toEqual({
revision: 1,
resetRevision: 0,
})
await Promise.resolve()
expect(listener).toHaveBeenCalledTimes(1)
})
it("requests a remount when a signature changes or reset is forced", () => {
const component = {} as Component.Component.Any
const cell = Refreshable.makeCell(component, "one", false)
cell.update({} as Component.Component.Any, "two", false)
expect(cell.snapshot.resetRevision).toBe(1)
cell.update({} as Component.Component.Any, "two", true)
expect(cell.snapshot.resetRevision).toBe(2)
})
it("builds the refresh shell from the current descriptor implementation", () => {
const implementation = () => null
const makeFunctionComponent = vi.fn(() => implementation)
const component = {
makeFunctionComponent,
} as unknown as Component.ComponentImpl.Any
const contextRef = {
current: {},
} as never
const cell = Refreshable.makeCell(component, "hooks", false)
const attached = Refreshable.attach(component, cell)
expect(attached.asFunctionComponent(contextRef)).not.toBe(implementation)
expect(makeFunctionComponent).toHaveBeenCalledWith(contextRef)
})
})
+181
View File
@@ -0,0 +1,181 @@
import type { Context, Scope } from "effect"
import * as React from "react"
import type * as Component from "./Component.js"
/**
* A stable identifier used to associate an Effect View descriptor with its
* development refresh cell.
*
* This low-level API is intended for development-server integrations such as
* `@effect-view/vite-plugin`.
*/
export const RefreshableTypeId: unique symbol = Symbol.for("@effect-view/Refreshable/Refreshable")
export type RefreshableTypeId = typeof RefreshableTypeId
/**
* The version observed by a mounted Effect View refresh shell.
*
* `revision` changes for every update. `resetRevision` changes only when the
* adapter determines that preserving React state is unsafe.
*/
export interface Snapshot {
readonly revision: number
readonly resetRevision: number
}
/**
* A mutable development cell holding the latest version of an Effect View
* descriptor.
*
* This low-level API is intended for development-server integrations.
*/
export interface Cell {
current: Component.ComponentImpl.Any
signature: string
forceReset: boolean
snapshot: Snapshot
readonly subscribe: (listener: () => void) => () => void
readonly getSnapshot: () => Snapshot
readonly update: (
component: Component.Component.Any,
signature: string,
forceReset: boolean,
) => void
}
export const RefreshablePrototype = Object.freeze({
asFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Component.Signature>(
this: Component.ComponentImpl<P, A, E, R, F> & Refreshable,
contextRef: React.RefObject<Context.Context<Exclude<R, Scope.Scope>>>,
) {
const cell = this[RefreshableTypeId]
let current = cell.current
let functionComponent = current.makeFunctionComponent(contextRef)
// Calling the current renderer inside this stable component deliberately
// keeps its hooks on the same fiber until resetRevision changes.
const Implementation = (props: P) => {
if (current !== cell.current) {
current = cell.current
functionComponent = current.makeFunctionComponent(contextRef)
}
return functionComponent(props)
}
const RefreshableComponent = (props: P) => {
const snapshot = React.useSyncExternalStore(
cell.subscribe,
cell.getSnapshot,
cell.getSnapshot,
)
return React.createElement(Implementation, {
...props,
key: snapshot.resetRevision,
})
}
return RefreshableComponent as F
},
} as const)
export type RefreshablePrototype = typeof RefreshablePrototype
/**
* A descriptor that can be connected to a development refresh cell.
*/
export interface Refreshable extends RefreshablePrototype {
readonly [RefreshableTypeId]: Cell
}
/**
* Checks whether a descriptor has been connected to a development refresh
* cell.
*/
export const isRefreshable = <A extends object>(
value: A,
): value is A & Refreshable => Object.hasOwn(value, RefreshableTypeId)
/**
* Creates a refresh cell for an Effect View descriptor.
*
* This low-level API is intended for development-server integrations.
*/
export const makeCell = (
component: Component.Component.Any,
signature: string,
forceReset: boolean,
): Cell => {
const listeners = new Set<() => void>()
let notificationPending = false
const cell: Cell = {
current: component as Component.ComponentImpl.Any,
signature,
forceReset,
snapshot: {
revision: 0,
resetRevision: 0,
},
subscribe(listener) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
getSnapshot() {
return cell.snapshot
},
update(nextComponent, nextSignature, nextForceReset) {
const shouldReset = cell.forceReset
|| nextForceReset
|| cell.signature !== nextSignature
cell.current = nextComponent as Component.ComponentImpl.Any
cell.signature = nextSignature
cell.forceReset = nextForceReset
cell.snapshot = {
revision: cell.snapshot.revision + 1,
resetRevision: cell.snapshot.resetRevision + (shouldReset ? 1 : 0),
}
if (!notificationPending) {
notificationPending = true
queueMicrotask(() => {
notificationPending = false
for (const listener of listeners)
listener()
})
}
},
}
return cell
}
/**
* Associates a descriptor with a refresh cell and returns the descriptor.
*
* This low-level API is intended for development-server integrations.
*/
export const attach = <A extends Component.Component.Any>(
component: A,
cell: Cell,
): A & Refreshable => {
if (!isRefreshable(component)) {
Object.setPrototypeOf(
component,
Object.freeze(Object.setPrototypeOf(
Object.assign({}, RefreshablePrototype),
Object.getPrototypeOf(component),
)),
)
}
Object.defineProperty(component, RefreshableTypeId, {
configurable: true,
enumerable: true,
value: cell,
})
return component as A & Refreshable
}
@@ -0,0 +1,186 @@
import { type Cause, Chunk, Context, DateTime, type Duration, Effect, Equal, Exit, HashMap, Layer, Option, Order, Predicate, Scope, Semaphore, Stream, SubscriptionRef } from "effect"
export const ScopeRegistryServiceTypeId: unique symbol = Symbol.for("@effect-view/ScopeRegistryService/ScopeRegistryService")
export type ScopeRegistryServiceTypeId = typeof ScopeRegistryServiceTypeId
export interface ScopeRegistryService {
readonly [ScopeRegistryServiceTypeId]: ScopeRegistryServiceTypeId
readonly ref: SubscriptionRef.SubscriptionRef<HashMap.HashMap<ScopeRegistryService.Key, ScopeRegistryService.Entry>>
register(
key: ScopeRegistryService.Key,
options: ScopeRegistryService.RegisterOptions,
): Effect.Effect<ScopeRegistryService.Entry>
commit(key: ScopeRegistryService.Key): Effect.Effect<ScopeRegistryService.Entry, Cause.NoSuchElementError>
release(key: ScopeRegistryService.Key): Effect.Effect<ScopeRegistryService.Entry, Cause.NoSuchElementError>
readonly run: Effect.Effect<void, never, Scope.Scope>
}
export declare namespace ScopeRegistryService {
export type Key = object
export interface RegisterOptions {
readonly finalizerExecutionStrategy: "sequential" | "parallel"
readonly finalizerExecutionDebounce: Duration.Input
readonly scopeCommitTimeout: Duration.Input
}
export interface Entry {
readonly scope: Scope.Closeable
readonly expiresAt: Option.Option<DateTime.Utc>
readonly finalizerExecutionDebounce: Duration.Input
}
}
export const isScopeRegistryService = (u: unknown): u is ScopeRegistryService => Predicate.hasProperty(u, ScopeRegistryServiceTypeId)
export const makeKey = (): ScopeRegistryService.Key => Equal.byReference({})
export class ScopeRegistryServiceImpl implements ScopeRegistryService {
readonly [ScopeRegistryServiceTypeId]: ScopeRegistryServiceTypeId = ScopeRegistryServiceTypeId
constructor(
readonly ref: SubscriptionRef.SubscriptionRef<HashMap.HashMap<ScopeRegistryService.Key, ScopeRegistryService.Entry>>,
readonly runSemaphore: Semaphore.Semaphore,
) {}
register(
key: ScopeRegistryService.Key,
options: ScopeRegistryService.RegisterOptions,
): Effect.Effect<ScopeRegistryService.Entry> {
return Effect.gen({ self: this }, function*() {
const entry = Equal.byReference({
scope: yield* Scope.make(options.finalizerExecutionStrategy),
expiresAt: Option.some(DateTime.addDuration(yield* DateTime.now, options.scopeCommitTimeout)),
finalizerExecutionDebounce: options.finalizerExecutionDebounce,
})
yield* SubscriptionRef.update(this.ref, HashMap.set(key, entry))
return entry
})
}
commit(key: ScopeRegistryService.Key): Effect.Effect<ScopeRegistryService.Entry, Cause.NoSuchElementError> {
return SubscriptionRef.get(this.ref).pipe(
Effect.map(HashMap.get(key)),
Effect.flatMap(Effect.fromOption),
Effect.map(entry => Equal.byReference<ScopeRegistryService.Entry>({
...entry,
expiresAt: Option.none(),
})),
Effect.tap(entry => SubscriptionRef.update(this.ref, HashMap.set(key, entry))),
)
}
release(key: ScopeRegistryService.Key): Effect.Effect<ScopeRegistryService.Entry, Cause.NoSuchElementError> {
return SubscriptionRef.get(this.ref).pipe(
Effect.map(HashMap.get(key)),
Effect.flatMap(option => Effect.all([
DateTime.now,
Effect.fromOption(option),
])),
Effect.map(([now, entry]) => Equal.byReference<ScopeRegistryService.Entry>({
...entry,
expiresAt: Option.some(DateTime.addDuration(now, entry.finalizerExecutionDebounce)),
})),
Effect.tap(entry => SubscriptionRef.update(this.ref, HashMap.set(key, entry))),
)
}
get run(): Effect.Effect<void, never, Scope.Scope> {
return Effect.addFinalizer(() => this.dispose).pipe(
Effect.andThen(SubscriptionRef.changes(this.ref).pipe(
Stream.switchMap(entries => Option.match(this.getNextExpiration(entries), {
onNone: () => Stream.never,
onSome: expiresAt => Stream.fromEffect(DateTime.now.pipe(
Effect.flatMap(now => DateTime.isLessThan(now, expiresAt)
? Effect.sleep(DateTime.distance(now, expiresAt))
: Effect.void),
Effect.andThen(Effect.uninterruptible(this.closeExpired)),
)),
})),
Stream.runDrain,
)),
this.runSemaphore.withPermit,
)
}
get dispose(): Effect.Effect<void> {
return SubscriptionRef.getAndSet(
this.ref,
HashMap.empty<ScopeRegistryService.Key, ScopeRegistryService.Entry>(),
).pipe(
Effect.flatMap(entries => Effect.forEach(
HashMap.values(entries),
entry => Scope.close(entry.scope, Exit.void),
)),
Effect.asVoid,
)
}
get closeExpired(): Effect.Effect<void> {
return Effect.flatMap(DateTime.now, now => SubscriptionRef.modify(
this.ref,
HashMap.reduce(
[
Chunk.empty<ScopeRegistryService.Entry>(),
HashMap.empty<ScopeRegistryService.Key, ScopeRegistryService.Entry>(),
] as const,
([expired, remaining], entry, key) => Option.exists(
entry.expiresAt,
expiresAt => DateTime.isLessThanOrEqualTo(expiresAt, now),
)
? [Chunk.append(expired, entry), remaining] as const
: [expired, HashMap.set(remaining, key, entry)] as const,
),
)).pipe(
Effect.flatMap(entries => Effect.forEach(
entries,
entry => Scope.close(entry.scope, Exit.void),
)),
Effect.asVoid,
)
}
getNextExpiration(
entries: HashMap.HashMap<ScopeRegistryService.Key, ScopeRegistryService.Entry>,
): Option.Option<DateTime.Utc> {
return HashMap.reduce(
entries,
Option.none<DateTime.Utc>(),
(earliest, entry) => Option.match(entry.expiresAt, {
onNone: () => earliest,
onSome: expiresAt => Option.some(Option.match(earliest, {
onNone: () => expiresAt,
onSome: Order.min<DateTime.Utc>(DateTime.Order)(expiresAt),
})),
}),
)
}
}
export const make: Effect.Effect<ScopeRegistryService> = Effect.gen(function*() {
return new ScopeRegistryServiceImpl(
yield* SubscriptionRef.make(HashMap.empty<ScopeRegistryService.Key, ScopeRegistryService.Entry>()),
yield* Semaphore.make(1),
)
})
/**
* Internal Effect service that maintains a registry of scopes associated with React component instances.
*
* This service is used internally by the `Component.useScope` hook to manage the lifecycle of component scopes,
* including tracking active scopes and coordinating their cleanup when components unmount or dependencies change.
*/
export class ScopeRegistry extends Context.Service<ScopeRegistry, ScopeRegistryService>()(
"@effect-view/ScopeRegistry/ScopeRegistry"
) {}
export const layer = Layer.effect(ScopeRegistry, Effect.tap(
make,
registry => Effect.forkScoped(registry.run),
))
@@ -0,0 +1,12 @@
import { Function } from "effect"
import type * as React from "react"
export const value: {
<S>(self: React.SetStateAction<S>, prevState: S): S
<S>(prevState: S): (self: React.SetStateAction<S>) => S
} = Function.dual(2, <S>(self: React.SetStateAction<S>, prevState: S): S =>
typeof self === "function"
? (self as (prevState: S) => S)(prevState)
: self
)
+33
View File
@@ -0,0 +1,33 @@
import { Effect, Equivalence, Option, Stream } from "effect"
import * as React from "react"
import * as Component from "./Component.js"
export * from "effect/Stream"
export const use: {
<A, E, R>(
stream: Stream.Stream<A, E, R>
): Effect.Effect<Option.Option<A>, never, R>
<A extends NonNullable<unknown>, E, R>(
stream: Stream.Stream<A, E, R>,
initialValue: A,
): Effect.Effect<Option.Some<A>, never, R>
} = Effect.fnUntraced(function* <A extends NonNullable<unknown>, E, R>(
stream: Stream.Stream<A, E, R>,
initialValue?: A,
) {
const [reactStateValue, setReactStateValue] = React.useState(() => initialValue
? Option.some(initialValue)
: Option.none()
)
yield* Component.useReactEffect(() => Effect.forkScoped(
Stream.runForEach(
Stream.changesWith(stream, Equivalence.strictEqual()),
v => Effect.sync(() => setReactStateValue(Option.some(v))),
)
), [stream])
return reactStateValue as Option.Some<A>
})
+94
View File
@@ -0,0 +1,94 @@
import { render, screen, waitFor } from "@testing-library/react"
import { Effect, Layer, SubscriptionRef } from "effect"
import { Lens } from "effect-lens"
import { describe, expect, it } from "vitest"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
import * as View from "./View.js"
const makeRuntime = async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await runtime.runtime.context()
return {
runtime,
effectRuntime,
dispose: () => runtime.runtime.dispose(),
}
}
describe("View", () => {
it("useAll returns the latest values and rerenders when any input changes", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const countRef = await Effect.runPromise(SubscriptionRef.make(1))
const labelRef = await Effect.runPromise(SubscriptionRef.make("a"))
const count = Lens.fromSubscriptionRef(countRef)
const label = Lens.fromSubscriptionRef(labelRef)
const Probe = Component.makeUntraced("ViewUseAllProbe")(function*() {
const [currentCount, currentLabel] = yield* View.useAll([count, label])
return <div>{`${currentCount}:${currentLabel}`}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("1:a")
await Effect.runPromise(Lens.set(count, 2))
await screen.findByText("2:a")
await Effect.runPromise(Lens.set(label, "b"))
await screen.findByText("2:b")
view.unmount()
await dispose()
})
it("useAll respects the provided equivalence when processing updates", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const itemRef = await Effect.runPromise(SubscriptionRef.make({ id: 1, label: "first" }))
const flagRef = await Effect.runPromise(SubscriptionRef.make(true))
const item = Lens.fromSubscriptionRef(itemRef)
const flag = Lens.fromSubscriptionRef(flagRef)
const Probe = Component.makeUntraced("ViewUseAllEquivalenceProbe")(function*() {
const [currentItem, currentFlag] = yield* View.useAll([item, flag], {
equivalence: ([selfItem, selfFlag], [thatItem, thatFlag]) =>
selfItem.id === thatItem.id && selfFlag === thatFlag,
})
return <div>{`${currentItem.label}:${currentFlag ? "on" : "off"}`}</div>
}).pipe(
Component.withContext(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first:on")
await Effect.runPromise(Lens.set(item, { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first:on")).toBeTruthy())
expect(screen.queryByText("ignored:on")).toBeNull()
await Effect.runPromise(Lens.set(flag, false))
await screen.findByText("ignored:off")
await Effect.runPromise(Lens.set(item, { id: 2, label: "updated" }))
await screen.findByText("updated:off")
view.unmount()
await dispose()
})
})
+42
View File
@@ -0,0 +1,42 @@
import { Effect, Equivalence, Stream } from "effect"
import { View } from "effect-lens"
import * as React from "react"
import * as Component from "./Component.js"
export * from "effect-lens/View"
export declare namespace useAll {
export type Success<T extends readonly View.View<any, any, any>[]> = [T[number]] extends [never]
? never
: { [K in keyof T]: T[K] extends View.View<infer A, infer _E, infer _R> ? A : never }
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useAll = Effect.fnUntraced(function* <const T extends readonly View.View<any, any, any>[]>(
elements: T,
options?: useAll.Options<useAll.Success<NoInfer<T>>>,
): Effect.fn.Return<
useAll.Success<T>,
[T[number]] extends [never] ? never : T[number] extends View.View<infer _A, infer E, infer _R> ? E : never,
[T[number]] extends [never] ? never : T[number] extends View.View<infer _A, infer _E, infer R> ? R : never
> {
const [reactStateValue, setReactStateValue] = React.useState(
yield* Component.useOnMount(() => Effect.all(elements.map(View.get)))
)
yield* Component.useReactEffect(() => Stream.make(reactStateValue).pipe(
Stream.concat(View.changes(View.zipLatestAll(...elements))),
Stream.changesWith((options?.equivalence as Equivalence.Equivalence<any[]> | undefined) ?? Equivalence.Array(Equivalence.strictEqual())),
Stream.drop(1),
Stream.runForEach(v =>
Effect.sync(() => setReactStateValue(v))
),
Effect.forkScoped,
), elements)
return reactStateValue as any
})
+17
View File
@@ -0,0 +1,17 @@
export * as Async from "./Async.js"
export * as Component from "./Component.js"
export * as Form from "./Form.js"
export * as Lens from "./Lens.js"
export * as LensForm from "./LensForm.js"
export * as Memoized from "./Memoized.js"
export * as Mutation from "./Mutation.js"
export * as MutationForm from "./MutationForm.js"
export * as PubSub from "./PubSub.js"
export * as Query from "./Query.js"
export * as QueryClient from "./QueryClient.js"
export * as ReactRuntime from "./ReactRuntime.js"
export * as Refreshable from "./Refreshable.js"
export * as ScopeRegistry from "./ScopeRegistry.js"
export * as SetStateAction from "./SetStateAction.js"
export * as Stream from "./Stream.js"
export * as View from "./View.js"
@@ -0,0 +1,4 @@
import { configure } from "@testing-library/react"
configure({ reactStrictMode: true })
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["**/setup-tests.ts", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"]
}
+39
View File
@@ -0,0 +1,39 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "NodeNext",
"moduleDetection": "force",
"jsx": "react-jsx",
// "allowJs": true,
// Bundler mode
"moduleResolution": "NodeNext",
// "allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
// "noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false,
// Build
"rootDir": "./src",
"outDir": "./dist",
"declaration": true,
"sourceMap": true,
"plugins": [
{ "name": "@effect/language-service" }
]
},
"include": ["./src"],
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
environment: "jsdom",
include: ["./src/**/*.test.ts?(x)"],
setupFiles: ["./src/setup-tests.ts"],
},
})
+10 -12
View File
@@ -15,39 +15,37 @@ Documentation is currently being written. In the meantime, you can take a look a
## What writing components looks like
```typescript
export class Todos extends Component.make("Todos")(function*() {
export class TodosView extends Component.make("TodosView")(function*() {
const state = yield* TodosState
const [todos] = yield* useSubscribables(state.ref)
const [todos] = yield* Component.useSubscribables([state.subscriptionRef])
yield* useOnMount(() => Effect.andThen(
yield* Component.useOnMount(() => Effect.andThen(
Console.log("Todos mounted"),
Effect.addFinalizer(() => Console.log("Todos unmounted")),
))
const TodoFC = yield* Todo
const Todo = yield* TodoView.use
return (
<Container>
<Heading align="center">Todos</Heading>
<Flex direction="column" align="stretch" gap="2" mt="2">
<TodoFC _tag="new" />
<Todo _tag="new" />
{Chunk.map(todos, todo =>
<TodoFC key={todo.id} _tag="edit" id={todo.id} />
<Todo key={todo.id} _tag="edit" id={todo.id} />
)}
</Flex>
</Container>
)
}) {}
const TodosStateLive = TodosState.Default("todos")
const Index = Component.make("IndexView")(function*() {
const context = yield* Component.useLayer(TodosState.Default)
const Todos = yield* Effect.provide(TodosView.use, context)
const Index = Component.make("Index")(function*() {
const context = yield* useContext(TodosStateLive)
const TodosFC = yield* Effect.provide(Todos, context)
return <TodosFC />
return <Todos />
}).pipe(
Component.withRuntime(runtime.context)
)
+13 -6
View File
@@ -1,7 +1,7 @@
{
"name": "effect-fc",
"description": "Write React function components with Effect",
"version": "0.2.3",
"version": "0.3.0",
"type": "module",
"files": [
"./README.md",
@@ -29,20 +29,27 @@
]
},
"scripts": {
"build": "tsc",
"lint:tsc": "tsc --noEmit",
"lint:tsc": "tsc -b --noEmit",
"lint:biome": "biome lint",
"test": "vitest run",
"build": "tsc -b tsconfig.build.json",
"pack": "npm pack",
"clean:cache": "rm -rf .turbo tsconfig.tsbuildinfo",
"clean:cache": "rm -rf .turbo *.tsbuildinfo",
"clean:dist": "rm -rf dist",
"clean:modules": "rm -rf node_modules"
},
"devDependencies": {
"@effect/platform-browser": "^0.74.0"
"@effect/platform-browser": "^0.76.0",
"@testing-library/react": "^16.3.0",
"jsdom": "^26.1.0",
"vitest": "^3.2.4"
},
"peerDependencies": {
"@types/react": "^19.2.0",
"effect": "^3.19.0",
"effect": "^3.21.0",
"react": "^19.2.0"
},
"dependencies": {
"effect-lens": "^0.2.0"
}
}
+117 -31
View File
@@ -1,35 +1,49 @@
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
import { Effect, Function, Predicate, Runtime, Scope } from "effect"
import { Effect, type Equivalence, Function, Predicate, Runtime, Scope } from "effect"
import * as React from "react"
import * as Component from "./Component.js"
export const TypeId: unique symbol = Symbol.for("@effect-fc/Async/Async")
export type TypeId = typeof TypeId
export const AsyncTypeId: unique symbol = Symbol.for("@effect-fc/Async/Async")
export type AsyncTypeId = typeof AsyncTypeId
export interface Async extends Async.Options {
readonly [TypeId]: TypeId
/**
* A trait for `Component`'s that allows them running asynchronous effects.
*/
export interface Async extends AsyncPrototype, AsyncOptions {}
export interface AsyncPrototype {
readonly [AsyncTypeId]: AsyncTypeId
}
export namespace Async {
export interface Options {
readonly defaultFallback?: React.ReactNode
}
export type Props = Omit<React.SuspenseProps, "children">
/**
* Configuration options for `Async` components.
*/
export interface AsyncOptions {
/**
* The default fallback React node to display while the async operation is pending.
* Used if no fallback is provided to the component when rendering.
*/
readonly defaultFallback?: React.ReactNode
}
/**
* Props for `Async` components.
*/
export type AsyncProps = Omit<React.SuspenseProps, "children">
const AsyncProto = Object.freeze({
[TypeId]: TypeId,
makeFunctionComponent<P extends {}, A extends React.ReactNode, E, R>(
this: Component.Component<P, A, E, R> & Async,
export const AsyncPrototype: AsyncPrototype = Object.freeze({
[AsyncTypeId]: AsyncTypeId,
asFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Component.Signature>(
this: Component.Component<P, A, E, R, F> & Async,
runtimeRef: React.RefObject<Runtime.Runtime<Exclude<R, Scope.Scope>>>,
) {
const SuspenseInner = (props: { readonly promise: Promise<React.ReactNode> }) => React.use(props.promise)
const Inner = (props: { readonly promise: Promise<React.ReactNode> }) => React.use(props.promise)
return ({ fallback, name, ...props }: Async.Props) => {
return ({ fallback, name, ...props }: AsyncProps) => {
const promise = Runtime.runPromise(runtimeRef.current)(
Effect.andThen(
Component.useScope([], this),
@@ -40,45 +54,117 @@ const AsyncProto = Object.freeze({
return React.createElement(
React.Suspense,
{ fallback: fallback ?? this.defaultFallback, name },
React.createElement(SuspenseInner, { promise }),
React.createElement(Inner, { promise }),
)
}
},
} as const)
/**
* An equivalence function for comparing `AsyncProps` that ignores the `fallback` property.
* Used by default by async components with `Memoized.memoized` applied.
*/
export const defaultPropsEquivalence: Equivalence.Equivalence<AsyncProps> = (
self: Record<string, unknown>,
that: Record<string, unknown>,
) => {
if (self === that)
return true
export const isAsync = (u: unknown): u is Async => Predicate.hasProperty(u, TypeId)
for (const key in self) {
if (key === "fallback")
continue
if (!(key in that) || !Object.is(self[key], that[key]))
return false
}
export const async = <T extends Component.Component<any, any, any, any>>(
self: T
for (const key in that) {
if (key === "fallback")
continue
if (!(key in self))
return false
}
return true
}
export const isAsync = (u: unknown): u is Async => Predicate.hasProperty(u, AsyncTypeId)
/**
* Converts a Component into an `Async` component that supports running asynchronous effects.
*
* Note: The component cannot have a prop named "promise" as it's reserved for internal use.
*
* @param self - The component to convert to an Async component
* @returns A new `Async` component with the same body, error, and context types as the input
*
* @example
* ```ts
* const MyAsyncComponent = MyComponent.pipe(
* Async.async,
* )
* ```
*/
export const async = <T extends Component.Component.Any>(
self: T & (
"promise" extends keyof Component.Component.Props<T>
? "The 'promise' prop name is restricted for Async components. Please rename the 'promise' prop to something else."
: T
)
): (
& Omit<T, keyof Component.Component.AsComponent<T>>
& Component.Component<
Component.Component.Props<T> & Async.Props,
Component.Component.Props<T> & AsyncProps,
Component.Component.Success<T>,
Component.Component.Error<T>,
Component.Component.Context<T>
Component.Component.Context<T>,
Component.Component.DefaultSignature<Component.Component.Props<T> & AsyncProps, Component.Component.Success<T>>
>
& Async
) => Object.setPrototypeOf(
Object.assign(function() {}, self),
Object.assign(function() {}, self, { propsEquivalence: defaultPropsEquivalence }),
Object.freeze(Object.setPrototypeOf(
Object.assign({}, AsyncProto),
Object.assign({}, AsyncPrototype),
Object.getPrototypeOf(self),
)),
)
/**
* Applies options to an Async component, returning a new Async component with the updated configuration.
*
* Supports both curried and uncurried application styles.
*
* @param self - The Async component to apply options to (in uncurried form)
* @param options - The options to apply to the component
* @returns An Async component with the applied options
*
* @example
* ```ts
* // Curried
* const MyAsyncComponent = MyComponent.pipe(
* Async.async,
* Async.withOptions({ defaultFallback: <p>Loading...</p> }),
* )
*
* // Uncurried
* const MyAsyncComponent = Async.withOptions(
* Async.async(MyComponent),
* { defaultFallback: <p>Loading...</p> },
* )
* ```
*/
export const withOptions: {
<T extends Component.Component<any, any, any, any> & Async>(
options: Partial<Async.Options>
<T extends Component.Component.Any & Async>(
options: Partial<AsyncOptions>
): (self: T) => T
<T extends Component.Component<any, any, any, any> & Async>(
<T extends Component.Component.Any & Async>(
self: T,
options: Partial<Async.Options>,
options: Partial<AsyncOptions>,
): T
} = Function.dual(2, <T extends Component.Component<any, any, any, any> & Async>(
} = Function.dual(2, <T extends Component.Component.Any & Async>(
self: T,
options: Partial<Async.Options>,
options: Partial<AsyncOptions>,
): T => Object.setPrototypeOf(
Object.assign(function() {}, self, options),
Object.getPrototypeOf(self),
+354
View File
@@ -0,0 +1,354 @@
import { render, screen, waitFor } from "@testing-library/react"
import { Context, Effect, Layer } from "effect"
import * as React from "react"
import { afterEach, describe, expect, it, vi } from "vitest"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
class ValueService extends Context.Tag("ValueService")<ValueService, { readonly value: string }>() {}
afterEach(() => {
vi.useRealTimers()
})
describe("Component", () => {
it("runs useOnMount only once across rerenders", async () => {
const onMount = vi.fn(() => Effect.succeed("mounted"))
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const Probe = Component.makeUntraced("UseOnMountProbe")(function*() {
const value = yield* Component.useOnMount(onMount)
return <div>{value}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("mounted")
expect(onMount).toHaveBeenCalledTimes(1)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
expect(await screen.findByText("mounted")).toBeTruthy()
expect(onMount).toHaveBeenCalledTimes(1)
view.unmount()
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("recomputes useOnChange only when dependencies change", async () => {
const onChange = vi.fn((value: number) => Effect.succeed(`value:${value}`))
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const Probe = Component.makeUntraced("UseOnChangeProbe")(function*(props: { readonly value: number }) {
const result = yield* Component.useOnChange(() => onChange(props.value), [props.value], {
finalizerExecutionDebounce: 0,
})
return <div>{result}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value={1} />
</runtime.context.Provider>
)
await screen.findByText("value:1")
expect(onChange).toHaveBeenCalledTimes(1)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value={1} />
</runtime.context.Provider>
)
expect(await screen.findByText("value:1")).toBeTruthy()
expect(onChange).toHaveBeenCalledTimes(1)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value={2} />
</runtime.context.Provider>
)
await screen.findByText("value:2")
expect(onChange).toHaveBeenCalledTimes(2)
view.unmount()
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("closes the previous scope on dependency changes and unmount", async () => {
const cleanup = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const Probe = Component.makeUntraced("ScopeCleanupProbe")(function*(props: { readonly value: string }) {
const result = yield* Component.useOnChange(
() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
return props.value
}),
[props.value],
{ finalizerExecutionDebounce: 0 },
)
return <div>{result}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
expect(cleanup).not.toHaveBeenCalled()
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"))
expect(cleanup).toHaveBeenCalledTimes(1)
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"))
expect(cleanup).toHaveBeenCalledTimes(2)
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("runs useReactEffect setup and cleanup when dependencies change", async () => {
const lifecycle = vi.fn<(message: string) => void>()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const Probe = Component.makeUntraced("UseReactEffectProbe")(function*(props: { readonly value: string }) {
yield* Component.useReactEffect(() =>
Effect.gen(function*() {
yield* Effect.sync(() => lifecycle(`mount:${props.value}`))
yield* Effect.addFinalizer(() => Effect.sync(() => lifecycle(`cleanup:${props.value}`)))
}),
[props.value])
return <div>{props.value}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("mount:first"))
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("cleanup:first"))
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("mount:second"))
view.unmount()
await waitFor(() => expect(lifecycle).toHaveBeenCalledWith("cleanup:second"))
expect(lifecycle.mock.calls.map(([message]) => message)).toEqual([
"mount:first",
"cleanup:first",
"mount:second",
"cleanup:second",
])
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("keeps useCallbackSync stable until dependencies change", async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const seenCallbacks: Array<(value: number) => string> = []
const Probe = Component.makeUntraced("UseCallbackSyncProbe")(function*(props: { readonly prefix: string }) {
const callback = yield* Component.useCallbackSync(
(value: number) => Effect.succeed(`${props.prefix}:${value}`),
[props.prefix],
)
yield* Component.useOnMount(() => Effect.sync(() => {
seenCallbacks.push(callback)
}))
React.useEffect(() => {
seenCallbacks.push(callback)
}, [callback])
return <div>{callback(1)}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="a" />
</runtime.context.Provider>
)
await screen.findByText("a:1")
expect(seenCallbacks).toHaveLength(2)
expect(seenCallbacks[0]).toBe(seenCallbacks[1])
expect(seenCallbacks[0]?.(2)).toBe("a:2")
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="a" />
</runtime.context.Provider>
)
await screen.findByText("a:1")
expect(seenCallbacks).toHaveLength(2)
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe prefix="b" />
</runtime.context.Provider>
)
await screen.findByText("b:1")
await waitFor(() => expect(seenCallbacks).toHaveLength(3))
expect(seenCallbacks[2]).not.toBe(seenCallbacks[1])
expect(seenCallbacks[2]?.(2)).toBe("b:2")
view.unmount()
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("delays cleanup according to finalizerExecutionDebounce", async () => {
const cleanup = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const Probe = Component.makeUntraced("DebouncedCleanupProbe")(function*(props: { readonly value: string }) {
const result = yield* Component.useOnChange(
() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
return props.value
}),
[props.value],
{ finalizerExecutionDebounce: "20 millis" },
)
return <div>{result}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Probe value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
expect(cleanup).not.toHaveBeenCalled()
await new Promise(resolve => setTimeout(resolve, 5))
expect(cleanup).not.toHaveBeenCalled()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"), { timeout: 100 })
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"), { timeout: 100 })
await Effect.runPromise(runtime.runtime.disposeEffect)
})
it("does not remount a component when only nonReactiveTags change", async () => {
const mounts = vi.fn()
const unmounts = vi.fn()
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
const SubComponent = Component.makeUntraced("NonReactiveSubComponent")(function*() {
const service = yield* ValueService
yield* Component.useOnMount(() => Effect.gen(function*() {
yield* Effect.sync(() => mounts())
yield* Effect.addFinalizer(() => Effect.sync(() => unmounts()))
}))
return <div>{service.value}</div>
}).pipe(
Component.withOptions({ nonReactiveTags: [ValueService] })
)
const Parent = Component.makeUntraced("NonReactiveParent")(function*(props: { readonly value: string }) {
const serviceLayer = React.useMemo(
() => Layer.succeed(ValueService, { value: props.value }),
[props.value],
)
const context = yield* Component.useLayer(serviceLayer, {
finalizerExecutionDebounce: 0,
})
const Child = yield* Effect.provide(SubComponent.use, context)
return <Child />
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Parent value="first" />
</runtime.context.Provider>
)
await screen.findByText("first")
expect(mounts).toHaveBeenCalledTimes(1)
expect(unmounts).not.toHaveBeenCalled()
view.rerender(
<runtime.context.Provider value={effectRuntime}>
<Parent value="second" />
</runtime.context.Provider>
)
await screen.findByText("second")
expect(mounts).toHaveBeenCalledTimes(1)
expect(unmounts).not.toHaveBeenCalled()
view.unmount()
await waitFor(() => expect(unmounts).toHaveBeenCalledTimes(1))
await Effect.runPromise(runtime.runtime.disposeEffect)
})
})
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -1,20 +1,20 @@
import { type Cause, Context, Effect, Exit, Layer, Option, Pipeable, Predicate, PubSub, type Queue, type Scope, Supervisor } from "effect"
export const TypeId: unique symbol = Symbol.for("@effect-fc/ErrorObserver/ErrorObserver")
export type TypeId = typeof TypeId
export const ErrorObserverTypeId: unique symbol = Symbol.for("@effect-fc/ErrorObserver/ErrorObserver")
export type ErrorObserverTypeId = typeof ErrorObserverTypeId
export interface ErrorObserver<in out E = never> extends Pipeable.Pipeable {
readonly [TypeId]: TypeId
readonly [ErrorObserverTypeId]: ErrorObserverTypeId
handle<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>
readonly subscribe: Effect.Effect<Queue.Dequeue<Cause.Cause<E>>, never, Scope.Scope>
}
export const ErrorObserver = <E = never>(): Context.Tag<ErrorObserver, ErrorObserver<E>> => Context.GenericTag("@effect-fc/ErrorObserver/ErrorObserver")
class ErrorObserverImpl<in out E = never>
export class ErrorObserverImpl<in out E = never>
extends Pipeable.Class() implements ErrorObserver<E> {
readonly [TypeId]: TypeId = TypeId
readonly [ErrorObserverTypeId]: ErrorObserverTypeId = ErrorObserverTypeId
readonly subscribe: Effect.Effect<Queue.Dequeue<Cause.Cause<E>>, never, Scope.Scope>
constructor(
@@ -29,7 +29,7 @@ extends Pipeable.Class() implements ErrorObserver<E> {
}
}
class ErrorObserverSupervisorImpl extends Supervisor.AbstractSupervisor<void> {
export class ErrorObserverSupervisorImpl extends Supervisor.AbstractSupervisor<void> {
readonly value = Effect.void
constructor(readonly pubsub: PubSub.PubSub<Cause.Cause<never>>) {
super()
@@ -43,7 +43,7 @@ class ErrorObserverSupervisorImpl extends Supervisor.AbstractSupervisor<void> {
}
export const isErrorObserver = (u: unknown): u is ErrorObserver<unknown> => Predicate.hasProperty(u, TypeId)
export const isErrorObserver = (u: unknown): u is ErrorObserver<unknown> => Predicate.hasProperty(u, ErrorObserverTypeId)
export const layer: Layer.Layer<ErrorObserver> = Layer.unwrapEffect(Effect.map(
PubSub.unbounded<Cause.Cause<never>>(),
+176 -298
View File
@@ -1,293 +1,157 @@
import { Array, Cause, Chunk, type Context, type Duration, Effect, Equal, Exit, Fiber, flow, Hash, HashMap, identity, Option, ParseResult, Pipeable, Predicate, Ref, Schema, type Scope, Stream } from "effect"
import { Array, type Cause, Chunk, type Duration, Effect, Equal, Function, identity, Option, type ParseResult, Pipeable, Predicate, type Scope, Stream, SubscriptionRef } from "effect"
import type * as React from "react"
import * as Component from "./Component.js"
import * as Mutation from "./Mutation.js"
import * as PropertyPath from "./PropertyPath.js"
import * as Result from "./Result.js"
import * as Lens from "./Lens.js"
import * as Subscribable from "./Subscribable.js"
import * as SubscriptionRef from "./SubscriptionRef.js"
import * as SubscriptionSubRef from "./SubscriptionSubRef.js"
export const FormTypeId: unique symbol = Symbol.for("@effect-fc/Form/Form")
export type FormTypeId = typeof FormTypeId
export interface Form<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
export interface Form<out P extends readonly PropertyKey[], in out A, in out I = A, in out ER = never, in out EW = never>
extends Pipeable.Pipeable {
readonly [FormTypeId]: FormTypeId
readonly schema: Schema.Schema<A, I, R>
readonly context: Context.Context<Scope.Scope | R>
readonly mutation: Mutation.Mutation<
readonly [value: A, form: Form<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
>
readonly autosubmit: boolean
readonly debounce: Option.Option<Duration.DurationInput>
readonly value: Subscribable.Subscribable<Option.Option<A>>
readonly encodedValue: SubscriptionRef.SubscriptionRef<I>
readonly error: Subscribable.Subscribable<Option.Option<ParseResult.ParseError>>
readonly validationFiber: Subscribable.Subscribable<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>>
readonly canSubmit: Subscribable.Subscribable<boolean>
field<const P extends PropertyPath.Paths<I>>(
path: P
): Effect.Effect<FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>>>
readonly run: Effect.Effect<void>
readonly submit: Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException>
readonly path: P
readonly value: Subscribable.Subscribable<Option.Option<A>, ER, never>
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>
readonly issues: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[], never, never>
readonly isValidating: Subscribable.Subscribable<boolean, ER, never>
readonly canCommit: Subscribable.Subscribable<boolean, never, never>
readonly isCommitting: Subscribable.Subscribable<boolean, never, never>
}
export class FormImpl<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Pipeable.Class() implements Form<A, I, R, MA, ME, MR, MP> {
export class FormImpl<out P extends readonly PropertyKey[], in out A, in out I = A, in out ER = never, in out EW = never>
extends Pipeable.Class() implements Form<P, A, I, ER, EW> {
readonly [FormTypeId]: FormTypeId = FormTypeId
constructor(
readonly schema: Schema.Schema<A, I, R>,
readonly context: Context.Context<Scope.Scope | R>,
readonly mutation: Mutation.Mutation<
readonly [value: A, form: Form<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
>,
readonly autosubmit: boolean,
readonly debounce: Option.Option<Duration.DurationInput>,
readonly value: SubscriptionRef.SubscriptionRef<Option.Option<A>>,
readonly encodedValue: SubscriptionRef.SubscriptionRef<I>,
readonly error: SubscriptionRef.SubscriptionRef<Option.Option<ParseResult.ParseError>>,
readonly validationFiber: SubscriptionRef.SubscriptionRef<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>>,
readonly runSemaphore: Effect.Semaphore,
readonly fieldCache: Ref.Ref<HashMap.HashMap<FormFieldKey, FormField<unknown, unknown>>>,
readonly path: P,
readonly value: Subscribable.Subscribable<Option.Option<A>, ER, never>,
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>,
readonly issues: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[], never, never>,
readonly isValidating: Subscribable.Subscribable<boolean, never, never>,
readonly canCommit: Subscribable.Subscribable<boolean, never, never>,
readonly isCommitting: Subscribable.Subscribable<boolean, never, never>,
) {
super()
this.canSubmit = Subscribable.map(
Subscribable.zipLatestAll(this.value, this.error, this.validationFiber, this.mutation.result),
([value, error, validationFiber, result]) => (
Option.isSome(value) &&
Option.isNone(error) &&
Option.isNone(validationFiber) &&
!(Result.isRunning(result) || Result.hasRefreshingFlag(result))
),
)
}
field<const P extends PropertyPath.Paths<I>>(
path: P
): Effect.Effect<FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>>> {
const key = new FormFieldKey(path)
return this.fieldCache.pipe(
Effect.map(HashMap.get(key)),
Effect.flatMap(Option.match({
onSome: v => Effect.succeed(v as FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>>),
onNone: () => Effect.tap(
Effect.succeed(makeFormField(this as Form<A, I, R, MA, ME, MR, MP>, path)),
v => Ref.update(this.fieldCache, HashMap.set(key, v as FormField<unknown, unknown>)),
),
})),
)
}
readonly canSubmit: Subscribable.Subscribable<boolean>
get run(): Effect.Effect<void> {
return this.runSemaphore.withPermits(1)(Stream.runForEach(
this.encodedValue.changes.pipe(
Option.isSome(this.debounce) ? Stream.debounce(this.debounce.value) : identity
),
encodedValue => this.validationFiber.pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(
Effect.forkScoped(Effect.onExit(
Schema.decode(this.schema, { errors: "all" })(encodedValue),
exit => Effect.andThen(
Exit.matchEffect(exit, {
onSuccess: v => Effect.andThen(
Ref.set(this.value, Option.some(v)),
Ref.set(this.error, Option.none()),
),
onFailure: c => Option.match(Chunk.findFirst(Cause.failures(c), e => e._tag === "ParseError"), {
onSome: e => Ref.set(this.error, Option.some(e)),
onNone: () => Effect.void,
}),
}),
Ref.set(this.validationFiber, Option.none()),
),
)).pipe(
Effect.tap(fiber => Ref.set(this.validationFiber, Option.some(fiber))),
Effect.andThen(Fiber.join),
Effect.andThen(value => this.autosubmit
? Effect.asVoid(Effect.forkScoped(this.submitValue(value)))
: Effect.void
),
Effect.forkScoped,
)
),
Effect.provide(this.context),
),
))
}
get submit(): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException> {
return this.value.pipe(
Effect.andThen(identity),
Effect.andThen(value => this.submitValue(value)),
)
}
submitValue(value: A): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>> {
return Effect.whenEffect(
Effect.tap(
this.mutation.mutate([value, this as any]),
result => Result.isFailure(result)
? Option.match(
Chunk.findFirst(
Cause.failures(result.cause as Cause.Cause<ParseResult.ParseError>),
e => e._tag === "ParseError",
),
{
onSome: e => Ref.set(this.error, Option.some(e)),
onNone: () => Effect.void,
},
)
: Effect.void
),
this.canSubmit.get,
)
}
}
export const isForm = (u: unknown): u is Form<unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, FormTypeId)
export declare namespace make {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Mutation.make.Options<
readonly [value: NoInfer<A>, form: Form<NoInfer<A>, NoInfer<I>, NoInfer<R>, unknown, unknown, unknown>],
MA, ME, MR, MP
> {
readonly schema: Schema.Schema<A, I, R>
readonly initialEncodedValue: NoInfer<I>
readonly autosubmit?: boolean
readonly debounce?: Duration.DurationInput
}
}
export const isForm = (u: unknown): u is Form<readonly PropertyKey[], unknown, unknown> => Predicate.hasProperty(u, FormTypeId)
const filterIssuesByPath = (
issues: readonly ParseResult.ArrayFormatterIssue[],
path: readonly PropertyKey[],
): readonly ParseResult.ArrayFormatterIssue[] => Array.filter(issues, issue =>
issue.path.length >= path.length && Array.every(path, (p, i) => p === issue.path[i])
)
export const focusObjectOn: {
<P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
self: Form<P, A, I, ER, EW>,
key: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW>
<P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
key: K,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, K], A[K], I[K], ER, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
self: Form<P, A, I, ER, EW>,
key: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, key] as const
export const make = Effect.fnUntraced(function* <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: make.Options<A, I, R, MA, ME, MR, MP>
): Effect.fn.Return<
Form<A, I, R, MA, ME, Result.forkEffect.OutputContext<MA, ME, MR, MP>, MP>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MA, ME, MR, MP>
> {
return new FormImpl(
options.schema,
yield* Effect.context<Scope.Scope | R>(),
yield* Mutation.make(options),
options.autosubmit ?? false,
Option.fromNullable(options.debounce),
yield* SubscriptionRef.make(Option.none<A>()),
yield* SubscriptionRef.make(options.initialEncodedValue),
yield* SubscriptionRef.make(Option.none<ParseResult.ParseError>()),
yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, ParseResult.ParseError>>()),
yield* Effect.makeSemaphore(1),
yield* Ref.make(HashMap.empty<FormFieldKey, FormField<unknown, unknown>>()),
path,
Subscribable.mapOption(form.value, a => a[key]),
Lens.focusObjectOn(form.encodedValue, key),
Subscribable.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export declare namespace service {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends make.Options<A, I, R, MA, ME, MR, MP> {}
}
export const focusArrayAt: {
<P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
self: Form<P, A, I, ER, EW>,
index: number,
): Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementException, EW | Cause.NoSuchElementException>
<P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
index: number,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementException, EW | Cause.NoSuchElementException>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends readonly any[], I extends readonly any[], ER, EW>(
self: Form<P, A, I, ER, EW>,
index: number,
): Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementException, EW | Cause.NoSuchElementException> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
export const service = <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: service.Options<A, I, R, MA, ME, MR, MP>
): Effect.Effect<
Form<A, I, R, MA, ME, Result.forkEffect.OutputContext<MA, ME, MR, MP>, MP>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MA, ME, MR, MP>
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)
export const FormFieldTypeId: unique symbol = Symbol.for("@effect-fc/Form/FormField")
export type FormFieldTypeId = typeof FormFieldTypeId
export interface FormField<in out A, in out I = A>
extends Pipeable.Pipeable {
readonly [FormFieldTypeId]: FormFieldTypeId
readonly value: Subscribable.Subscribable<Option.Option<A>, Cause.NoSuchElementException>
readonly encodedValue: SubscriptionRef.SubscriptionRef<I>
readonly issues: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[]>
readonly isValidating: Subscribable.Subscribable<boolean>
readonly isSubmitting: Subscribable.Subscribable<boolean>
}
class FormFieldImpl<in out A, in out I = A>
extends Pipeable.Class() implements FormField<A, I> {
readonly [FormFieldTypeId]: FormFieldTypeId = FormFieldTypeId
constructor(
readonly value: Subscribable.Subscribable<Option.Option<A>, Cause.NoSuchElementException>,
readonly encodedValue: SubscriptionRef.SubscriptionRef<I>,
readonly issues: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[]>,
readonly isValidating: Subscribable.Subscribable<boolean>,
readonly isSubmitting: Subscribable.Subscribable<boolean>,
) {
super()
}
}
const FormFieldKeyTypeId: unique symbol = Symbol.for("@effect-fc/Form/FormFieldKey")
type FormFieldKeyTypeId = typeof FormFieldKeyTypeId
class FormFieldKey implements Equal.Equal {
readonly [FormFieldKeyTypeId]: FormFieldKeyTypeId = FormFieldKeyTypeId
constructor(readonly path: PropertyPath.PropertyPath) {}
[Equal.symbol](that: Equal.Equal) {
return isFormFieldKey(that) && PropertyPath.equivalence(this.path, that.path)
}
[Hash.symbol]() {
return Hash.array(this.path)
}
}
export const isFormField = (u: unknown): u is FormField<unknown, unknown> => Predicate.hasProperty(u, FormFieldTypeId)
const isFormFieldKey = (u: unknown): u is FormFieldKey => Predicate.hasProperty(u, FormFieldKeyTypeId)
export const makeFormField = <A, I, R, MA, ME, MR, MP, const P extends PropertyPath.Paths<NoInfer<I>>>(
self: Form<A, I, R, MA, ME, MR, MP>,
path: P,
): FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>> => {
return new FormFieldImpl(
Subscribable.mapEffect(self.value, Option.match({
onSome: v => Option.map(PropertyPath.get(v, path), Option.some),
onNone: () => Option.some(Option.none()),
})),
SubscriptionSubRef.makeFromPath(self.encodedValue, path),
Subscribable.mapEffect(self.error, Option.match({
onSome: flow(
ParseResult.ArrayFormatter.formatError,
Effect.map(Array.filter(issue => PropertyPath.equivalence(issue.path, path))),
),
onNone: () => Effect.succeed([]),
})),
Subscribable.map(self.validationFiber, Option.isSome),
Subscribable.map(self.mutation.result, result => Result.isRunning(result) || Result.hasRefreshingFlag(result)),
return new FormImpl(
path,
Subscribable.mapOptionEffect(form.value, Array.get(index)),
Lens.focusArrayAt(form.encodedValue, index),
Subscribable.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
}
})
export const focusTupleAt: {
<P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
self: Form<P, A, I, ER, EW>,
index: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW>
<P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
index: K,
): (self: Form<P, A, I, ER, EW>) => Form<readonly [...P, K], A[K], I[K], ER, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A extends readonly [any, ...any[]], I extends readonly [any, ...any[]], ER, EW, K extends number>(
self: Form<P, A, I, ER, EW>,
index: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
Subscribable.mapOption(form.value, Array.unsafeGet(index)),
Lens.focusTupleAt(form.encodedValue, index),
Subscribable.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export const focusChunkAt: {
<P extends readonly PropertyKey[], A, I, ER, EW>(
self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>,
index: number,
): Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementException, EW>
<P extends readonly PropertyKey[], A, I, ER, EW>(
index: number,
): (self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>) => Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementException, EW>
} = Function.dual(2, <P extends readonly PropertyKey[], A, I, ER, EW>(
self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>,
index: number,
): Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementException, EW> => {
const form = self as FormImpl<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
Subscribable.mapOptionEffect(form.value, Chunk.get(index)),
Lens.focusChunkAt(form.encodedValue, index),
Subscribable.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
form.canCommit,
form.isCommitting,
)
})
export namespace useInput {
@@ -301,33 +165,39 @@ export namespace useInput {
}
}
export const useInput = Effect.fnUntraced(function* <A, I>(
field: FormField<A, I>,
export const useInput = Effect.fnUntraced(function* <P extends readonly PropertyKey[], A, I, ER, EW>(
form: Form<P, A, I, ER, EW>,
options?: useInput.Options,
): Effect.fn.Return<useInput.Success<I>, Cause.NoSuchElementException, Scope.Scope> {
const internalValueRef = yield* Component.useOnChange(() => Effect.tap(
Effect.andThen(field.encodedValue, SubscriptionRef.make),
internalValueRef => Effect.forkScoped(Effect.all([
): Effect.fn.Return<useInput.Success<I>, ER, Scope.Scope> {
const internalValueLens = yield* Component.useOnChange(() => Effect.gen(function*() {
const internalValueLens = yield* Lens.get(form.encodedValue).pipe(
Effect.flatMap(SubscriptionRef.make),
Effect.map(Lens.fromSubscriptionRef),
)
yield* Effect.forkScoped(Effect.all([
Stream.runForEach(
Stream.drop(field.encodedValue, 1),
Stream.drop(form.encodedValue.changes, 1),
upstreamEncodedValue => Effect.whenEffect(
Ref.set(internalValueRef, upstreamEncodedValue),
Effect.andThen(internalValueRef, internalValue => !Equal.equals(upstreamEncodedValue, internalValue)),
Lens.set(internalValueLens, upstreamEncodedValue),
Effect.andThen(Lens.get(internalValueLens), internalValue => !Equal.equals(upstreamEncodedValue, internalValue)),
),
),
Stream.runForEach(
internalValueRef.changes.pipe(
internalValueLens.changes.pipe(
Stream.drop(1),
Stream.changesWith(Equal.equivalence()),
options?.debounce ? Stream.debounce(options.debounce) : identity,
),
internalValue => Ref.set(field.encodedValue, internalValue),
internalValue => Lens.set(form.encodedValue, internalValue),
),
], { concurrency: "unbounded" })),
), [field, options?.debounce])
], { concurrency: "unbounded", discard: true }))
const [value, setValue] = yield* SubscriptionRef.useSubscriptionRefState(internalValueRef)
return internalValueLens
}), [form, options?.debounce])
const [value, setValue] = yield* Lens.useState(internalValueLens)
return { value, setValue }
})
@@ -342,55 +212,63 @@ export namespace useOptionalInput {
}
}
export const useOptionalInput = Effect.fnUntraced(function* <A, I>(
field: FormField<A, Option.Option<I>>,
export const useOptionalInput = Effect.fnUntraced(function* <P extends readonly PropertyKey[], A, I, ER, EW>(
field: Form<P, A, Option.Option<I>, ER, EW>,
options: useOptionalInput.Options<I>,
): Effect.fn.Return<useOptionalInput.Success<I>, Cause.NoSuchElementException, Scope.Scope> {
const [enabledRef, internalValueRef] = yield* Component.useOnChange(() => Effect.tap(
Effect.andThen(
field.encodedValue,
): Effect.fn.Return<useOptionalInput.Success<I>, ER, Scope.Scope> {
const [enabledLens, internalValueLens] = yield* Component.useOnChange(() => Effect.gen(function*() {
const [enabledLens, internalValueLens] = yield* Effect.flatMap(
Lens.get(field.encodedValue),
Option.match({
onSome: v => Effect.all([SubscriptionRef.make(true), SubscriptionRef.make(v)]),
onNone: () => Effect.all([SubscriptionRef.make(false), SubscriptionRef.make(options.defaultValue)]),
onSome: v => Effect.all([
Effect.map(SubscriptionRef.make(true), Lens.fromSubscriptionRef),
Effect.map(SubscriptionRef.make(v), Lens.fromSubscriptionRef),
]),
onNone: () => Effect.all([
Effect.map(SubscriptionRef.make(false), Lens.fromSubscriptionRef),
Effect.map(SubscriptionRef.make(options.defaultValue), Lens.fromSubscriptionRef),
]),
}),
),
)
([enabledRef, internalValueRef]) => Effect.forkScoped(Effect.all([
yield* Effect.forkScoped(Effect.all([
Stream.runForEach(
Stream.drop(field.encodedValue, 1),
Stream.drop(field.encodedValue.changes, 1),
upstreamEncodedValue => Effect.whenEffect(
Option.match(upstreamEncodedValue, {
onSome: v => Effect.andThen(
Ref.set(enabledRef, true),
Ref.set(internalValueRef, v),
Lens.set(enabledLens, true),
Lens.set(internalValueLens, v),
),
onNone: () => Effect.andThen(
Ref.set(enabledRef, false),
Ref.set(internalValueRef, options.defaultValue),
Lens.set(enabledLens, false),
Lens.set(internalValueLens, options.defaultValue),
),
}),
Effect.andThen(
Effect.all([enabledRef, internalValueRef]),
Effect.all([Lens.get(enabledLens), Lens.get(internalValueLens)]),
([enabled, internalValue]) => !Equal.equals(upstreamEncodedValue, enabled ? Option.some(internalValue) : Option.none()),
),
),
),
Stream.runForEach(
enabledRef.changes.pipe(
Stream.zipLatest(internalValueRef.changes),
enabledLens.changes.pipe(
Stream.zipLatest(internalValueLens.changes),
Stream.drop(1),
Stream.changesWith(Equal.equivalence()),
options?.debounce ? Stream.debounce(options.debounce) : identity,
),
([enabled, internalValue]) => Ref.set(field.encodedValue, enabled ? Option.some(internalValue) : Option.none()),
([enabled, internalValue]) => Lens.set(field.encodedValue, enabled ? Option.some(internalValue) : Option.none()),
),
], { concurrency: "unbounded" })),
), [field, options.debounce])
], { concurrency: "unbounded" }))
const [enabled, setEnabled] = yield* SubscriptionRef.useSubscriptionRefState(enabledRef)
const [value, setValue] = yield* SubscriptionRef.useSubscriptionRefState(internalValueRef)
return [enabledLens, internalValueLens] as const
}), [field, options.debounce])
const [enabled, setEnabled] = yield* Lens.useState(enabledLens)
const [value, setValue] = yield* Lens.useState(internalValueLens)
return { enabled, setEnabled, value, setValue }
})
+171
View File
@@ -0,0 +1,171 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react"
import { Effect, Layer, SubscriptionRef } from "effect"
import * as React from "react"
import { describe, expect, it } from "vitest"
import * as Component from "./Component.js"
import * as Lens from "./Lens.js"
import * as ReactRuntime from "./ReactRuntime.js"
const makeRuntime = async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
return {
runtime,
effectRuntime,
dispose: () => Effect.runPromise(runtime.runtime.disposeEffect),
}
}
const expectDefined = <A,>(value: A | undefined): A => {
if (value === undefined)
throw new Error("Expected value to be defined")
return value
}
describe("Lens", () => {
it("useState stays in sync with lens updates in both directions", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const ref = await Effect.runPromise(SubscriptionRef.make(0))
const lens = Lens.fromSubscriptionRef(ref)
const Probe = Component.makeUntraced("LensUseStateProbe")(function*() {
const [value, setValue] = yield* Lens.useState(lens)
return (
<>
<div>{value}</div>
<button type="button" onClick={() => setValue(previous => previous + 1)}>increment</button>
</>
)
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("0")
await Effect.runPromise(Lens.set(lens, 5))
await screen.findByText("5")
fireEvent.click(screen.getByRole("button", { name: "increment" }))
await screen.findByText("6")
expect(await Effect.runPromise(Lens.get(lens))).toBe(6)
view.unmount()
await dispose()
})
it("useState respects the provided equivalence when subscribing to lens changes", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const ref = await Effect.runPromise(SubscriptionRef.make({ id: 1, label: "first" }))
const lens = Lens.fromSubscriptionRef(ref)
const Probe = Component.makeUntraced("LensUseStateEquivalenceProbe")(function*() {
const [value] = yield* Lens.useState(lens, {
equivalence: (self, that) => self.id === that.id,
})
return <div>{value.label}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first")
await Effect.runPromise(Lens.set(lens, { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first")).toBeTruthy())
expect(screen.queryByText("ignored")).toBeNull()
await Effect.runPromise(Lens.set(lens, { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
await dispose()
})
it("useFromReactState writes React state changes into the returned lens", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
let lens: Lens.Lens<string, never, never, never, never> | undefined
const Probe = Component.makeUntraced("LensUseFromReactStateProbe")(function*() {
const [value, setValue] = React.useState("hello")
const reactLens = yield* Lens.useFromReactState([value, setValue])
yield* Component.useOnMount(() => Effect.sync(() => {
lens = reactLens
}))
return <button type="button" onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("hello")
await waitFor(() => expect(lens).toBeDefined())
fireEvent.click(screen.getByRole("button", { name: "hello" }))
await screen.findByText("hello!")
await waitFor(async () => expect(await Effect.runPromise(Lens.get(expectDefined(lens)))).toBe("hello!"))
view.unmount()
await dispose()
})
it("useFromReactState respects equivalence when lens updates flow back into React state", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
let lens: Lens.Lens<{ readonly id: number; readonly label: string }, never, never, never, never> | undefined
const Probe = Component.makeUntraced("LensUseFromReactStateEquivalenceProbe")(function*() {
const [value, setValue] = React.useState({ id: 1, label: "first" })
const reactLens = yield* Lens.useFromReactState([value, setValue], {
equivalence: (self, that) => self.id === that.id,
})
yield* Component.useOnMount(() => Effect.sync(() => {
lens = reactLens
}))
return <div>{value.label}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first")
await waitFor(() => expect(lens).toBeDefined())
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first")).toBeTruthy())
expect(screen.queryByText("ignored")).toBeNull()
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
await dispose()
})
})
+62
View File
@@ -0,0 +1,62 @@
import { Effect, Equivalence, Stream, SubscriptionRef } from "effect"
import { Lens } from "effect-lens"
import * as React from "react"
import * as Component from "./Component.js"
import * as SetStateAction from "./SetStateAction.js"
export * from "effect-lens/Lens"
export declare namespace useState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useState = Effect.fnUntraced(function* <A, ER, EW, RR, RW>(
lens: Lens.Lens<A, ER, EW, RR, RW>,
options?: useState.Options<NoInfer<A>>,
): Effect.fn.Return<readonly [A, React.Dispatch<React.SetStateAction<A>>], ER, RR | RW> {
const [reactStateValue, setReactStateValue] = React.useState(yield* Component.useOnMount(() => Lens.get(lens)))
yield* Component.useReactEffect(() => Effect.forkScoped(
Stream.runForEach(
Stream.changesWith(lens.changes, options?.equivalence ?? Equivalence.strict()),
v => Effect.sync(() => setReactStateValue(v)),
)
), [lens])
const setValue = yield* Component.useCallbackSync(
(setStateAction: React.SetStateAction<A>) => Effect.andThen(
Lens.updateAndGet(lens, prevState => SetStateAction.value(setStateAction, prevState)),
v => setReactStateValue(v),
),
[lens],
)
return [reactStateValue, setValue]
})
export declare namespace useFromReactState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useFromReactState = Effect.fnUntraced(function* <A>(
[value, setValue]: readonly [A, React.Dispatch<React.SetStateAction<A>>],
options?: useFromReactState.Options<NoInfer<A>>,
): Effect.fn.Return<Lens.Lens<A, never, never, never, never>> {
const lens = yield* Component.useOnMount(() => Effect.map(
SubscriptionRef.make(value),
Lens.fromSubscriptionRef,
))
yield* Component.useReactEffect(() => Effect.forkScoped(Stream.runForEach(
Stream.changesWith(lens.changes, options?.equivalence ?? Equivalence.strict()),
v => Effect.sync(() => setValue(v)),
)), [setValue])
yield* Component.useReactEffect(() => Lens.set(lens, value), [value])
return lens
})
+80 -19
View File
@@ -1,50 +1,111 @@
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
import { type Equivalence, Function, Predicate } from "effect"
import * as React from "react"
import type * as Component from "./Component.js"
export const TypeId: unique symbol = Symbol.for("@effect-fc/Memoized/Memoized")
export type TypeId = typeof TypeId
export const MemoizedTypeId: unique symbol = Symbol.for("@effect-fc/Memoized/Memoized")
export type MemoizedTypeId = typeof MemoizedTypeId
export interface Memoized<P> extends Memoized.Options<P> {
readonly [TypeId]: TypeId
/**
* A trait for `Component`'s that uses `React.memo` to optimize re-renders based on prop equality.
*
* @template P The props type of the component
*/
export interface Memoized<P> extends MemoizedPrototype, MemoizedOptions<P> {}
export interface MemoizedPrototype {
readonly [MemoizedTypeId]: MemoizedTypeId
}
export namespace Memoized {
export interface Options<P> {
readonly propsAreEqual?: Equivalence.Equivalence<P>
}
/**
* Configuration options for Memoized components.
*
* @template P The props type of the component
*/
export interface MemoizedOptions<P> {
/**
* An optional equivalence function for comparing component props.
* If provided, this function is used by React.memo to determine if props have changed.
* Returns `true` if props are equivalent (no re-render), `false` if they differ (re-render).
*/
readonly propsEquivalence?: Equivalence.Equivalence<P>
}
const MemoizedProto = Object.freeze({
[TypeId]: TypeId
export const MemoizedPrototype: MemoizedPrototype = Object.freeze({
[MemoizedTypeId]: MemoizedTypeId,
transformFunctionComponent<P extends {}>(
this: Memoized<P>,
f: React.FC<P>,
) {
return React.memo(f, this.propsEquivalence)
},
} as const)
export const isMemoized = (u: unknown): u is Memoized<unknown> => Predicate.hasProperty(u, TypeId)
export const isMemoized = (u: unknown): u is Memoized<unknown> => Predicate.hasProperty(u, MemoizedTypeId)
export const memoized = <T extends Component.Component<any, any, any, any>>(
/**
* Converts a Component into a `Memoized` component that optimizes re-renders using `React.memo`.
*
* @param self - The component to convert to a Memoized component
* @returns A new `Memoized` component with the same body, error, and context types as the input
*
* @example
* ```ts
* const MyMemoizedComponent = MyComponent.pipe(
* Memoized.memoized,
* )
* ```
*/
export const memoized = <T extends Component.Component.Any>(
self: T
): T & Memoized<Component.Component.Props<T>> => Object.setPrototypeOf(
Object.assign(function() {}, self),
Object.freeze(Object.setPrototypeOf(
Object.assign({}, MemoizedProto),
Object.assign({}, MemoizedPrototype),
Object.getPrototypeOf(self),
)),
)
/**
* Applies options to a Memoized component, returning a new Memoized component with the updated configuration.
*
* Supports both curried and uncurried application styles.
*
* @param self - The Memoized component to apply options to (in uncurried form)
* @param options - The options to apply to the component
* @returns A Memoized component with the applied options
*
* @example
* ```ts
* // Curried
* const MyMemoizedComponent = MyComponent.pipe(
* Memoized.memoized,
* Memoized.withOptions({ propsEquivalence: (a, b) => a.id === b.id }),
* )
*
* // Uncurried
* const MyMemoizedComponent = Memoized.withOptions(
* Memoized.memoized(MyComponent),
* { propsEquivalence: (a, b) => a.id === b.id },
* )
* ```
*/
export const withOptions: {
<T extends Component.Component<any, any, any, any> & Memoized<any>>(
options: Partial<Memoized.Options<Component.Component.Props<T>>>
<T extends Component.Component.Any & Memoized<any>>(
options: Partial<MemoizedOptions<Component.Component.Props<T>>>
): (self: T) => T
<T extends Component.Component<any, any, any, any> & Memoized<any>>(
<T extends Component.Component.Any & Memoized<any>>(
self: T,
options: Partial<Memoized.Options<Component.Component.Props<T>>>,
options: Partial<MemoizedOptions<Component.Component.Props<T>>>,
): T
} = Function.dual(2, <T extends Component.Component<any, any, any, any> & Memoized<any>>(
} = Function.dual(2, <T extends Component.Component.Any & Memoized<any>>(
self: T,
options: Partial<Memoized.Options<Component.Component.Props<T>>>,
options: Partial<MemoizedOptions<Component.Component.Props<T>>>,
): T => Object.setPrototypeOf(
Object.assign(function() {}, self, options),
Object.getPrototypeOf(self),
+5 -3
View File
@@ -99,8 +99,10 @@ extends Pipeable.Class() implements Mutation<K, A, E, R, P> {
}
}
export const isMutation = (u: unknown): u is Mutation<readonly unknown[], unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, MutationTypeId)
export declare namespace make {
export interface Options<K extends Mutation.AnyKey = never, A = void, E = never, R = never, P = never> {
readonly f: (key: K) => Effect.Effect<A, E, Result.forkEffect.InputContext<R, NoInfer<P>>>
@@ -111,12 +113,12 @@ export declare namespace make {
export const make = Effect.fnUntraced(function* <const K extends Mutation.AnyKey = never, A = void, E = never, R = never, P = never>(
options: make.Options<K, A, E, R, P>
): Effect.fn.Return<
Mutation<K, A, E, Result.forkEffect.OutputContext<A, E, R, P>, P>,
Mutation<K, A, E, Result.forkEffect.OutputContext<R, P>, P>,
never,
Scope.Scope | Result.forkEffect.OutputContext<A, E, R, P>
Scope.Scope | Result.forkEffect.OutputContext<R, P>
> {
return new MutationImpl(
yield* Effect.context<Scope.Scope | Result.forkEffect.OutputContext<A, E, R, P>>(),
yield* Effect.context<Scope.Scope | Result.forkEffect.OutputContext<R, P>>(),
options.f as any,
options.initialProgress as P,
-98
View File
@@ -1,98 +0,0 @@
import { Array, Equivalence, Function, Option, Predicate } from "effect"
export type PropertyPath = readonly PropertyKey[]
type Prev = readonly [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
export type Paths<T, D extends number = 5, Seen = never> = readonly [] | (
D extends never ? readonly [] :
T extends Seen ? readonly [] :
T extends readonly any[] ? {
[K in keyof T as K extends number ? K : never]:
| readonly [K]
| readonly [K, ...Paths<T[K], Prev[D], Seen | T>]
} extends infer O
? O[keyof O]
: never
:
T extends object ? {
[K in keyof T as K extends string | number | symbol ? K : never]-?:
NonNullable<T[K]> extends infer V
? readonly [K] | readonly [K, ...Paths<V, Prev[D], Seen>]
: never
} extends infer O
? O[keyof O]
: never
:
never
)
export type ValueFromPath<T, P extends readonly any[]> = P extends readonly [infer Head, ...infer Tail]
? Head extends keyof T
? ValueFromPath<T[Head], Tail>
: T extends readonly any[]
? Head extends number
? ValueFromPath<T[number], Tail>
: never
: never
: T
export const equivalence: Equivalence.Equivalence<PropertyPath> = Equivalence.array(Equivalence.strict())
export const unsafeGet: {
<T, const P extends Paths<T>>(path: P): (self: T) => ValueFromPath<T, P>
<T, const P extends Paths<T>>(self: T, path: P): ValueFromPath<T, P>
} = Function.dual(2, <T, const P extends Paths<T>>(self: T, path: P): ValueFromPath<T, P> =>
path.reduce((acc: any, key: any) => acc?.[key], self)
)
export const get: {
<T, const P extends Paths<T>>(path: P): (self: T) => Option.Option<ValueFromPath<T, P>>
<T, const P extends Paths<T>>(self: T, path: P): Option.Option<ValueFromPath<T, P>>
} = Function.dual(2, <T, const P extends Paths<T>>(self: T, path: P): Option.Option<ValueFromPath<T, P>> =>
path.reduce(
(acc: Option.Option<any>, key: any): Option.Option<any> => Option.isSome(acc)
? Predicate.hasProperty(acc.value, key)
? Option.some(acc.value[key])
: Option.none()
: acc,
Option.some(self),
)
)
export const immutableSet: {
<T, const P extends Paths<T>>(path: P, value: ValueFromPath<T, P>): (self: T) => Option.Option<T>
<T, const P extends Paths<T>>(self: T, path: P, value: ValueFromPath<T, P>): Option.Option<T>
} = Function.dual(3, <T, const P extends Paths<T>>(self: T, path: P, value: ValueFromPath<T, P>): Option.Option<T> => {
const key = Array.head(path as PropertyPath)
if (Option.isNone(key))
return Option.some(value as T)
if (!Predicate.hasProperty(self, key.value))
return Option.none()
const child = immutableSet<any, any>(self[key.value], Option.getOrThrow(Array.tail(path as PropertyPath)), value)
if (Option.isNone(child))
return child
if (Array.isArray(self))
return typeof key.value === "number"
? Option.some([
...self.slice(0, key.value),
child.value,
...self.slice(key.value + 1),
] as T)
: Option.none()
if (typeof self === "object")
return Option.some(
Object.assign(
Object.create(Object.getPrototypeOf(self)),
{ ...self, [key.value]: child.value },
)
)
return Option.none()
})
+1 -1
View File
@@ -3,7 +3,7 @@ import type * as React from "react"
import * as Component from "./Component.js"
export const usePubSubFromReactiveValues = Effect.fnUntraced(function* <const A extends React.DependencyList>(
export const useFromReactiveValues = Effect.fnUntraced(function* <const A extends React.DependencyList>(
values: A
): Effect.fn.Return<PubSub.PubSub<A>, never, Scope.Scope> {
const pubsub = yield* Component.useOnMount(() => Effect.acquireRelease(PubSub.unbounded<A>(), PubSub.shutdown))
+169
View File
@@ -0,0 +1,169 @@
import { Effect, Option, type Scope, Stream } from "effect"
import { describe, expect, it } from "vitest"
import * as Query from "./Query.js"
import * as QueryClient from "./QueryClient.js"
import * as Result from "./Result.js"
const runQueryTest = <A, E>(effect: Effect.Effect<A, E, QueryClient.QueryClient | Scope.Scope>) =>
Effect.runPromise(Effect.scoped(effect.pipe(
Effect.provide(QueryClient.QueryClient.Default),
)))
const expectSuccessValue = <A, E, P>(
result: Result.Result<A, E, P>,
): A => {
expect(Result.isSuccess(result)).toBe(true)
if (!Result.isSuccess(result))
throw new Error(`Expected Success result, received ${result._tag}`)
return result.value
}
const expectSomeValue = <A>(option: Option.Option<A>): A => {
expect(Option.isSome(option)).toBe(true)
if (!Option.isSome(option))
throw new Error("Expected Some option, received None")
return option.value
}
describe("Query", () => {
it("fetch caches successful results until they are invalidated or stale", async () => {
let calls = 0
const key = Stream.empty as Stream.Stream<readonly [number]>
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(1)
expect(result[0]._tag).toBe("Success")
expect(result[1]._tag).toBe("Success")
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:1")
})
it("refresh reruns the latest query key", async () => {
let calls = 0
const key = Stream.empty as Stream.Stream<readonly [number]>
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "0 millis",
})
const first = yield* query.fetch([1])
yield* Effect.sleep("1 millis")
const refreshed = yield* query.refresh
return [first, refreshed] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("invalidateCacheEntry forces the next fetch for that key to rerun", async () => {
let calls = 0
const key = Stream.empty as Stream.Stream<readonly [number]>
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
yield* query.invalidateCacheEntry([1])
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("invalidateCache clears cached entries for the query function", async () => {
let calls = 0
const key = Stream.empty as Stream.Stream<readonly [number]>
const result = await runQueryTest(Effect.gen(function*() {
const query = yield* Query.make({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
const first = yield* query.fetch([1])
yield* query.invalidateCache
const second = yield* query.fetch([1])
return [first, second] as const
}))
expect(calls).toBe(2)
expect(expectSuccessValue(result[0])).toBe("value:1:1")
expect(expectSuccessValue(result[1])).toBe("value:1:2")
})
it("service starts the key stream automatically and updates latest state", async () => {
let calls = 0
const key = Stream.make([1] as const) as Stream.Stream<readonly [number]>
const effect = Effect.gen(function*() {
const query = yield* Query.service({
key,
f: ([id]: readonly [number]) => Effect.sync(() => {
calls += 1
return `value:${id}:${calls}`
}),
staleTime: "1 minute",
})
yield* Effect.sleep("10 millis")
return {
final: yield* query.result.get,
latestKey: yield* query.latestKey.get,
latestFinalResult: yield* query.latestFinalResult.get,
}
})
const result = await runQueryTest(effect)
expect(calls).toBe(1)
expect(expectSuccessValue(result.final)).toBe("value:1:1")
expect(expectSomeValue(result.latestKey)).toEqual([1])
expect(expectSuccessValue(expectSomeValue(result.latestFinalResult))).toBe("value:1:1")
})
})
+23 -20
View File
@@ -6,12 +6,12 @@ import * as Result from "./Result.js"
export const QueryTypeId: unique symbol = Symbol.for("@effect-fc/Query/Query")
export type QueryTypeId = typeof QueryTypeId
export interface Query<in out K extends Query.AnyKey, in out A, in out E = never, in out R = never, in out P = never>
export interface Query<in out K extends Query.AnyKey, in out A, in out KE = never, in out KR = never, in out E = never, in out R = never, in out P = never>
extends Pipeable.Pipeable {
readonly [QueryTypeId]: QueryTypeId
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | R>
readonly key: Stream.Stream<K>
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | KR | R>
readonly key: Stream.Stream<K, KE, KR>
readonly f: (key: K) => Effect.Effect<A, E, R>
readonly initialProgress: P
@@ -37,13 +37,13 @@ export declare namespace Query {
export type AnyKey = readonly any[]
}
export class QueryImpl<in out K extends Query.AnyKey, in out A, in out E = never, in out R = never, in out P = never>
extends Pipeable.Class() implements Query<K, A, E, R, P> {
export class QueryImpl<in out K extends Query.AnyKey, in out A, in out KE = never, in out KR = never, in out E = never, in out R = never, in out P = never>
extends Pipeable.Class() implements Query<K, A, KE, KR, E, R, P> {
readonly [QueryTypeId]: QueryTypeId = QueryTypeId
constructor(
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | R>,
readonly key: Stream.Stream<K>,
readonly context: Context.Context<Scope.Scope | QueryClient.QueryClient | KR | R>,
readonly key: Stream.Stream<K, KE, KR>,
readonly f: (key: K) => Effect.Effect<A, E, R>,
readonly initialProgress: P,
@@ -77,6 +77,7 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
], { concurrency: "unbounded" }).pipe(
Effect.ignore,
this.runSemaphore.withPermits(1),
Effect.provide(this.context),
)
}
@@ -265,11 +266,13 @@ extends Pipeable.Class() implements Query<K, A, E, R, P> {
}
}
export const isQuery = (u: unknown): u is Query<readonly unknown[], unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, QueryTypeId)
export const isQuery = (u: unknown): u is Query<readonly unknown[], unknown> => Predicate.hasProperty(u, QueryTypeId)
export declare namespace make {
export interface Options<K extends Query.AnyKey, A, E = never, R = never, P = never> {
readonly key: Stream.Stream<K>
export interface Options<K extends Query.AnyKey, A, KE = never, KR = never, E = never, R = never, P = never> {
readonly key: Stream.Stream<K, KE, KR>
readonly f: (key: NoInfer<K>) => Effect.Effect<A, E, Result.forkEffect.InputContext<R, NoInfer<P>>>
readonly initialProgress?: P
readonly staleTime?: Duration.DurationInput
@@ -277,17 +280,17 @@ export declare namespace make {
}
}
export const make = Effect.fnUntraced(function* <K extends Query.AnyKey, A, E = never, R = never, P = never>(
options: make.Options<K, A, E, R, P>
export const make = Effect.fnUntraced(function* <K extends Query.AnyKey, A, KE = never, KR = never, E = never, R = never, P = never>(
options: make.Options<K, A, KE, KR, E, R, P>
): Effect.fn.Return<
Query<K, A, E, Result.forkEffect.OutputContext<A, E, R, P>, P>,
Query<K, A, KE, KR, E, Result.forkEffect.OutputContext<R, P>, P>,
never,
Scope.Scope | QueryClient.QueryClient | Result.forkEffect.OutputContext<A, E, R, P>
Scope.Scope | QueryClient.QueryClient | KR | Result.forkEffect.OutputContext<R, P>
> {
const client = yield* QueryClient.QueryClient
return new QueryImpl(
yield* Effect.context<Scope.Scope | QueryClient.QueryClient | Result.forkEffect.OutputContext<A, E, R, P>>(),
return new QueryImpl<K, A, KE, KR, E, Result.forkEffect.OutputContext<R, P>, P>(
yield* Effect.context<Scope.Scope | QueryClient.QueryClient | KR | Result.forkEffect.OutputContext<R, P>>(),
options.key,
options.f as any,
options.initialProgress as P,
@@ -304,12 +307,12 @@ export const make = Effect.fnUntraced(function* <K extends Query.AnyKey, A, E =
)
})
export const service = <K extends Query.AnyKey, A, E = never, R = never, P = never>(
options: make.Options<K, A, E, R, P>
export const service = <K extends Query.AnyKey, A, KE = never, KR = never, E = never, R = never, P = never>(
options: make.Options<K, A, KE, KR, E, R, P>
): Effect.Effect<
Query<K, A, E, Result.forkEffect.OutputContext<A, E, R, P>, P>,
Query<K, A, KE, KR, E, Result.forkEffect.OutputContext<R, P>, P>,
never,
Scope.Scope | QueryClient.QueryClient | Result.forkEffect.OutputContext<A, E, R, P>
Scope.Scope | QueryClient.QueryClient | KR | Result.forkEffect.OutputContext<R, P>
> => Effect.tap(
make(options),
query => Effect.forkScoped(query.run),
+77 -87
View File
@@ -1,4 +1,5 @@
import { Cause, Context, Data, Effect, Equal, Exit, type Fiber, Hash, Layer, Match, Pipeable, Predicate, PubSub, pipe, Ref, type Scope, Stream, Subscribable } from "effect"
import { Cause, Context, Data, Effect, Equal, Exit, type Fiber, Hash, Layer, Match, Pipeable, Predicate, PubSub, pipe, Ref, type Scope, Stream, type Subscribable, SynchronizedRef } from "effect"
import { Lens } from "effect-lens"
export const ResultTypeId: unique symbol = Symbol.for("@effect-fc/Result/Result")
@@ -15,10 +16,6 @@ export type Final<A, E = never, P = never> = (Success<A> | Failure<E>) & ({} | F
export type Flags<P = never> = WillFetch | WillRefresh | Refreshing<P>
export declare namespace Result {
export interface Prototype extends Pipeable.Pipeable, Equal.Equal {
readonly [ResultTypeId]: ResultTypeId
}
export type Success<R extends Result<any, any, any>> = [R] extends [Result<infer A, infer _E, infer _P>] ? A : never
export type Failure<R extends Result<any, any, any>> = [R] extends [Result<infer _A, infer E, infer _P>] ? E : never
export type Progress<R extends Result<any, any, any>> = [R] extends [Result<infer _A, infer _E, infer P>] ? P : never
@@ -28,21 +25,21 @@ export declare namespace Flags {
export type Keys = keyof WillFetch & WillRefresh & Refreshing<any>
}
export interface Initial extends Result.Prototype {
export interface Initial extends ResultPrototype {
readonly _tag: "Initial"
}
export interface Running<P = never> extends Result.Prototype {
export interface Running<P = never> extends ResultPrototype {
readonly _tag: "Running"
readonly progress: P
}
export interface Success<A> extends Result.Prototype {
export interface Success<A> extends ResultPrototype {
readonly _tag: "Success"
readonly value: A
}
export interface Failure<E = never> extends Result.Prototype {
export interface Failure<E = never> extends ResultPrototype {
readonly _tag: "Failure"
readonly cause: Cause.Cause<E>
}
@@ -61,7 +58,11 @@ export interface Refreshing<P = never> {
}
const ResultPrototype = Object.freeze({
export interface ResultPrototype extends Pipeable.Pipeable, Equal.Equal {
readonly [ResultTypeId]: ResultTypeId
}
export const ResultPrototype: ResultPrototype = Object.freeze({
...Pipeable.Prototype,
[ResultTypeId]: ResultTypeId,
@@ -95,7 +96,7 @@ const ResultPrototype = Object.freeze({
Hash.cached(this),
)
},
} as const satisfies Result.Prototype)
} as const)
export const isResult = (u: unknown): u is Result<unknown, unknown, unknown> => Predicate.hasProperty(u, ResultTypeId)
@@ -162,52 +163,40 @@ export const toExit: {
}
export interface State<A, E = never, P = never> {
readonly get: Effect.Effect<Result<A, E, P>>
readonly set: (v: Result<A, E, P>) => Effect.Effect<void>
}
export const State = <A, E = never, P = never>(): Context.Tag<State<A, E, P>, State<A, E, P>> => Context.GenericTag("@effect-fc/Result/State")
export interface Progress<P = never> {
readonly update: <E, R>(
f: (previous: P) => Effect.Effect<P, E, R>
) => Effect.Effect<void, PreviousResultNotRunningNorRefreshing | E, R>
readonly progress: Lens.Lens<P, PreviousResultNotRunningNorRefreshing, never, never, never>
}
export const Progress = <P = never>(): Context.Tag<Progress<P>, Progress<P>> => Context.GenericTag("@effect-fc/Result/Progress")
export class PreviousResultNotRunningNorRefreshing extends Data.TaggedError("@effect-fc/Result/PreviousResultNotRunningNorRefreshing")<{
readonly previous: Result<unknown, unknown, unknown>
}> {}
export const Progress = <P = never>(): Context.Tag<Progress<P>, Progress<P>> => Context.GenericTag("@effect-fc/Result/Progress")
export const makeProgressLayer = <A, E, P = never>(): Layer.Layer<
Progress<P>,
never,
State<A, E, P>
> => Layer.effect(Progress<P>(), Effect.gen(function*() {
const state = yield* State<A, E, P>()
return {
update: <FE, FR>(f: (previous: P) => Effect.Effect<P, FE, FR>) => Effect.Do.pipe(
Effect.bind("previous", () => Effect.andThen(state.get, previous =>
(isRunning(previous) || hasRefreshingFlag(previous))
? Effect.succeed(previous)
: Effect.fail(new PreviousResultNotRunningNorRefreshing({ previous })),
)),
Effect.bind("progress", ({ previous }) => f(previous.progress)),
Effect.let("next", ({ previous, progress }) => isRunning(previous)
? running(progress)
: refreshing(previous, progress) as Final<A, E, P> & Refreshing<P>
export const makeProgressLayer = <A, E, P = never>(
state: Lens.Lens<Result<A, E, P>, never, never, never, never>
): Layer.Layer<Progress<P> | Progress<never>, never, never> => Layer.succeed(
Progress<P>() as Context.Tag<Progress<P> | Progress<never>, Progress<P> | Progress<never>>,
{
progress: state.pipe(
Lens.mapEffect(
a => (isRunning(a) || hasRefreshingFlag(a))
? Effect.succeed(a)
: Effect.fail(new PreviousResultNotRunningNorRefreshing({ previous: a })),
(_, b) => Effect.succeed(b),
),
Effect.andThen(({ next }) => state.set(next)),
),
}
}))
Lens.map(
a => a.progress,
(a, b) => isRunning(a)
? running(b)
: refreshing(a, b) as Final<A, E, P> & Refreshing<P>,
),
)
},
)
export namespace unsafeForkEffect {
export type OutputContext<A, E, R, P> = Exclude<R, State<A, E, P> | Progress<P> | Progress<never>>
export type OutputContext<R, P> = Exclude<R, Progress<P> | Progress<never>>
export interface Options<A, E, P> {
readonly initial?: Initial | Final<A, E, P>
@@ -215,55 +204,56 @@ export namespace unsafeForkEffect {
}
}
export const unsafeForkEffect = <A, E, R, P = never>(
export const unsafeForkEffect = Effect.fnUntraced(function* <A, E, R, P = never>(
effect: Effect.Effect<A, E, R>,
options?: unsafeForkEffect.Options<NoInfer<A>, NoInfer<E>, P>,
): Effect.Effect<
): Effect.fn.Return<
readonly [result: Subscribable.Subscribable<Result<A, E, P>, never, never>, fiber: Fiber.Fiber<A, E>],
never,
Scope.Scope | unsafeForkEffect.OutputContext<A, E, R, P>
> => Effect.Do.pipe(
Effect.bind("ref", () => Ref.make(options?.initial ?? initial<A, E, P>())),
Effect.bind("pubsub", () => PubSub.unbounded<Result<A, E, P>>()),
Effect.bind("fiber", ({ ref, pubsub }) => Effect.forkScoped(State<A, E, P>().pipe(
Effect.andThen(state => state.set(
Scope.Scope | unsafeForkEffect.OutputContext<R, P>
> {
const ref = (yield* SynchronizedRef.make(
options?.initial ?? initial<A, E, P>()
)) as Lens.SynchronizedRefLensImpl.SynchronizedRefWithInternals<Result<A, E, P>>
const pubsub = yield* PubSub.unbounded<Result<A, E, P>>()
const state = Lens.make({
get: Ref.get(ref.ref),
get changes() {
return Stream.unwrapScoped(Effect.map(
Effect.all([Ref.get(ref.ref), Stream.fromPubSub(pubsub, { scoped: true })]),
([latest, stream]) => Stream.concat(Stream.make(latest), stream),
))
},
commit: value => Effect.zipLeft(
Ref.set(ref.ref, value),
PubSub.publish(pubsub, value),
),
lock: Effect.succeed(ref.withLock),
})
const fiber = yield* Effect.gen(function*() {
yield* Lens.set(
state,
(isFinal(options?.initial) && hasWillRefreshFlag(options?.initial))
? refreshing(options.initial, options?.initialProgress) as Result<A, E, P>
: running(options?.initialProgress)
).pipe(
Effect.andThen(effect),
Effect.onExit(exit => Effect.andThen(
state.set(fromExit(exit)),
Effect.forkScoped(PubSub.shutdown(pubsub)),
)),
)),
Effect.provide(Layer.empty.pipe(
Layer.provideMerge(makeProgressLayer<A, E, P>()),
Layer.provideMerge(Layer.succeed(State<A, E, P>(), {
get: ref,
set: v => Effect.andThen(Ref.set(ref, v), PubSub.publish(pubsub, v))
})),
)),
))),
Effect.map(({ ref, pubsub, fiber }) => [
Subscribable.make({
get: ref,
changes: Stream.unwrapScoped(Effect.map(
Effect.all([ref, Stream.fromPubSub(pubsub, { scoped: true })]),
([latest, stream]) => Stream.concat(Stream.make(latest), stream),
)),
}),
fiber,
]),
) as Effect.Effect<
readonly [result: Subscribable.Subscribable<Result<A, E, P>, never, never>, fiber: Fiber.Fiber<A, E>],
never,
Scope.Scope | unsafeForkEffect.OutputContext<A, E, R, P>
>
: running(options?.initialProgress),
)
return yield* Effect.onExit(effect, exit => Effect.andThen(
Lens.set(state, fromExit(exit)),
Effect.forkScoped(PubSub.shutdown(pubsub)),
))
}).pipe(
Effect.forkScoped,
Effect.provide(makeProgressLayer(state)),
)
return [state, fiber] as const
})
export namespace forkEffect {
export type InputContext<R, P> = R extends Progress<infer X> ? [X] extends [P] ? R : never : R
export type OutputContext<A, E, R, P> = unsafeForkEffect.OutputContext<A, E, R, P>
export type OutputContext<R, P> = unsafeForkEffect.OutputContext<R, P>
export interface Options<A, E, P> extends unsafeForkEffect.Options<A, E, P> {}
}
@@ -274,6 +264,6 @@ export const forkEffect: {
): Effect.Effect<
readonly [result: Subscribable.Subscribable<Result<A, E, P>, never, never>, fiber: Fiber.Fiber<A, E>],
never,
Scope.Scope | forkEffect.OutputContext<A, E, R, P>
Scope.Scope | forkEffect.OutputContext<R, P>
>
} = unsafeForkEffect
+1 -1
View File
@@ -3,8 +3,8 @@ import type * as React from "react"
export const value: {
<S>(prevState: S): (self: React.SetStateAction<S>) => S
<S>(self: React.SetStateAction<S>, prevState: S): S
<S>(prevState: S): (self: React.SetStateAction<S>) => S
} = Function.dual(2, <S>(self: React.SetStateAction<S>, prevState: S): S =>
typeof self === "function"
? (self as (prevState: S) => S)(prevState)
+1 -1
View File
@@ -3,7 +3,7 @@ import * as React from "react"
import * as Component from "./Component.js"
export const useStream: {
export const use: {
<A, E, R>(
stream: Stream.Stream<A, E, R>
): Effect.Effect<Option.Option<A>, never, R>
+220
View File
@@ -0,0 +1,220 @@
import { Array, Cause, Chunk, type Context, Effect, Fiber, flow, identity, Option, ParseResult, Pipeable, Predicate, Schema, type Scope, SubscriptionRef } from "effect"
import * as Form from "./Form.js"
import * as Lens from "./Lens.js"
import * as Mutation from "./Mutation.js"
import * as Result from "./Result.js"
import * as Subscribable from "./Subscribable.js"
export const SubmittableFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/SubmittableForm")
export type SubmittableFormTypeId = typeof SubmittableFormTypeId
export interface SubmittableForm<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Form.Form<readonly [], A, I, never, never> {
readonly [SubmittableFormTypeId]: SubmittableFormTypeId
readonly schema: Schema.Schema<A, I, R>
readonly context: Context.Context<Scope.Scope | R>
readonly mutation: Mutation.Mutation<
readonly [value: A, form: SubmittableForm<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
>
readonly validationFiber: Subscribable.Subscribable<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>, never, never>
readonly run: Effect.Effect<void>
readonly submit: Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException>
}
export class SubmittableFormImpl<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Pipeable.Class() implements SubmittableForm<A, I, R, MA, ME, MR, MP> {
readonly [Form.FormTypeId]: Form.FormTypeId = Form.FormTypeId
readonly [SubmittableFormTypeId]: SubmittableFormTypeId = SubmittableFormTypeId
readonly path = [] as const
readonly encodedValue: Lens.Lens<I, never, never, never, never>
readonly isValidating: Subscribable.Subscribable<boolean, never, never>
readonly canCommit: Subscribable.Subscribable<boolean, never, never>
readonly isCommitting: Subscribable.Subscribable<boolean, never, never>
constructor(
readonly schema: Schema.Schema<A, I, R>,
readonly context: Context.Context<Scope.Scope | R>,
readonly mutation: Mutation.Mutation<
readonly [value: A, form: SubmittableForm<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
>,
readonly value: Lens.Lens<Option.Option<A>, never, never, never, never>,
readonly internalEncodedValue: Lens.Lens<I, never, never, never, never>,
readonly issues: Lens.Lens<readonly ParseResult.ArrayFormatterIssue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>, never, never, never, never>,
readonly runSemaphore: Effect.Semaphore,
) {
super()
this.encodedValue = Effect.all([
Effect.succeed(this),
Effect.succeed(Lens.asLensImpl(this.internalEncodedValue)),
]).pipe(
Effect.map(([self, parent]) => Lens.make({
get: parent.get,
get changes() { return parent.changes },
commit: a => Effect.andThen(
Effect.flatMap(
parent.resolve,
resolved => resolved.commit(Effect.succeed(a)),
),
self.synchronizeEncodedValue(a),
),
lock: parent.lock,
})),
Lens.unwrap,
)
this.isValidating = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.map(self.validationFiber, Option.isSome)),
Subscribable.unwrap,
)
this.canCommit = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.map(
Subscribable.zipLatestAll(self.value, self.issues, self.validationFiber, self.mutation.result),
([value, issues, validationFiber, result]) => (
Option.isSome(value) &&
Array.isEmptyReadonlyArray(issues) &&
Option.isNone(validationFiber) &&
!(Result.isRunning(result) || Result.hasRefreshingFlag(result))
),
)),
Subscribable.unwrap,
)
this.isCommitting = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.map(
self.mutation.result,
result => Result.isRunning(result) || Result.hasRefreshingFlag(result),
)),
Subscribable.unwrap,
)
}
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void, never, never> {
return Lens.get(this.validationFiber).pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(Effect.forkScoped(
Effect.ensuring(
Schema.decode(this.schema, { errors: "all" })(encodedValue),
Lens.set(this.validationFiber, Option.none()),
)
)),
Effect.tap(fiber => Lens.set(this.validationFiber, Option.some(fiber))),
Effect.flatMap(Fiber.join),
Effect.tap(() => Lens.set(this.issues, Array.empty())),
Effect.flatMap(value => Lens.set(this.value, Option.some(value))),
Effect.catchIf(
ParseResult.isParseError,
flow(
ParseResult.ArrayFormatter.formatError,
Effect.flatMap(v => Lens.set(this.issues, v)),
),
),
Effect.provide(this.context),
)
}
get run(): Effect.Effect<void, never, never> {
return Lens.get(this.encodedValue).pipe(
Effect.flatMap(v => Schema.decode(this.schema)(v)),
Effect.option,
Effect.flatMap(v => Lens.set(this.value, v)),
Effect.provide(this.context),
this.runSemaphore.withPermits(1),
)
}
get submit(): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementException, never> {
return Lens.get(this.value).pipe(
Effect.flatMap(identity),
Effect.flatMap(value => this.submitValue(value)),
)
}
submitValue(value: A): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, never, never> {
return Effect.whenEffect(
Effect.tap(
this.mutation.mutate([value, this as any]),
result => Result.isFailure(result)
? Option.match(
Chunk.findFirst(
Cause.failures(result.cause as Cause.Cause<ParseResult.ParseError>),
e => e._tag === "ParseError",
),
{
onSome: e => Effect.flatMap(
ParseResult.ArrayFormatter.formatError(e),
v => Lens.set(this.issues, v),
),
onNone: () => Effect.void,
},
)
: Effect.void
),
this.canCommit.get,
)
}
}
export const isSubmittableForm = (u: unknown): u is SubmittableForm<unknown, unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, SubmittableFormTypeId)
export declare namespace make {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Mutation.make.Options<
readonly [value: NoInfer<A>, form: SubmittableForm<NoInfer<A>, NoInfer<I>, NoInfer<R>, unknown, unknown, unknown>],
MA, ME, MR, MP
> {
readonly schema: Schema.Schema<A, I, R>
readonly initialEncodedValue: NoInfer<I>
}
}
export const make = Effect.fnUntraced(function* <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: make.Options<A, I, R, MA, ME, MR, MP>
): Effect.fn.Return<
SubmittableForm<A, I, R, MA, ME, Result.forkEffect.OutputContext<MR, MP>, MP>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MR, MP>
> {
return new SubmittableFormImpl(
options.schema,
yield* Effect.context<Scope.Scope | R>(),
yield* Mutation.make(options),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<A>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(options.initialEncodedValue)),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly ParseResult.ArrayFormatterIssue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, ParseResult.ParseError>>())),
yield* Effect.makeSemaphore(1),
)
})
export declare namespace service {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends make.Options<A, I, R, MA, ME, MR, MP> {}
}
export const service = <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: service.Options<A, I, R, MA, ME, MR, MP>
): Effect.Effect<
SubmittableForm<A, I, R, MA, ME, Result.forkEffect.OutputContext<MR, MP>, MP>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MR, MP>
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)
@@ -0,0 +1,129 @@
import { render, screen, waitFor } from "@testing-library/react"
import { Effect, Fiber, Layer, Stream, SubscriptionRef } from "effect"
import { Lens } from "effect-lens"
import { describe, expect, it } from "vitest"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
import * as Subscribable from "./Subscribable.js"
const makeRuntime = async () => {
const runtime = ReactRuntime.make(Layer.empty)
const effectRuntime = await Effect.runPromise(runtime.runtime.runtimeEffect)
return {
runtime,
effectRuntime,
dispose: () => Effect.runPromise(runtime.runtime.disposeEffect),
}
}
describe("Subscribable", () => {
it("zipLatestAll reads current values from all inputs", async () => {
const leftRef = await Effect.runPromise(SubscriptionRef.make(1))
const rightRef = await Effect.runPromise(SubscriptionRef.make("a"))
const left = Lens.fromSubscriptionRef(leftRef)
const right = Lens.fromSubscriptionRef(rightRef)
const zipped = Subscribable.zipLatestAll(left, right)
expect(await Effect.runPromise(zipped.get)).toEqual([1, "a"])
})
it("zipLatestAll emits updates when any input changes", async () => {
const leftRef = await Effect.runPromise(SubscriptionRef.make(1))
const rightRef = await Effect.runPromise(SubscriptionRef.make("a"))
const left = Lens.fromSubscriptionRef(leftRef)
const right = Lens.fromSubscriptionRef(rightRef)
const zipped = Subscribable.zipLatestAll(left, right)
const values: Array<readonly [number, string]> = []
const collector = Effect.runFork(Effect.scoped(zipped.changes.pipe(
Stream.runForEach(value => Effect.sync(() => {
values.push(value as readonly [number, string])
})),
)))
await Effect.runPromise(Lens.set(left, 2))
await waitFor(() => expect(values).toContainEqual([2, "a"]))
await Effect.runPromise(Lens.set(right, "b"))
await waitFor(() => expect(values).toContainEqual([2, "b"]))
Fiber.interruptFork(collector)
})
it("useAll returns the latest values and rerenders when any input changes", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const countRef = await Effect.runPromise(SubscriptionRef.make(1))
const labelRef = await Effect.runPromise(SubscriptionRef.make("a"))
const count = Lens.fromSubscriptionRef(countRef)
const label = Lens.fromSubscriptionRef(labelRef)
const Probe = Component.makeUntraced("SubscribableUseAllProbe")(function*() {
const [currentCount, currentLabel] = yield* Subscribable.useAll([count, label])
return <div>{`${currentCount}:${currentLabel}`}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("1:a")
await Effect.runPromise(Lens.set(count, 2))
await screen.findByText("2:a")
await Effect.runPromise(Lens.set(label, "b"))
await screen.findByText("2:b")
view.unmount()
await dispose()
})
it("useAll respects the provided equivalence when processing updates", async () => {
const { runtime, effectRuntime, dispose } = await makeRuntime()
const itemRef = await Effect.runPromise(SubscriptionRef.make({ id: 1, label: "first" }))
const flagRef = await Effect.runPromise(SubscriptionRef.make(true))
const item = Lens.fromSubscriptionRef(itemRef)
const flag = Lens.fromSubscriptionRef(flagRef)
const Probe = Component.makeUntraced("SubscribableUseAllEquivalenceProbe")(function*() {
const [currentItem, currentFlag] = yield* Subscribable.useAll([item, flag], {
equivalence: ([selfItem, selfFlag], [thatItem, thatFlag]) =>
selfItem.id === thatItem.id && selfFlag === thatFlag,
})
return <div>{`${currentItem.label}:${currentFlag ? "on" : "off"}`}</div>
}).pipe(
Component.withRuntime(runtime.context)
)
const view = render(
<runtime.context.Provider value={effectRuntime}>
<Probe />
</runtime.context.Provider>
)
await screen.findByText("first:on")
await Effect.runPromise(Lens.set(item, { id: 1, label: "ignored" }))
await waitFor(() => expect(screen.getByText("first:on")).toBeTruthy())
expect(screen.queryByText("ignored:on")).toBeNull()
await Effect.runPromise(Lens.set(flag, false))
await screen.findByText("ignored:off")
await Effect.runPromise(Lens.set(item, { id: 2, label: "updated" }))
await screen.findByText("updated:off")
view.unmount()
await dispose()
})
})
+8 -7
View File
@@ -1,8 +1,11 @@
import { Effect, Equivalence, Stream, Subscribable } from "effect"
import { Effect, Equivalence, Stream } from "effect"
import { Subscribable } from "effect-lens"
import * as React from "react"
import * as Component from "./Component.js"
export * from "effect-lens/Subscribable"
export const zipLatestAll = <const T extends readonly Subscribable.Subscribable<any, any, any>[]>(
...elements: T
): Subscribable.Subscribable<
@@ -16,7 +19,7 @@ export const zipLatestAll = <const T extends readonly Subscribable.Subscribable<
changes: Stream.zipLatestAll(...elements.map(v => v.changes)),
}) as any
export declare namespace useSubscribables {
export declare namespace useAll {
export type Success<T extends readonly Subscribable.Subscribable<any, any, any>[]> = [T[number]] extends [never]
? never
: { [K in keyof T]: T[K] extends Subscribable.Subscribable<infer A, infer _E, infer _R> ? A : never }
@@ -26,11 +29,11 @@ export declare namespace useSubscribables {
}
}
export const useSubscribables = Effect.fnUntraced(function* <const T extends readonly Subscribable.Subscribable<any, any, any>[]>(
export const useAll = Effect.fnUntraced(function* <const T extends readonly Subscribable.Subscribable<any, any, any>[]>(
elements: T,
options?: useSubscribables.Options<useSubscribables.Success<NoInfer<T>>>,
options?: useAll.Options<useAll.Success<NoInfer<T>>>,
): Effect.fn.Return<
useSubscribables.Success<T>,
useAll.Success<T>,
[T[number]] extends [never] ? never : T[number] extends Subscribable.Subscribable<infer _A, infer E, infer _R> ? E : never,
[T[number]] extends [never] ? never : T[number] extends Subscribable.Subscribable<infer _A, infer _E, infer R> ? R : never
> {
@@ -48,5 +51,3 @@ export const useSubscribables = Effect.fnUntraced(function* <const T extends rea
return reactStateValue as any
})
export * from "effect/Subscribable"
-61
View File
@@ -1,61 +0,0 @@
import { Effect, Equivalence, Ref, Stream, SubscriptionRef } from "effect"
import * as React from "react"
import * as Component from "./Component.js"
import * as SetStateAction from "./SetStateAction.js"
export declare namespace useSubscriptionRefState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useSubscriptionRefState = Effect.fnUntraced(function* <A>(
ref: SubscriptionRef.SubscriptionRef<A>,
options?: useSubscriptionRefState.Options<NoInfer<A>>,
): Effect.fn.Return<readonly [A, React.Dispatch<React.SetStateAction<A>>]> {
const [reactStateValue, setReactStateValue] = React.useState(yield* Component.useOnMount(() => ref))
yield* Component.useReactEffect(() => Effect.forkScoped(
Stream.runForEach(
Stream.changesWith(ref.changes, options?.equivalence ?? Equivalence.strict()),
v => Effect.sync(() => setReactStateValue(v)),
)
), [ref])
const setValue = yield* Component.useCallbackSync(
(setStateAction: React.SetStateAction<A>) => Effect.andThen(
Ref.updateAndGet(ref, prevState => SetStateAction.value(setStateAction, prevState)),
v => setReactStateValue(v),
),
[ref],
)
return [reactStateValue, setValue]
})
export declare namespace useSubscriptionRefFromState {
export interface Options<A> {
readonly equivalence?: Equivalence.Equivalence<A>
}
}
export const useSubscriptionRefFromState = Effect.fnUntraced(function* <A>(
[value, setValue]: readonly [A, React.Dispatch<React.SetStateAction<A>>],
options?: useSubscriptionRefFromState.Options<NoInfer<A>>,
): Effect.fn.Return<SubscriptionRef.SubscriptionRef<A>> {
const ref = yield* Component.useOnChange(() => Effect.tap(
SubscriptionRef.make(value),
ref => Effect.forkScoped(
Stream.runForEach(
Stream.changesWith(ref.changes, options?.equivalence ?? Equivalence.strict()),
v => Effect.sync(() => setValue(v)),
)
),
), [setValue])
yield* Component.useReactEffect(() => Ref.set(ref, value), [value])
return ref
})
export * from "effect/SubscriptionRef"
@@ -1,186 +0,0 @@
import { Chunk, Effect, Effectable, Option, Predicate, Readable, Ref, Stream, Subscribable, SubscriptionRef, SynchronizedRef, type Types, type Unify } from "effect"
import * as PropertyPath from "./PropertyPath.js"
export const SubscriptionSubRefTypeId: unique symbol = Symbol.for("@effect-fc/SubscriptionSubRef/SubscriptionSubRef")
export type SubscriptionSubRefTypeId = typeof SubscriptionSubRefTypeId
export interface SubscriptionSubRef<in out A, in out B extends SubscriptionRef.SubscriptionRef<any>>
extends SubscriptionSubRef.Variance<A, B>, SubscriptionRef.SubscriptionRef<A> {
readonly parent: B
readonly [Unify.typeSymbol]?: unknown
readonly [Unify.unifySymbol]?: SubscriptionSubRefUnify<this>
readonly [Unify.ignoreSymbol]?: SubscriptionSubRefUnifyIgnore
}
export declare namespace SubscriptionSubRef {
export interface Variance<in out A, in out B> {
readonly [SubscriptionSubRefTypeId]: {
readonly _A: Types.Invariant<A>
readonly _B: Types.Invariant<B>
}
}
}
export interface SubscriptionSubRefUnify<A extends { [Unify.typeSymbol]?: any }> extends SubscriptionRef.SubscriptionRefUnify<A> {
SubscriptionSubRef?: () => Extract<A[Unify.typeSymbol], SubscriptionSubRef<any, any>>
}
export interface SubscriptionSubRefUnifyIgnore extends SubscriptionRef.SubscriptionRefUnifyIgnore {
SubscriptionRef?: true
}
const refVariance = { _A: (_: any) => _ }
const synchronizedRefVariance = { _A: (_: any) => _ }
const subscriptionRefVariance = { _A: (_: any) => _ }
const subscriptionSubRefVariance = { _A: (_: any) => _, _B: (_: any) => _ }
class SubscriptionSubRefImpl<in out A, in out B extends SubscriptionRef.SubscriptionRef<any>>
extends Effectable.Class<A> implements SubscriptionSubRef<A, B> {
readonly [Readable.TypeId]: Readable.TypeId = Readable.TypeId
readonly [Subscribable.TypeId]: Subscribable.TypeId = Subscribable.TypeId
readonly [Ref.RefTypeId] = refVariance
readonly [SynchronizedRef.SynchronizedRefTypeId] = synchronizedRefVariance
readonly [SubscriptionRef.SubscriptionRefTypeId] = subscriptionRefVariance
readonly [SubscriptionSubRefTypeId] = subscriptionSubRefVariance
readonly get: Effect.Effect<A>
constructor(
readonly parent: B,
readonly getter: (parentValue: Effect.Effect.Success<B>) => A,
readonly setter: (parentValue: Effect.Effect.Success<B>, value: A) => Effect.Effect.Success<B>,
) {
super()
this.get = Effect.map(this.parent, this.getter)
}
commit() {
return this.get
}
get changes(): Stream.Stream<A> {
return Stream.unwrap(
Effect.map(this.get, a => Stream.concat(
Stream.make(a),
Stream.map(this.parent.changes, this.getter),
))
)
}
modify<C>(f: (a: A) => readonly [C, A]): Effect.Effect<C> {
return this.modifyEffect(a => Effect.succeed(f(a)))
}
modifyEffect<C, E, R>(f: (a: A) => Effect.Effect<readonly [C, A], E, R>): Effect.Effect<C, E, R> {
return Effect.Do.pipe(
Effect.bind("b", (): Effect.Effect<Effect.Effect.Success<B>> => this.parent),
Effect.bind("ca", ({ b }) => f(this.getter(b))),
Effect.tap(({ b, ca: [, a] }) => SubscriptionRef.set(this.parent, this.setter(b, a))),
Effect.map(({ ca: [c] }) => c),
)
}
}
export const isSubscriptionSubRef = (u: unknown): u is SubscriptionSubRef<unknown, SubscriptionRef.SubscriptionRef<unknown>> => Predicate.hasProperty(u, SubscriptionSubRefTypeId)
export const makeFromGetSet = <A, B extends SubscriptionRef.SubscriptionRef<any>>(
parent: B,
options: {
readonly get: (parentValue: Effect.Effect.Success<B>) => A
readonly set: (parentValue: Effect.Effect.Success<B>, value: A) => Effect.Effect.Success<B>
},
): SubscriptionSubRef<A, B> => new SubscriptionSubRefImpl(parent, options.get, options.set)
export const makeFromPath = <
B extends SubscriptionRef.SubscriptionRef<any>,
const P extends PropertyPath.Paths<Effect.Effect.Success<B>>,
>(
parent: B,
path: P,
): SubscriptionSubRef<PropertyPath.ValueFromPath<Effect.Effect.Success<B>, P>, B> => new SubscriptionSubRefImpl(
parent,
parentValue => Option.getOrThrow(PropertyPath.get(parentValue, path)),
(parentValue, value) => Option.getOrThrow(PropertyPath.immutableSet(parentValue, path, value)),
)
export const makeFromChunkIndex: {
<B extends SubscriptionRef.SubscriptionRef<Chunk.NonEmptyChunk<any>>>(
parent: B,
index: number,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.NonEmptyChunk<infer A> ? A : never,
B
>
<B extends SubscriptionRef.SubscriptionRef<Chunk.Chunk<any>>>(
parent: B,
index: number,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.Chunk<infer A> ? A : never,
B
>
} = (
parent: SubscriptionRef.SubscriptionRef<Chunk.Chunk<any>>,
index: number,
) => new SubscriptionSubRefImpl(
parent,
parentValue => Chunk.unsafeGet(parentValue, index),
(parentValue, value) => Chunk.replace(parentValue, index, value),
) as any
export const makeFromChunkFindFirst: {
<B extends SubscriptionRef.SubscriptionRef<Chunk.NonEmptyChunk<any>>>(
parent: B,
findFirstPredicate: Predicate.Predicate<Effect.Effect.Success<B> extends Chunk.NonEmptyChunk<infer A> ? A : never>,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.NonEmptyChunk<infer A> ? A : never,
B
>
<B extends SubscriptionRef.SubscriptionRef<Chunk.Chunk<any>>>(
parent: B,
findFirstPredicate: Predicate.Predicate<Effect.Effect.Success<B> extends Chunk.Chunk<infer A> ? A : never>,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.Chunk<infer A> ? A : never,
B
>
} = (
parent: SubscriptionRef.SubscriptionRef<Chunk.Chunk<never>>,
findFirstPredicate: Predicate.Predicate.Any,
) => new SubscriptionSubRefImpl(
parent,
parentValue => Option.getOrThrow(Chunk.findFirst(parentValue, findFirstPredicate)),
(parentValue, value) => Option.getOrThrow(Option.andThen(
Chunk.findFirstIndex(parentValue, findFirstPredicate),
index => Chunk.replace(parentValue, index, value),
)),
) as any
export const makeFromChunkFindLast: {
<B extends SubscriptionRef.SubscriptionRef<Chunk.NonEmptyChunk<any>>>(
parent: B,
findLastPredicate: Predicate.Predicate<Effect.Effect.Success<B> extends Chunk.NonEmptyChunk<infer A> ? A : never>,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.NonEmptyChunk<infer A> ? A : never,
B
>
<B extends SubscriptionRef.SubscriptionRef<Chunk.Chunk<any>>>(
parent: B,
findLastPredicate: Predicate.Predicate<Effect.Effect.Success<B> extends Chunk.Chunk<infer A> ? A : never>,
): SubscriptionSubRef<
Effect.Effect.Success<B> extends Chunk.Chunk<infer A> ? A : never,
B
>
} = (
parent: SubscriptionRef.SubscriptionRef<Chunk.Chunk<never>>,
findLastPredicate: Predicate.Predicate.Any,
) => new SubscriptionSubRefImpl(
parent,
parentValue => Option.getOrThrow(Chunk.findLast(parentValue, findLastPredicate)),
(parentValue, value) => Option.getOrThrow(Option.andThen(
Chunk.findLastIndex(parentValue, findLastPredicate),
index => Chunk.replace(parentValue, index, value),
)),
) as any
+223
View File
@@ -0,0 +1,223 @@
import { Array, type Context, Effect, Equal, Fiber, flow, Option, ParseResult, Pipeable, Predicate, Schema, type Scope, Stream, SubscriptionRef } from "effect"
import * as Form from "./Form.js"
import * as Lens from "./Lens.js"
import * as Subscribable from "./Subscribable.js"
export const SynchronizedFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/SynchronizedForm")
export type SynchronizedFormTypeId = typeof SynchronizedFormTypeId
export interface SynchronizedForm<
in out A,
in out I = A,
in out R = never,
in out TER = never,
in out TEW = never,
in out TRR = never,
in out TRW = never,
> extends Form.Form<readonly [], A, I, TER, TER | TEW> {
readonly [SynchronizedFormTypeId]: SynchronizedFormTypeId
readonly schema: Schema.Schema<A, I, R>
readonly context: Context.Context<Scope.Scope | R | TRR | TRW>
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>
readonly validationFiber: Subscribable.Subscribable<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>, never, never>
readonly run: Effect.Effect<void, TER>
}
export class SynchronizedFormImpl<
in out A,
in out I = A,
in out R = never,
in out TER = never,
in out TEW = never,
in out TRR = never,
in out TRW = never,
> extends Pipeable.Class() implements SynchronizedForm<A, I, R, TER, TEW, TRR, TRW> {
readonly [Form.FormTypeId]: Form.FormTypeId = Form.FormTypeId
readonly [SynchronizedFormTypeId]: SynchronizedFormTypeId = SynchronizedFormTypeId
readonly path = [] as const
readonly value: Subscribable.Subscribable<Option.Option<A>, never, never>
readonly encodedValue: Lens.Lens<I, TER, TER | TEW, never, never>
readonly isValidating: Subscribable.Subscribable<boolean, never, never>
readonly canCommit: Subscribable.Subscribable<boolean, never, never>
constructor(
readonly schema: Schema.Schema<A, I, R>,
readonly context: Context.Context<Scope.Scope | R | TRR | TRW>,
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>,
readonly internalEncodedValue: Lens.Lens<I, never, never, never, never>,
readonly issues: Lens.Lens<readonly ParseResult.ArrayFormatterIssue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, ParseResult.ParseError>>, never, never, never, never>,
readonly isCommitting: Lens.Lens<boolean, never, never>,
readonly runSemaphore: Effect.Semaphore,
) {
super()
this.value = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.make({
get: Effect.provide(Effect.option(self.target.get), self.context),
get changes() {
return Stream.provideContext(
self.target.changes.pipe(
Stream.map(Option.some),
Stream.catchAll(() => Stream.make(Option.none())),
),
self.context,
)
},
})),
Subscribable.unwrap,
)
this.encodedValue = Effect.all([
Effect.succeed(this),
Effect.succeed(Lens.asLensImpl(this.internalEncodedValue)),
]).pipe(
Effect.map(([self, parent]) => Lens.make<I, TER, TER | TEW, never, never>({
get: parent.get,
get changes() { return parent.changes },
commit: a => Effect.andThen(
Effect.flatMap(
parent.resolve,
resolved => resolved.commit(Effect.succeed(a)),
),
self.synchronizeEncodedValue(a),
),
lock: parent.lock,
})),
Lens.unwrap,
)
this.isValidating = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.map(self.validationFiber, Option.isSome)),
Subscribable.unwrap,
)
this.canCommit = Effect.succeed(this).pipe(
Effect.map(self => Subscribable.map(
Subscribable.zipLatestAll(self.issues, self.validationFiber, self.isCommitting),
([issues, validationFiber, isCommitting]) => (
Array.isEmptyReadonlyArray(issues) &&
Option.isNone(validationFiber) &&
!isCommitting
),
)),
Subscribable.unwrap,
)
}
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void, TER | TEW, never> {
return Lens.get(this.validationFiber).pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(Effect.forkScoped(
Effect.ensuring(
Schema.decode(this.schema, { errors: "all" })(encodedValue),
Lens.set(this.validationFiber, Option.none()),
)
)),
Effect.tap(fiber => Lens.set(this.validationFiber, Option.some(fiber))),
Effect.flatMap(Fiber.join),
Effect.flatMap(value => Effect.ensuring(
Lens.set(this.isCommitting, true).pipe(
Effect.andThen(Lens.set(this.issues, Array.empty())),
Effect.andThen(Lens.set(this.target, value)),
),
Lens.set(this.isCommitting, false),
)),
Effect.catchIf(
ParseResult.isParseError,
flow(
ParseResult.ArrayFormatter.formatError,
Effect.flatMap(v => Lens.set(this.issues, v)),
),
),
Effect.provide(this.context),
)
}
get run(): Effect.Effect<void, TER, never> {
return this.runSemaphore.withPermits(1)(Effect.provide(
Stream.runForEach(
Stream.drop(this.target.changes, 1),
targetValue => Schema.encode(this.schema, { errors: "all" })(targetValue).pipe(
Effect.flatMap(encodedValue => Effect.whenEffect(
Effect.andThen(
Lens.set(this.issues, Array.empty()),
Lens.set(this.internalEncodedValue, encodedValue),
),
Effect.map(
Lens.get(this.internalEncodedValue),
currentEncodedValue => !Equal.equals(encodedValue, currentEncodedValue),
),
)),
Effect.ignore,
),
),
this.context,
))
}
}
export const isSynchronizedForm = (u: unknown): u is SynchronizedForm<unknown, unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, SynchronizedFormTypeId)
export declare namespace make {
export interface Options<in out A, in out I = A, in out R = never, in out TER = never, in out TEW = never, in out TRR = never, in out TRW = never> {
readonly schema: Schema.Schema<A, I, R>
readonly target: Lens.Lens<A, TER, TEW, TRR, TRW>
readonly initialEncodedValue?: NoInfer<I>
}
}
export const make = Effect.fnUntraced(function* <A, I = A, R = never, TER = never, TEW = never, TRR = never, TRW = never>(
options: make.Options<A, I, R, TER, TEW, TRR, TRW>
): Effect.fn.Return<
SynchronizedForm<A, I, R, TER, TEW, TRR, TRW>,
ParseResult.ParseError | TER,
Scope.Scope | R | TRR | TRW
> {
const initialEncodedValue = options.initialEncodedValue !== undefined
? options.initialEncodedValue
: yield* Effect.flatMap(
Lens.get(options.target),
Schema.encode(options.schema, { errors: "all" }),
)
return new SynchronizedFormImpl(
options.schema,
yield* Effect.context<Scope.Scope | R | TRR | TRW>(),
options.target,
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(initialEncodedValue)),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly ParseResult.ArrayFormatterIssue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, ParseResult.ParseError>>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(false)),
yield* Effect.makeSemaphore(1),
)
})
export declare namespace service {
export interface Options<in out A, in out I = A, in out R = never, in out TER = never, in out TEW = never, in out TRR = never, in out TRW = never>
extends make.Options<A, I, R, TER, TEW, TRR, TRW> {}
}
export const service = <A, I = A, R = never, TER = never, TEW = never, TRR = never, TRW = never>(
options: service.Options<A, I, R, TER, TEW, TRR, TRW>
): Effect.Effect<
SynchronizedForm<A, I, R, TER, TEW, TRR, TRW>,
ParseResult.ParseError | TER,
Scope.Scope | R | TRR | TRW
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)
+3 -3
View File
@@ -2,9 +2,9 @@ export * as Async from "./Async.js"
export * as Component from "./Component.js"
export * as ErrorObserver from "./ErrorObserver.js"
export * as Form from "./Form.js"
export * as Lens from "./Lens.js"
export * as Memoized from "./Memoized.js"
export * as Mutation from "./Mutation.js"
export * as PropertyPath from "./PropertyPath.js"
export * as PubSub from "./PubSub.js"
export * as Query from "./Query.js"
export * as QueryClient from "./QueryClient.js"
@@ -12,6 +12,6 @@ export * as ReactRuntime from "./ReactRuntime.js"
export * as Result from "./Result.js"
export * as SetStateAction from "./SetStateAction.js"
export * as Stream from "./Stream.js"
export * as SubmittableForm from "./SubmittableForm.js"
export * as Subscribable from "./Subscribable.js"
export * as SubscriptionRef from "./SubscriptionRef.js"
export * as SubscriptionSubRef from "./SubscriptionSubRef.js"
export * as SynchronizedForm from "./SynchronizedForm.js"
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["**/setup-tests.ts", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"]
}
+2 -1
View File
@@ -25,6 +25,7 @@
"noPropertyAccessFromIndexSignature": false,
// Build
"rootDir": "./src",
"outDir": "./dist",
"declaration": true,
"sourceMap": true,
@@ -34,5 +35,5 @@
]
},
"include": ["./src"]
"include": ["./src"],
}
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
environment: "jsdom",
include: ["./src/**/*.test.ts?(x)"],
},
})
+26
View File
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.tanstack
+10
View File
@@ -0,0 +1,10 @@
# Effect FC Next Example
Minimal React example for `effect-fc-next`, Effect V4, and `effect-lens@2`.
```bash
bun run dev
```
The counter demonstrates a V4 `SubscriptionRef` exposed as an Effect Lens and
rendered through an Effect-FC component.
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://biomejs.dev/schemas/latest/schema.json",
"root": false,
"extends": "//",
"files": {
"includes": ["./src/**", "!src/routeTree.gen.ts"]
}
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+41
View File
@@ -0,0 +1,41 @@
{
"name": "@effect-fc/example-next",
"version": "0.0.0",
"type": "module",
"private": true,
"scripts": {
"build": "tsc -b && vite build",
"dev": "vite",
"lint:tsc": "tsc -b --noEmit",
"lint:biome": "biome lint",
"preview": "vite preview",
"clean:cache": "rm -rf .turbo node_modules/.tmp node_modules/.vite* .tanstack",
"clean:dist": "rm -rf dist",
"clean:modules": "rm -rf node_modules"
},
"devDependencies": {
"@effect-view/vite-plugin": "workspace:*",
"@tanstack/react-router": "^1.170.10",
"@tanstack/react-router-devtools": "^1.167.0",
"@tanstack/router-plugin": "^1.168.13",
"@types/react": "^19.2.15",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.2",
"globals": "^17.6.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"vite": "^8.0.16"
},
"dependencies": {
"@effect/platform-browser": "4.0.0-beta.98",
"@radix-ui/themes": "^3.3.0",
"effect": "4.0.0-beta.98",
"effect-fc-next": "workspace:*",
"react-icons": "^5.6.0"
},
"overrides": {
"@types/react": "^19.2.15",
"effect": "4.0.0-beta.98",
"react": "^19.2.6"
}
}
View File
@@ -0,0 +1,56 @@
import { Callout, Flex, Spinner, TextField } from "@radix-ui/themes"
import { Array, Option, Struct } from "effect"
import { Component, Form, View } from "effect-fc-next"
import type * as React from "react"
export declare namespace TextFieldFormInputView {
export interface Props<out P extends readonly PropertyKey[], A, ER, EW>
extends Omit<TextField.RootProps, "form">, Form.useInput.Options {
readonly form: Form.Form<P, A, string, ER, EW>
}
export type Signature = <P extends readonly PropertyKey[], A, ER, EW>(props: Props<P, A, ER, EW>) => React.ReactNode
}
export const TextFieldFormInputView = Component.make("TextFieldFormInputView")(function*(
props: TextFieldFormInputView.Props<readonly PropertyKey[], any, any, any>
) {
const input = yield* Form.useInput(props.form, props)
const [issues, isValidating, isCommitting] = yield* View.useAll([
props.form.issues,
props.form.isValidating,
props.form.isCommitting,
])
return (
<Flex direction="column" gap="1">
<TextField.Root
value={input.value}
onChange={e => input.setValue(e.target.value)}
disabled={isCommitting}
{...Struct.omit(props, ["form"])}
>
{isValidating &&
<TextField.Slot side="right">
<Spinner />
</TextField.Slot>
}
{props.children}
</TextField.Root>
{Option.match(Array.head(issues), {
onSome: issue => (
<Callout.Root>
<Callout.Text>{issue.message}</Callout.Text>
</Callout.Root>
),
onNone: () => <></>,
})}
</Flex>
)
}).pipe(
Component.withSignature<TextFieldFormInputView.Signature>()
)
@@ -0,0 +1,64 @@
import { Callout, Flex, Spinner, Switch, TextField } from "@radix-ui/themes"
import { Array, Option, Struct } from "effect"
import { Component, Form, View } from "effect-fc-next"
import type * as React from "react"
export declare namespace TextFieldOptionalFormInputView {
export interface Props<out P extends readonly PropertyKey[], A, ER, EW>
extends Omit<TextField.RootProps, "form" | "defaultValue">, Form.useOptionalInput.Options<string> {
readonly form: Form.Form<P, A, Option.Option<string>, ER, EW>
}
export type Signature = <P extends readonly PropertyKey[], A, ER, EW>(props: Props<P, A, ER, EW>) => React.ReactNode
}
export const TextFieldOptionalFormInputView = Component.make("TextFieldOptionalFormInputView")(function*(
props: TextFieldOptionalFormInputView.Props<readonly PropertyKey[], any, any, any>
) {
const input = yield* Form.useOptionalInput(props.form, props)
const [issues, isValidating, isCommitting] = yield* View.useAll([
props.form.issues,
props.form.isValidating,
props.form.isCommitting,
])
return (
<Flex direction="column" gap="1">
<TextField.Root
value={input.value}
onChange={e => input.setValue(e.target.value)}
disabled={!input.enabled || isCommitting}
{...Struct.omit(props, ["form", "defaultValue"])}
>
<TextField.Slot side="left">
<Switch
size="1"
checked={input.enabled}
onCheckedChange={input.setEnabled}
/>
</TextField.Slot>
{isValidating &&
<TextField.Slot side="right">
<Spinner />
</TextField.Slot>
}
{props.children}
</TextField.Root>
{Option.match(Array.head(issues), {
onSome: issue => (
<Callout.Root>
<Callout.Text>{issue.message}</Callout.Text>
</Callout.Root>
),
onNone: () => <></>,
})}
</Flex>
)
}).pipe(
Component.withSignature<TextFieldOptionalFormInputView.Signature>()
)
+21
View File
@@ -0,0 +1,21 @@
import { createRouter, RouterProvider } from "@tanstack/react-router"
import { ReactRuntime } from "effect-fc-next"
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { routeTree } from "./routeTree.gen"
import { runtime } from "./runtime"
const router = createRouter({ routeTree })
declare module "@tanstack/react-router" {
interface Register { router: typeof router }
}
// biome-ignore lint/style/noNonNullAssertion: the Vite template provides this element
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ReactRuntime.Provider runtime={runtime}>
<RouterProvider router={router} />
</ReactRuntime.Provider>
</StrictMode>,
)
+149
View File
@@ -0,0 +1,149 @@
/* eslint-disable */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
import { Route as AsyncRouteImport } from './routes/async'
import { Route as BlankRouteImport } from './routes/blank'
import { Route as FormRouteImport } from './routes/form'
import { Route as LensformRouteImport } from './routes/lensform'
import { Route as QueryRouteImport } from './routes/query'
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const AsyncRoute = AsyncRouteImport.update({
id: '/async',
path: '/async',
getParentRoute: () => rootRouteImport,
} as any)
const BlankRoute = BlankRouteImport.update({
id: '/blank',
path: '/blank',
getParentRoute: () => rootRouteImport,
} as any)
const FormRoute = FormRouteImport.update({
id: '/form',
path: '/form',
getParentRoute: () => rootRouteImport,
} as any)
const LensformRoute = LensformRouteImport.update({
id: '/lensform',
path: '/lensform',
getParentRoute: () => rootRouteImport,
} as any)
const QueryRoute = QueryRouteImport.update({
id: '/query',
path: '/query',
getParentRoute: () => rootRouteImport,
} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
id: '__root__' | '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
AsyncRoute: typeof AsyncRoute
BlankRoute: typeof BlankRoute
FormRoute: typeof FormRoute
LensformRoute: typeof LensformRoute
QueryRoute: typeof QueryRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
'/async': {
id: '/async'
path: '/async'
fullPath: '/async'
preLoaderRoute: typeof AsyncRouteImport
parentRoute: typeof rootRouteImport
}
'/blank': {
id: '/blank'
path: '/blank'
fullPath: '/blank'
preLoaderRoute: typeof BlankRouteImport
parentRoute: typeof rootRouteImport
}
'/form': {
id: '/form'
path: '/form'
fullPath: '/form'
preLoaderRoute: typeof FormRouteImport
parentRoute: typeof rootRouteImport
}
'/lensform': {
id: '/lensform'
path: '/lensform'
fullPath: '/lensform'
preLoaderRoute: typeof LensformRouteImport
parentRoute: typeof rootRouteImport
}
'/query': {
id: '/query'
path: '/query'
fullPath: '/query'
preLoaderRoute: typeof QueryRouteImport
parentRoute: typeof rootRouteImport
}
}
}
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
AsyncRoute: AsyncRoute,
BlankRoute: BlankRoute,
FormRoute: FormRoute,
LensformRoute: LensformRoute,
QueryRoute: QueryRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()

Some files were not shown because too many files have changed in this diff Show More