4 Commits

Author SHA1 Message Date
renovate-bot dfb5789200 Update dependency jsdom to v30
Lint / lint (push) Failing after 1m17s
Test build / test-build (pull_request) Failing after 29s
2026-07-29 12:05:52 +00:00
Thilawyn 4b712de788 Finalize the Effect View rename and refresh docs, examples, and tooling (#59)
Publish / publish (push) Successful in 3m23s
Lint / lint (push) Successful in 48s
## Summary

- Rename `effect-fc-next` to `effect-view` and update package metadata, internal symbols, imports, and repository references.
- Promote the Effect 4 example to `packages/example` and move the legacy Effect 3 example to `packages/effect-fc-example`.
- Add `effect-view` to the npm publishing workflow.
- Update the Vite Fast Refresh plugin for `effect-view` and rename `effectViewPlugin()` to `effectView()`.
- Upgrade Effect, React, TypeScript, build tooling, and related dependencies.
- Refresh the documentation and homepage.

## Documentation

- Add a dedicated Async guide covering:
  - Suspense fallbacks
  - Hook ordering
  - Memoization
  - Structural prop equality
- Clarify synchronous and asynchronous component behavior.
- Document runner scope and service requirements.
- Explain stable construction of Query, Mutation, and Form instances.
- Expand focused Lens and Form examples, including curried focus helpers.
- Document the optional `@effect/platform-browser` dependency for window-focus query refresh.
- Improve the Forms guide structure and examples.
- Fix responsive homepage headline wrapping and update homepage copy.

## Notable API changes

- Package rename:

  ```diff
  - effect-fc-next
  + effect-view

---------

Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: #59
2026-07-27 04:11:42 +02:00
Julien Valverdé ec21d49dce Fix Docker image name
Publish / publish (push) Successful in 3m37s
Lint / lint (push) Successful in 57s
2026-07-26 02:42:15 +02:00
Thilawyn 4478598f15 Add Effect v4 support, Fast Refresh tooling, and revamped docs (#56)
Lint / lint (push) Successful in 57s
Publish / publish (push) Failing after 57s
## Summary

- Add `effect-fc-next`, a React 19 integration targeting Effect v4 beta.
- Introduce component lifecycles, scoped resources, queries, mutations, forms, lenses, views, and refreshable components.
- Add `@effect-view/vite-plugin` for Vite Fast Refresh support.
- Add an Effect v4 example application covering the new APIs.
- Expand test coverage for both the existing and next-generation packages.
- Replace the starter Docusaurus content with complete Effect View documentation while preserving the Effect v3 docs as a versioned snapshot.
- Update the landing page, navigation, package scripts, and build output.
- Extend CI with linting, tests, package builds, Docker builds, and container publishing.

## Validation

- `bun lint:tsc`
- `bun lint:biome`
- `bun test`
- `bun run build`
- `bun pack`
- Docker image build

---------

Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: Thilawyn/effect-fc#56
2026-07-26 02:32:59 +02:00
136 changed files with 3162 additions and 1484 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
+46
View File
@@ -11,16 +11,35 @@ jobs:
steps:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Container Registry
uses: docker/login-action@v3
with:
registry: docker.valverde.cloud
username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}
password: ${{ secrets.DOCKER_REGISTRY_PASSWORD }}
- name: Clone repo
uses: actions/checkout@v6
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint TypeScript
run: bun lint:tsc
- name: Lint Biome
run: bun lint:biome
- name: Test
run: bun run test
- name: Build
run: bun run build
- name: Publish effect-view
uses: JS-DevTools/npm-publish@v4
with:
package: packages/effect-view
access: public
token: ${{ secrets.NPM_TOKEN }}
registry: https://registry.npmjs.org
- name: Publish effect-fc
uses: JS-DevTools/npm-publish@v4
with:
@@ -28,3 +47,30 @@ jobs:
access: public
token: ${{ secrets.NPM_TOKEN }}
registry: https://registry.npmjs.org
- name: Clean before Docker build
run: |
bun clean:cache
bun clean:dist
bun clean:modules
- name: Generate Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: |
docker.valverde.cloud/thilawyn/effect-view
tags: |
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=sha
flavor: |
latest=true
- name: Build Docker image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+34 -1
View File
@@ -12,16 +12,49 @@ jobs:
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version: "24"
node-version: "22"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Clone repo
uses: actions/checkout@v6
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint TypeScript
run: bun lint:tsc
- name: Lint Biome
run: bun lint:biome
- name: Test
run: bun run test
- name: Build
run: bun run build
- name: Pack
run: bun pack
- name: Clean before Docker build
run: |
bun clean:cache
bun clean:dist
bun clean:modules
- name: Generate Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: |
docker.valverde.cloud/thilawyn/effect-view
tags: |
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
type=sha
flavor: |
latest=true
- name: Build Docker image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: false
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+12
View File
@@ -0,0 +1,12 @@
FROM oven/bun:1.3.12-debian@sha256:1b709c9dd883fc1af38c210f7ea5222c552a8d470ea73efbd4b8fcfee798a64b AS bun
FROM node:22.21.1-trixie-slim@sha256:98e1429d1a0b99378b4de43fa385f0746fd6276faf4feeb6104d91f6bad290f9
COPY --from=bun /usr/local/bin/bun /usr/local/bin/bunx /usr/local/bin/
COPY . /app
WORKDIR /app
RUN bun install --frozen-lockfile && \
bun run build && \
bun clean:cache && \
bun clean:modules && \
bun install --production --frozen-lockfile
+59 -5
View File
@@ -1,7 +1,61 @@
# Effect FC Monorepo
<p align="center">
<a href="https://thila.dev/effect-view">
<img src="https://github.com/Thiladev/effect-view/raw/master/packages/docs/static/img/logo.svg" width="104" height="104" alt="Effect View logo" />
</a>
</p>
[Effect-TS](https://effect.website/) integration for React 19.2+ that allows you to write function components using Effect generators.
<h1 align="center">Effect View Monorepo</h1>
This monorepo contains:
- [The `effect-fc` library](packages/effect-fc)
- [An example project](packages/example)
<p align="center">
Write React components as typed Effect programs.
</p>
This repository contains Effect View, its documentation, development examples,
and supporting tooling. Effect View brings Effect's typed services, resource
safety, concurrency, and data modeling to React while keeping ordinary React
components, hooks, and JSX.
## Packages
| Package | Description |
| --- | --- |
| [`effect-view`](packages/effect-view) | The Effect View library for Effect v4 and React 19. |
| [`@effect-view/vite-plugin`](packages/vite-plugin) | Vite Fast Refresh support for Effect View components. |
| [`docs`](packages/docs) | The [Effect View documentation](https://thila.dev/effect-view), built with Docusaurus. |
| [`example`](packages/example) | Example application using Effect View and Effect v4. |
| [`effect-fc`](packages/effect-fc) | Legacy Effect v3 package. |
| [`effect-fc-example`](packages/effect-fc-example) | Example application for the legacy package. |
## Development
The monorepo uses [Bun](https://bun.sh/) workspaces and
[Turborepo](https://turbo.build/).
```bash
bun install
```
Run checks and builds from the repository root:
```bash
bun run lint:tsc
bun run lint:biome
bun run test
bun run build
```
Start the Effect View example or documentation site:
```bash
bun run --cwd packages/example dev
bun run --cwd packages/docs start
```
## Documentation
Read the documentation at
[thila.dev/effect-view](https://thila.dev/effect-view).
## License
[MIT](LICENSE)
+313 -266
View File
File diff suppressed because it is too large Load Diff
+8 -7
View File
@@ -1,26 +1,27 @@
{
"name": "@effect-fc/monorepo",
"name": "@effect-view/monorepo",
"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.4.16",
"@effect/language-service": "^0.86.2",
"@biomejs/biome": "^2.5.5",
"@effect/language-service": "^0.87.1",
"@types/bun": "^1.3.14",
"npm-check-updates": "^22.2.1",
"npm-check-updates": "^23.0.0",
"npm-sort": "^0.0.4",
"turbo": "^2.9.16",
"typescript": "^6.0.3"
"turbo": "^2.10.7",
"typescript": "^7.0.2"
}
}
+10
View File
@@ -4,5 +4,15 @@
"extends": "//",
"files": {
"includes": ["./src/**"]
},
"linter": {
"rules": {
"complexity": {
"noImportantStyles": "off"
},
"style": {
"noDescendingSpecificity": "off"
}
}
}
}
+145
View File
@@ -0,0 +1,145 @@
---
sidebar_position: 2
title: Async
---
# Async
Effect View components run synchronously by default. Apply `Async.async` when a
component must wait for an asynchronous Effect before it can return JSX. The
component suspends while the Effect runs and accepts React Suspense props such
as `fallback`.
```tsx title="src/UserCard.tsx"
import { Effect } from "effect"
import { Async, Component } from "effect-view"
import { loadUser } from "./api"
export const UserCard = Component.make("UserCard")(
function* ({ userId }: { readonly userId: string }) {
const user = yield* Component.useOnChange(
() => loadUser(userId),
[userId],
)
return <article>{user.name}</article>
},
).pipe(Async.async)
```
Pass a fallback when rendering the component:
```tsx
const User = yield* UserCard.use
return <User userId="123" fallback={<p>Loading user...</p>} />
```
Or configure a default fallback once:
```tsx
export const UserCard = Component.make("UserCard")(
function* ({ userId }: { readonly userId: string }) {
const user = yield* Component.useOnChange(
() => loadUser(userId),
[userId],
)
return <article>{user.name}</article>
},
).pipe(
Async.async,
Async.withOptions({ defaultFallback: <p>Loading user...</p> }),
)
```
## Hook ordering
**Important:** Do not use React hooks or Effect View hook helpers after an
asynchronous computation in the component body. After the computation suspends,
the generator continuation runs outside React's synchronous render phase.
Place every hook before the first operation that may suspend:
```tsx
import { useState } from "react"
const UserCard = Component.make("UserCard")(
function* ({ userId }: { readonly userId: string }) {
// Hooks and hook helpers go before asynchronous work.
const [showDetails, setShowDetails] = useState(false)
// This may suspend, so no hooks may be used after it.
const user = yield* Component.useOnChange(
() => loadUser(userId),
[userId],
)
return (
<article>
<button onClick={() => setShowDetails((value) => !value)}>
{user.name}
</button>
{showDetails && <p>{user.bio}</p>}
</article>
)
},
).pipe(Async.async)
```
## Memoization
An async computation starts whenever its component renders. Apply
`Memoized.memoized` after `Async.async` to prevent an unrelated parent render
from restarting an async child whose props have not changed:
```tsx
import { Async, Component, Memoized } from "effect-view"
export const UserCard = Component.make("UserCard")(
function* ({ userId }: { readonly userId: string }) {
const user = yield* Component.useOnChange(
() => loadUser(userId),
[userId],
)
return <article>{user.name}</article>
},
).pipe(
Async.async,
Memoized.memoized,
)
```
Async components compare props with `Object.is` by default and ignore the
`fallback` prop during that comparison. A changed `userId` renders the child
again, closes the previous dependency scope, and runs `loadUser` for the new
value.
If props contain immutable objects or arrays that may be recreated with the same
content, use `Equal.asEquivalence()` for full structural equality:
```tsx
import { Equal } from "effect"
import { Async, Component, Memoized } from "effect-view"
export const UserCard = Component.make("UserCard")(
function* (props: { readonly user: { readonly id: string } }) {
const details = yield* Component.useOnChange(
() => loadUser(props.user.id),
[props.user.id],
)
return <article>{details.name}</article>
},
).pipe(
Async.async,
Memoized.memoized,
Memoized.withOptions({
propsEquivalence: Equal.asEquivalence(),
}),
)
```
Supplying `propsEquivalence` replaces the async component's default comparison,
so `fallback` is also included in this structural comparison.
+139 -121
View File
@@ -52,6 +52,14 @@ valid decoded value should go:
| `MutationForm` | Yes | It is passed to a mutation when `submit` runs. |
| `LensForm` | Yes | It is written automatically to a target `Lens`. |
## Create forms once
`MutationForm.service` and `LensForm.service` are Effect constructors, not
hooks. Create each root form once and keep it stable. For a component-owned
form, call the constructor inside `Component.useOnMount`; for a form shared by
multiple components, create it in an Effect service. Update the existing form's
Lenses rather than reconstructing the form during render.
## MutationForm: validate, then submit
Use `MutationForm` for registration, checkout, search, and other workflows with
@@ -102,9 +110,9 @@ 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.
`MutationForm.service` also starts initial validation in the current scope. In
the example above, `Component.useOnMount` keeps that validation and the form's
mutation work tied to the component that owns them.
## LensForm: validate, then synchronize
@@ -163,124 +171,6 @@ 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
@@ -300,6 +190,16 @@ const contactForm = Form.focusObjectOn(form, "contact")
const emailField = Form.focusObjectOn(contactForm, "email")
```
Form focus helpers also have a dual API. Pass only the key or index to get a curried function. Curried helpers can be chained
with `pipe` to focus through a deeper path:
```tsx
const emailField = form.pipe(
Form.focusObjectOn("contact"),
Form.focusObjectOn("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`
@@ -455,3 +355,121 @@ They expose the schema pipeline as reactive Lenses and Views:
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.
## 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.
+68 -51
View File
@@ -35,6 +35,33 @@ 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.
## Set up hot reloading with Vite
Install the Effect View Vite plugin to preserve component state while editing
Effect View components:
```bash npm2yarn
npm install --save-dev @effect-view/vite-plugin
```
Add `effectView()` before the React plugin in your Vite configuration:
```ts title="vite.config.ts"
import { effectView } from "@effect-view/vite-plugin"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
export default defineConfig({
plugins: [
effectView(),
react(),
],
})
```
Vite is the only bundler supported for Effect View hot reloading at the moment.
Support for other bundlers will follow.
## Create the runtime
`ReactRuntime` owns a managed Effect runtime. Define it at module scope from the
@@ -172,51 +199,25 @@ 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.
A regular Effect View component runs its body during React render. Effects
executed directly by that body—including setup passed to `useOnMount`,
`useOnChange`, or `useLayer`—must complete synchronously every time they run.
Yielding services and reading synchronous state 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`:
Choose the integration that matches the asynchronous work:
```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.
- Make the component asynchronous with [`Async.async`](./async) when it must
wait for a one-off asynchronous Effect before producing JSX. The component
suspends while it waits.
- Use [Query](./query) for server reads that need caching, sharing, refresh, or
invalidation.
- Use [Mutation](./mutation) for user-triggered writes with observable pending
and error state.
- Use `useRunPromise` or `useCallbackPromise` for asynchronous event work that
does not need Mutation state.
- Use a post-commit hook with a scoped fiber for subscriptions or background
work tied to the component lifecycle.
## Use Effect services
@@ -294,24 +295,25 @@ const ResourceView = Component.make("Resource")(function* () {
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.
`useOnChange`, `useReactEffect`, and `useReactLayoutEffect` each manage their
own resources. When their dependencies change, those resources are cleaned up
and recreated while the rest of the component remains active.
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 |
| `useOnMount` | Computes and caches a value for the component instance | 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 |
| `useLayer` | Builds and provides a layer context | A new scope tied to the current layer reference | 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.
`useRunSync` and `useRunPromise` do not create a new scope. The runner they
return includes the component root scope in its context by default.
`useCallbackSync` and `useCallbackPromise` similarly capture the component
context required by their Effect.
### useOnMount
@@ -409,6 +411,21 @@ Use `Component.useRunSync` only for Effects known to complete synchronously.
Use `Component.useRunPromise` for Effects that may suspend, sleep, fetch, or
otherwise continue asynchronously.
Both runners provide `Scope.Scope` by default, so they can run scoped Effects
without a type argument. When an Effect also requires application services,
declare the complete runner context explicitly:
```tsx
import { Scope } from "effect"
const runPromise = yield* Component.useRunPromise<
Scope.Scope | UserRepository
>()
```
The resulting runner accepts Effects that require the component scope,
`UserRepository`, or both.
When a callback is passed to a memoized child or used as a dependency, use the
callback variants to preserve its identity:
+5
View File
@@ -30,6 +30,11 @@ 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:
`Mutation.make` is an Effect constructor, not a hook. Create each mutation
instance once and keep it stable instead of calling `Mutation.make` again on
every render. Use `Component.useOnMount` for a component-owned mutation or
create it in an Effect service when it should be shared.
```tsx
import { Effect } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
+23 -8
View File
@@ -35,7 +35,6 @@ 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(
@@ -44,7 +43,6 @@ const AppLive = Layer.empty.pipe(
defaultRefreshOnWindowFocus: true,
cacheGcTime: "5 minutes",
})),
Layer.provideMerge(FetchHttpClient.layer),
)
export const runtime = ReactRuntime.make(AppLive)
@@ -52,7 +50,9 @@ 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.
client defaults. Window-focus refresh also requires the optional
`@effect/platform-browser` package, as described under
[Staleness and cache lifetime](#staleness-and-cache-lifetime).
## Create a reactive query
@@ -60,6 +60,12 @@ 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.
`Query.service` is an Effect constructor, not a hook. Create each query instance
once and keep it stable. In a component, the usual place is
`Component.useOnMount`; a query shared by multiple components can instead be
owned by an Effect service. Change the existing query's reactive key rather
than reconstructing the query during render.
```tsx
import { Effect, Schema, SubscriptionRef } from "effect"
import { HttpClient } from "effect/unstable/http"
@@ -118,9 +124,9 @@ 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 instanceand one
stable query function identityfor the component's lifetime.
`Query.service` starts watching its key in the current scope. The
`Component.useOnMount` call above keeps both the query instance and its query
function identity stable for the component's lifetime.
## Render AsyncResult
@@ -264,8 +270,17 @@ const query = yield* Query.service({
})
```
Window focus resolves the current key again, subject to the same freshness
check. The browser integration is ignored in non-browser environments.
Window-focus refresh depends on the optional `@effect/platform-browser`
integration. Install it in browser applications that use this behavior:
```bash npm2yarn
npm install @effect/platform-browser@beta
```
When the package is available, focusing the window resolves the current key
again, subject to the same freshness check. Without it,
`refreshOnWindowFocus` has no effect; the rest of the Query API continues to
work normally. The integration is also ignored in non-browser environments.
## The Effect touch
+39 -16
View File
@@ -12,9 +12,9 @@ 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
[`effect-lens`](https://www.npmjs.com/package/effect-lens/v/beta) 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.
[`effect-lens` documentation](https://www.npmjs.com/package/effect-lens/v/beta) 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
@@ -219,15 +219,16 @@ interface UserProfile {
readonly name: string
readonly email: string
readonly role: string
readonly contact: {
readonly address: {
readonly city: string
}
}
}
class ProfileState extends Context.Service<
ProfileState,
{
readonly profile: Lens.Lens<UserProfile>
readonly name: Lens.Lens<string>
readonly role: Lens.Lens<string>
}
{ readonly profile: Lens.Lens<UserProfile> }
>()("ProfileState") {
static readonly layer = Layer.effect(
ProfileState,
@@ -237,20 +238,35 @@ class ProfileState extends Context.Service<
name: "",
email: "",
role: "reader",
contact: {
address: {
city: "",
},
},
}),
)
const name = Lens.focusObjectOn(profile, "name")
const role = Lens.focusObjectOn(profile, "role")
return { profile, name, role } as const
return { profile } 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])
const [nameLens, roleLens, cityLens] = yield* Component.useOnMount(() =>
Effect.succeed([
Lens.focusObjectOn(state.profile, "name"),
Lens.focusObjectOn(state.profile, "role"),
state.profile.pipe(
Lens.focusObjectOn("contact"),
Lens.focusObjectOn("address"),
Lens.focusObjectOn("city"),
),
] as const),
)
const [name, setName] = yield* Lens.useState(nameLens)
const [role, city] = yield* View.useAll([roleLens, cityLens])
return (
<label>
@@ -260,15 +276,22 @@ const ProfileNameView = Component.make("ProfileName")(function*() {
onChange={(event) => setName(event.currentTarget.value)}
/>
<span>Role: {role}</span>
<span>City: {city}</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.
The service owns only the root `profile` Lens. The component chooses the fields
it needs, creates those focused Lenses once in `Component.useOnMount`, and
subscribes only to them. Updating `nameLens` through `Lens.useState` still
updates the parent `profile` Lens.
Lens focus helpers have a dual API. They can be called in data-first form, such
as `Lens.focusObjectOn(profile, "name")`, or in curried form with only the key
or index. The `cityLens` above uses the curried form with `pipe` to focus through
a deeper path without storing intermediate Lenses.
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).
[`effect-lens` documentation](https://www.npmjs.com/package/effect-lens/v/beta).
+9 -4
View File
@@ -46,11 +46,11 @@ const config: Config = {
lastVersion: "current",
versions: {
current: {
label: "effect-view v1",
label: "effect-view v0",
},
"effect-fc-1.0": {
label: "effect-fc 1.0",
path: "effect-fc/1.0",
"effect-fc-v0": {
label: "effect-fc v0",
path: "effect-fc/v0",
},
},
},
@@ -84,6 +84,11 @@ const config: Config = {
type: "docsVersionDropdown",
position: "right",
},
{
href: "https://www.npmjs.com/package/effect-view",
label: "npm",
position: "right",
},
{
href: "https://github.com/Thiladev/effect-view",
label: "GitHub",
+13 -9
View File
@@ -3,21 +3,25 @@
"version": "0.0.0",
"private": true,
"scripts": {
"lint:tsc": "tsc -b --noEmit",
"lint:biome": "biome lint",
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"build": "docusaurus build --out-dir dist",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"serve": "docusaurus serve --dir dist",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids",
"typecheck": "tsc"
"clean:cache": "rm -rf .turbo *.tsbuildinfo && docusaurus clear",
"clean:dist": "rm -rf dist",
"clean:modules": "rm -rf node_modules"
},
"dependencies": {
"@docusaurus/core": "3.10.1",
"@docusaurus/faster": "^3.10.1",
"@docusaurus/preset-classic": "3.10.1",
"@docusaurus/core": "^3.10.2",
"@docusaurus/faster": "^3.10.2",
"@docusaurus/preset-classic": "^3.10.2",
"@mdx-js/react": "^3.1.1",
"clsx": "^2.1.1",
"prism-react-renderer": "^2.4.1",
@@ -25,9 +29,9 @@
"react-dom": "^19.2.5"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.10.1",
"@docusaurus/tsconfig": "3.10.1",
"@docusaurus/types": "3.10.1",
"@docusaurus/module-type-aliases": "^3.10.2",
"@docusaurus/tsconfig": "^3.10.2",
"@docusaurus/types": "^3.10.2",
"@types/react": "^19.2.15",
"@types/react-dom": "^19.2.3",
"typescript": "~6.0.3"
+1
View File
@@ -6,6 +6,7 @@ const sidebars: SidebarsConfig = {
docsSidebar: [
"getting-started",
"state-management",
"async",
"query",
"mutation",
"forms",
+27 -1
View File
@@ -72,9 +72,15 @@
letter-spacing: -0.075em;
line-height: 0.92;
margin: 0;
overflow-wrap: normal;
word-break: normal;
}
.hero h1 span {
.hero h1 .unbreakable {
white-space: nowrap;
}
.hero h1 .heroAccent {
background: linear-gradient(105deg, var(--home-teal) 5%, #1a9793 48%, var(--home-amber));
background-clip: text;
color: transparent;
@@ -157,6 +163,26 @@
padding: 0;
}
.hotReload {
align-items: center;
color: var(--home-teal);
display: inline-flex;
font-size: 0.82rem;
font-weight: 750;
gap: 0.5rem;
margin-top: 0.75rem;
text-decoration: none !important;
}
.hotReload span {
color: var(--home-amber);
font-size: 1rem;
}
.hotReload:hover {
color: var(--home-teal-bright);
}
.codeStage {
min-width: 0;
perspective: 1200px;
+9 -2
View File
@@ -100,8 +100,8 @@ export default function Home(): ReactNode {
Effect View for React 19
</div>
<h1>
React components,
<span> powered by Effect.</span>
React <span className={styles.unbreakable}>components,</span>
<span className={styles.heroAccent}> powered by Effect.</span>
</h1>
<p className={styles.lede}>
Bring typed services, scoped resources, reactive state, server
@@ -126,6 +126,13 @@ export default function Home(): ReactNode {
<span aria-hidden="true">$</span>
<code>npm install effect-view effect@beta</code>
</div>
<Link
className={styles.hotReload}
to="/docs/getting-started#set-up-hot-reloading-with-vite"
>
<span aria-hidden="true"></span>
Hot reload with Vite Fast Refresh
</Link>
</div>
<div className={styles.codeStage}>
+1 -1
View File
@@ -1,3 +1,3 @@
[
"effect-fc-1.0"
"effect-fc-v0"
]
+51
View File
@@ -0,0 +1,51 @@
# Effect FC Example
Example application for the legacy `effect-fc` package, built with React,
TypeScript, and Vite.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```
- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:
```js
// eslint.config.js
import react from 'eslint-plugin-react'
export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
@@ -4,7 +4,7 @@
<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>
<title>Effect FC Example</title>
</head>
<body>
<div id="root"></div>
@@ -1,10 +1,9 @@
{
"name": "@effect-fc/example-next",
"name": "@effect-fc/example",
"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",
@@ -23,18 +22,21 @@
"globals": "^17.6.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"type-fest": "^5.7.0",
"vite": "^8.0.16"
},
"dependencies": {
"@effect/platform-browser": "4.0.0-beta.98",
"@effect/platform": "^0.96.1",
"@effect/platform-browser": "^0.76.0",
"@radix-ui/themes": "^3.3.0",
"effect": "4.0.0-beta.98",
"effect-fc-next": "workspace:*",
"@typed/id": "^0.17.2",
"effect": "^3.21.2",
"effect-fc": "workspace:*",
"react-icons": "^5.6.0"
},
"overrides": {
"@types/react": "^19.2.15",
"effect": "4.0.0-beta.98",
"effect": "^3.21.2",
"react": "^19.2.6"
}
}

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -1,6 +1,6 @@
import { Callout, Flex, Spinner, TextField } from "@radix-ui/themes"
import { Array, Option, Struct } from "effect"
import { Component, Form, View } from "effect-fc-next"
import { Component, Form, Subscribable } from "effect-fc"
import type * as React from "react"
@@ -17,7 +17,7 @@ export const TextFieldFormInputView = Component.make("TextFieldFormInputView")(f
props: TextFieldFormInputView.Props<readonly PropertyKey[], any, any, any>
) {
const input = yield* Form.useInput(props.form, props)
const [issues, isValidating, isCommitting] = yield* View.useAll([
const [issues, isValidating, isCommitting] = yield* Subscribable.useAll([
props.form.issues,
props.form.isValidating,
props.form.isCommitting,
@@ -29,7 +29,7 @@ export const TextFieldFormInputView = Component.make("TextFieldFormInputView")(f
value={input.value}
onChange={e => input.setValue(e.target.value)}
disabled={isCommitting}
{...Struct.omit(props, ["form"])}
{...Struct.omit(props, "form")}
>
{isValidating &&
<TextField.Slot side="right">
@@ -1,6 +1,6 @@
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 { Component, Form, Subscribable } from "effect-fc"
import type * as React from "react"
@@ -17,7 +17,7 @@ export const TextFieldOptionalFormInputView = Component.make("TextFieldOptionalF
props: TextFieldOptionalFormInputView.Props<readonly PropertyKey[], any, any, any>
) {
const input = yield* Form.useOptionalInput(props.form, props)
const [issues, isValidating, isCommitting] = yield* View.useAll([
const [issues, isValidating, isCommitting] = yield* Subscribable.useAll([
props.form.issues,
props.form.isValidating,
props.form.isCommitting,
@@ -29,7 +29,7 @@ export const TextFieldOptionalFormInputView = Component.make("TextFieldOptionalF
value={input.value}
onChange={e => input.setValue(e.target.value)}
disabled={!input.enabled || isCommitting}
{...Struct.omit(props, ["form", "defaultValue"])}
{...Struct.omit(props, "form", "defaultValue")}
>
<TextField.Slot side="left">
<Switch
@@ -1,21 +1,24 @@
import { createRouter, RouterProvider } from "@tanstack/react-router"
import { ReactRuntime } from "effect-fc-next"
import { ReactRuntime } from "effect-fc"
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 }
interface Register {
router: typeof router
}
}
// biome-ignore lint/style/noNonNullAssertion: the Vite template provides this element
// biome-ignore lint/style/noNonNullAssertion: React entrypoint
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ReactRuntime.Provider runtime={runtime}>
<RouterProvider router={router} />
</ReactRuntime.Provider>
</StrictMode>,
</StrictMode>
)
@@ -9,26 +9,23 @@
// 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 ResultRouteImport } from './routes/result'
import { Route as QueryRouteImport } from './routes/query'
import { Route as FormRouteImport } from './routes/form'
import { Route as BlankRouteImport } from './routes/blank'
import { Route as AsyncRouteImport } from './routes/async'
import { Route as IndexRouteImport } from './routes/index'
import { Route as DevMemoRouteImport } from './routes/dev/memo'
import { Route as DevContextRouteImport } from './routes/dev/context'
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
const ResultRoute = ResultRouteImport.update({
id: '/result',
path: '/result',
getParentRoute: () => rootRouteImport,
} as any)
const AsyncRoute = AsyncRouteImport.update({
id: '/async',
path: '/async',
getParentRoute: () => rootRouteImport,
} as any)
const BlankRoute = BlankRouteImport.update({
id: '/blank',
path: '/blank',
const QueryRoute = QueryRouteImport.update({
id: '/query',
path: '/query',
getParentRoute: () => rootRouteImport,
} as any)
const FormRoute = FormRouteImport.update({
@@ -36,14 +33,29 @@ const FormRoute = FormRouteImport.update({
path: '/form',
getParentRoute: () => rootRouteImport,
} as any)
const LensformRoute = LensformRouteImport.update({
id: '/lensform',
path: '/lensform',
const BlankRoute = BlankRouteImport.update({
id: '/blank',
path: '/blank',
getParentRoute: () => rootRouteImport,
} as any)
const QueryRoute = QueryRouteImport.update({
id: '/query',
path: '/query',
const AsyncRoute = AsyncRouteImport.update({
id: '/async',
path: '/async',
getParentRoute: () => rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const DevMemoRoute = DevMemoRouteImport.update({
id: '/dev/memo',
path: '/dev/memo',
getParentRoute: () => rootRouteImport,
} as any)
const DevContextRoute = DevContextRouteImport.update({
id: '/dev/context',
path: '/dev/context',
getParentRoute: () => rootRouteImport,
} as any)
@@ -52,16 +64,20 @@ export interface FileRoutesByFullPath {
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
'/result': typeof ResultRoute
'/dev/context': typeof DevContextRoute
'/dev/memo': typeof DevMemoRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
'/result': typeof ResultRoute
'/dev/context': typeof DevContextRoute
'/dev/memo': typeof DevMemoRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
@@ -69,15 +85,42 @@ export interface FileRoutesById {
'/async': typeof AsyncRoute
'/blank': typeof BlankRoute
'/form': typeof FormRoute
'/lensform': typeof LensformRoute
'/query': typeof QueryRoute
'/result': typeof ResultRoute
'/dev/context': typeof DevContextRoute
'/dev/memo': typeof DevMemoRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
fullPaths:
| '/'
| '/async'
| '/blank'
| '/form'
| '/query'
| '/result'
| '/dev/context'
| '/dev/memo'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
id: '__root__' | '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
to:
| '/'
| '/async'
| '/blank'
| '/form'
| '/query'
| '/result'
| '/dev/context'
| '/dev/memo'
id:
| '__root__'
| '/'
| '/async'
| '/blank'
| '/form'
| '/query'
| '/result'
| '/dev/context'
| '/dev/memo'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -85,31 +128,26 @@ export interface RootRouteChildren {
AsyncRoute: typeof AsyncRoute
BlankRoute: typeof BlankRoute
FormRoute: typeof FormRoute
LensformRoute: typeof LensformRoute
QueryRoute: typeof QueryRoute
ResultRoute: typeof ResultRoute
DevContextRoute: typeof DevContextRoute
DevMemoRoute: typeof DevMemoRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
'/result': {
id: '/result'
path: '/result'
fullPath: '/result'
preLoaderRoute: typeof ResultRouteImport
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
'/query': {
id: '/query'
path: '/query'
fullPath: '/query'
preLoaderRoute: typeof QueryRouteImport
parentRoute: typeof rootRouteImport
}
'/form': {
@@ -119,18 +157,39 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof FormRouteImport
parentRoute: typeof rootRouteImport
}
'/lensform': {
id: '/lensform'
path: '/lensform'
fullPath: '/lensform'
preLoaderRoute: typeof LensformRouteImport
'/blank': {
id: '/blank'
path: '/blank'
fullPath: '/blank'
preLoaderRoute: typeof BlankRouteImport
parentRoute: typeof rootRouteImport
}
'/query': {
id: '/query'
path: '/query'
fullPath: '/query'
preLoaderRoute: typeof QueryRouteImport
'/async': {
id: '/async'
path: '/async'
fullPath: '/async'
preLoaderRoute: typeof AsyncRouteImport
parentRoute: typeof rootRouteImport
}
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
'/dev/memo': {
id: '/dev/memo'
path: '/dev/memo'
fullPath: '/dev/memo'
preLoaderRoute: typeof DevMemoRouteImport
parentRoute: typeof rootRouteImport
}
'/dev/context': {
id: '/dev/context'
path: '/dev/context'
fullPath: '/dev/context'
preLoaderRoute: typeof DevContextRouteImport
parentRoute: typeof rootRouteImport
}
}
@@ -141,8 +200,10 @@ const rootRouteChildren: RootRouteChildren = {
AsyncRoute: AsyncRoute,
BlankRoute: BlankRoute,
FormRoute: FormRoute,
LensformRoute: LensformRoute,
QueryRoute: QueryRoute,
ResultRoute: ResultRoute,
DevContextRoute: DevContextRoute,
DevMemoRoute: DevMemoRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
@@ -7,7 +7,7 @@ import "../index.css"
export const Route = createRootRoute({
component: Root,
component: Root
})
function Root() {
@@ -17,10 +17,6 @@ function Root() {
<Flex direction="row" justify="center" align="center" gap="2">
<Link to="/">Index</Link>
<Link to="/blank">Blank</Link>
<Link to="/async">Async</Link>
<Link to="/query">Query</Link>
<Link to="/form">Form</Link>
<Link to="/lensform">LensForm</Link>
</Flex>
</Container>
@@ -1,35 +1,30 @@
import { HttpClient } from "@effect/platform"
import { Container, Flex, Heading, Slider, Text, TextField } from "@radix-ui/themes"
import { createFileRoute } from "@tanstack/react-router"
import { Console, Effect } from "effect"
import { Async, Component, Memoized } from "effect-fc-next"
import { Array, Effect, flow, Option, Schema } from "effect"
import { Async, Component, Memoized } from "effect-fc"
import * as React from "react"
import { runtime } from "@/runtime"
const fetchPost = (id: number) => Effect.sleep("500 millis").pipe(
Effect.as({
title: `Post ${id}`,
body: `This is the content of post ${id}.`,
}),
)
const Post = Schema.Struct({
userId: Schema.Int,
id: Schema.Int,
title: Schema.String,
body: Schema.String,
})
interface AsyncFetchPostViewProps {
readonly id: number
}
const AsyncFetchPostView = Component.make("AsyncFetchPostView")(function*(
props: AsyncFetchPostViewProps,
) {
yield* Component.useOnMount(() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Console.log("AsyncFetchPostView unmounted"))
yield* Console.log("AsyncFetchPostView mounted")
}))
const post = yield* Component.useOnChange(
() => fetchPost(props.id),
[props.id],
)
class AsyncFetchPostView extends Component.make("AsyncFetchPostView")(function*(props: AsyncFetchPostViewProps) {
const post = yield* Component.useOnChange(() => HttpClient.HttpClient.pipe(
Effect.tap(Effect.sleep("500 millis")),
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ props.id }`)),
Effect.andThen(response => response.json),
Effect.andThen(Schema.decodeUnknown(Post)),
), [props.id])
return (
<div>
@@ -39,9 +34,10 @@ const AsyncFetchPostView = Component.make("AsyncFetchPostView")(function*(
)
}).pipe(
Async.async,
Async.withOptions({ defaultFallback: <Text>Loading post...</Text> }),
Async.withOptions({ defaultFallback: <Text>Default fallback</Text> }),
Memoized.memoized,
)
) {}
const AsyncRouteComponent = Component.make("AsyncRouteView")(function*() {
const [text, setText] = React.useState("Typing here should not trigger a refetch of the post")
@@ -54,22 +50,20 @@ const AsyncRouteComponent = Component.make("AsyncRouteView")(function*() {
<Flex direction="column" align="stretch" gap="2">
<TextField.Root
value={text}
onChange={event => setText(event.currentTarget.value)}
onChange={e => setText(e.currentTarget.value)}
/>
<Slider
value={[id]}
min={1}
max={10}
onValueChange={([value]) => setId(value ?? 1)}
onValueChange={flow(Array.head, Option.getOrThrow, setId)}
/>
<AsyncFetchPost id={id} />
<AsyncFetchPost id={id} fallback={<Text>Loading post...</Text>} />
</Flex>
</Container>
)
}).pipe(
Component.withContext(runtime.context),
Component.withRuntime(runtime.context)
)
export const Route = createFileRoute("/async")({
@@ -0,0 +1,143 @@
import { Button, Container, Flex, Text } from "@radix-ui/themes"
import { createFileRoute } from "@tanstack/react-router"
import { Console, Effect, Match, Option, ParseResult, Schema } from "effect"
import { Component, Form, SubmittableForm, Subscribable } from "effect-fc"
import { TextFieldFormInputView } from "@/lib/form/TextFieldFormInputView"
import { TextFieldOptionalFormInputView } from "@/lib/form/TextFieldOptionalFormInputView"
import { DateTimeUtcFromZonedInput } from "@/lib/schema"
import { runtime } from "@/runtime"
const email = Schema.pattern<typeof Schema.String>(
/^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i,
{
identifier: "email",
title: "email",
message: () => "Not an email address",
},
)
const RegisterFormSchema = Schema.Struct({
email: Schema.String.pipe(email),
password: Schema.String.pipe(Schema.minLength(3)),
birth: Schema.OptionFromSelf(DateTimeUtcFromZonedInput),
})
const RegisterFormSubmitSchema = Schema.Struct({
email: Schema.transformOrFail(
Schema.String,
Schema.String,
{
decode: (input, _options, ast) => input !== "admin@admin.com"
? ParseResult.succeed(input)
: ParseResult.fail(new ParseResult.Type(ast, input, "This email is already in use.")),
encode: ParseResult.succeed,
},
),
password: Schema.String,
birth: Schema.OptionFromSelf(Schema.DateTimeUtcFromSelf),
})
class RegisterFormService extends Effect.Service<RegisterFormService>()("RegisterFormService", {
scoped: Effect.gen(function*() {
const form = yield* SubmittableForm.service({
schema: RegisterFormSchema.pipe(
Schema.compose(
Schema.transformOrFail(
Schema.typeSchema(RegisterFormSchema),
Schema.typeSchema(RegisterFormSchema),
{
decode: v => Effect.andThen(Effect.sleep("500 millis"), ParseResult.succeed(v)),
encode: ParseResult.succeed,
},
),
),
),
initialEncodedValue: { email: "", password: "", birth: Option.none() },
f: Effect.fnUntraced(function*([value]) {
yield* Effect.sleep("500 millis")
return yield* Schema.decode(RegisterFormSubmitSchema)(value)
}),
})
return {
form,
emailField: Form.focusObjectOn(form, "email"),
passwordField: Form.focusObjectOn(form, "password"),
birthField: Form.focusObjectOn(form, "birth"),
} as const
})
}) {}
class RegisterFormView extends Component.make("RegisterFormView")(function*() {
const form = yield* RegisterFormService
const [canCommit, submitResult] = yield* Subscribable.useAll([
form.form.canCommit,
form.form.mutation.result,
])
const runPromise = yield* Component.useRunPromise()
const TextFieldFormInput = yield* TextFieldFormInputView.use
const TextFieldOptionalFormInput = yield* TextFieldOptionalFormInputView.use
yield* Component.useOnMount(() => Effect.gen(function*() {
yield* Effect.addFinalizer(() => Console.log("RegisterFormView unmounted"))
yield* Console.log("RegisterFormView mounted")
}))
return (
<Container width="300">
<form onSubmit={e => {
e.preventDefault()
void runPromise(form.form.submit)
}}>
<Flex direction="column" gap="2">
<TextFieldFormInput
form={form.emailField}
debounce="250 millis"
/>
<TextFieldFormInput
form={form.passwordField}
debounce="250 millis"
/>
<TextFieldOptionalFormInput
type="datetime-local"
form={form.birthField}
defaultValue=""
/>
<Button disabled={!canCommit}>Submit</Button>
</Flex>
</form>
{Match.value(submitResult).pipe(
Match.tag("Initial", () => <></>),
Match.tag("Running", () => <Text>Submitting...</Text>),
Match.tag("Success", () => <Text>Submitted successfully!</Text>),
Match.tag("Failure", e => <Text>Error: {e.cause.toString()}</Text>),
Match.exhaustive,
)}
</Container>
)
}) {}
const RegisterPage = Component.make("RegisterPageView")(function*() {
const RegisterForm = yield* Effect.provide(
RegisterFormView.use,
yield* Component.useLayer(RegisterFormService.Default),
)
return <RegisterForm />
}).pipe(
Component.withRuntime(runtime.context)
)
export const Route = createFileRoute("/form")({
component: RegisterPage
})
@@ -0,0 +1,24 @@
import { createFileRoute } from "@tanstack/react-router"
import { Effect } from "effect"
import { Component } from "effect-fc"
import { runtime } from "@/runtime"
import { TodosState } from "@/todo/TodosState"
import { TodosView } from "@/todo/TodosView"
const TodosStateLive = TodosState.Default("todos")
const Index = Component.make("IndexView")(function*() {
const Todos = yield* Effect.provide(
TodosView.use,
yield* Component.useLayer(TodosStateLive),
)
return <Todos />
}).pipe(
Component.withRuntime(runtime.context)
)
export const Route = createFileRoute("/")({
component: Index
})
@@ -0,0 +1,117 @@
import { HttpClient, type HttpClientError } from "@effect/platform"
import { Button, Container, Flex, Heading, Slider, Text } from "@radix-ui/themes"
import { createFileRoute } from "@tanstack/react-router"
import { Array, Cause, Chunk, Console, Effect, flow, Match, Option, Schema, Stream, SubscriptionRef } from "effect"
import { Component, ErrorObserver, Lens, Mutation, Query, Result, Subscribable } from "effect-fc"
import { runtime } from "@/runtime"
const Post = Schema.Struct({
userId: Schema.Int,
id: Schema.Int,
title: Schema.String,
body: Schema.String,
})
const ResultView = Component.make("ResultView")(function*() {
const runPromise = yield* Component.useRunPromise()
const [idLens, query, mutation] = yield* Component.useOnMount(() => Effect.gen(function*() {
const idLens = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(1))
const key = Stream.map(idLens.changes, id => [id] as const)
const query = yield* Query.service({
key,
f: ([id]) => HttpClient.HttpClient.pipe(
Effect.tap(Effect.sleep("500 millis")),
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ id }`)),
Effect.andThen(response => response.json),
Effect.andThen(Schema.decodeUnknown(Post)),
),
staleTime: "10 seconds",
})
const mutation = yield* Mutation.make({
f: ([id]: readonly [id: number]) => HttpClient.HttpClient.pipe(
Effect.tap(Effect.sleep("500 millis")),
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ id }`)),
Effect.andThen(response => response.json),
Effect.andThen(Schema.decodeUnknown(Post)),
),
})
return [idLens, query, mutation] as const
}))
const [id, setId] = yield* Lens.useState(idLens)
const [queryResult, mutationResult] = yield* Subscribable.useAll([query.result, mutation.result])
yield* Component.useOnMount(() => ErrorObserver.ErrorObserver<HttpClientError.HttpClientError>().pipe(
Effect.andThen(observer => observer.subscribe),
Effect.andThen(Stream.fromQueue),
Stream.unwrapScoped,
Stream.runForEach(flow(
Cause.failures,
Chunk.findFirst(e => e._tag === "RequestError" || e._tag === "ResponseError"),
Option.match({
onSome: e => Console.log("ResultView HttpClient error", e),
onNone: () => Effect.void,
}),
)),
Effect.forkScoped,
))
return (
<Container>
<Flex direction="column" align="center" gap="2">
<Slider
value={[id]}
onValueChange={flow(Array.head, Option.getOrThrow, setId)}
/>
<div>
{Match.value(queryResult).pipe(
Match.tag("Running", () => <Text>Loading...</Text>),
Match.tag("Success", result => <>
<Heading>{result.value.title}</Heading>
<Text>{result.value.body}</Text>
{Result.hasRefreshingFlag(result) && <Text>Refreshing...</Text>}
</>),
Match.tag("Failure", result =>
<Text>An error has occured: {result.cause.toString()}</Text>
),
Match.orElse(() => <></>),
)}
</div>
<Flex direction="row" justify="center" align="center" gap="1">
<Button onClick={() => runPromise(query.refresh)}>Refresh</Button>
<Button onClick={() => runPromise(query.invalidateCache)}>Invalidate cache</Button>
</Flex>
<div>
{Match.value(mutationResult).pipe(
Match.tag("Running", () => <Text>Loading...</Text>),
Match.tag("Success", result => <>
<Heading>{result.value.title}</Heading>
<Text>{result.value.body}</Text>
{Result.hasRefreshingFlag(result) && <Text>Refreshing...</Text>}
</>),
Match.tag("Failure", result =>
<Text>An error has occured: {result.cause.toString()}</Text>
),
Match.orElse(() => <></>),
)}
</div>
<Flex direction="row" justify="center" align="center" gap="1">
<Button onClick={() => runPromise(Effect.andThen(Lens.get(idLens), id => mutation.mutate([id])))}>Mutate</Button>
</Flex>
</Flex>
</Container>
)
})
export const Route = createFileRoute("/query")({
component: Component.withRuntime(ResultView, runtime.context)
})
@@ -1,11 +1,10 @@
import { FetchHttpClient } from "@effect/platform"
import { Clipboard, Geolocation, Permissions } from "@effect/platform-browser"
import { DateTime, Layer } from "effect"
import { FetchHttpClient } from "effect/unstable/http"
import { QueryClient, ReactRuntime } from "effect-fc-next"
import { ReactRuntime } from "effect-fc"
export const layer = Layer.empty.pipe(
Layer.provideMerge(QueryClient.layer()),
export const AppLive = Layer.empty.pipe(
Layer.provideMerge(DateTime.layerCurrentZoneLocal),
Layer.provideMerge(Clipboard.layer),
Layer.provideMerge(Geolocation.layer),
@@ -13,4 +12,4 @@ export const layer = Layer.empty.pipe(
Layer.provideMerge(FetchHttpClient.layer),
)
export const runtime = ReactRuntime.make(layer)
export const runtime = ReactRuntime.make(AppLive)
-57
View File
@@ -1,57 +0,0 @@
{
"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"
},
"./*": [
{
"types": "./dist/*/index.d.ts",
"default": "./dist/*/index.js"
},
{
"types": "./dist/*.d.ts",
"default": "./dist/*.js"
}
]
},
"scripts": {
"build": "tsc",
"lint:tsc": "tsc --noEmit",
"lint:biome": "biome lint",
"test": "vitest run",
"pack": "npm pack",
"clean:cache": "rm -rf .turbo tsconfig.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"
}
}
@@ -1,47 +0,0 @@
import { type Cause, Context, Effect, Layer, Option, Pipeable, Predicate, PubSub, type Scope } from "effect"
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 [ErrorObserverTypeId]: ErrorObserverTypeId
handle<A, E1, R>(effect: Effect.Effect<A, E1, R>): Effect.Effect<A, E1, R>
readonly subscribe: Effect.Effect<PubSub.Subscription<Cause.Cause<E>>, never, Scope.Scope>
}
export const ErrorObserver = <E = never>() => Context.Service<ErrorObserver<E>>(
"@effect-fc/ErrorObserver/ErrorObserver",
)
export class ErrorObserverImpl<in out E = never> extends Pipeable.Class implements ErrorObserver<E> {
readonly [ErrorObserverTypeId]: ErrorObserverTypeId = ErrorObserverTypeId
constructor(readonly pubsub: PubSub.PubSub<Cause.Cause<E>>) {
super()
}
get subscribe(): Effect.Effect<PubSub.Subscription<Cause.Cause<E>>, never, Scope.Scope> {
return PubSub.subscribe(this.pubsub)
}
handle<A, E1, R>(effect: Effect.Effect<A, E1, R>): Effect.Effect<A, E1, R> {
return Effect.tapCause(effect, cause => Effect.asVoid(
PubSub.publish(this.pubsub, cause as unknown as Cause.Cause<E>),
))
}
}
export const isErrorObserver = (u: unknown): u is ErrorObserver<unknown> => Predicate.hasProperty(u, ErrorObserverTypeId)
export const layer: Layer.Layer<ErrorObserver> = Layer.effect(ErrorObserver())(
Effect.map(PubSub.unbounded<Cause.Cause<never>>(), pubsub => new ErrorObserverImpl(pubsub)),
)
export const handle = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => Effect.flatMap(
Effect.serviceOption(ErrorObserver()),
Option.match({
onSome: observer => observer.handle(effect),
onNone: () => effect,
}),
)
+1 -1
View File
@@ -4,7 +4,7 @@
This library is in early development. While it is (almost) feature complete and mostly usable, expect bugs and quirks. Things are still being ironed out, so ideas and criticisms are more than welcome.
Documentation is currently being written. In the meantime, you can take a look at the `packages/example` directory.
Documentation is currently being written. In the meantime, you can take a look at the `packages/effect-fc-example` directory.
## Peer dependencies
- `effect` 3.19+
+7 -7
View File
@@ -1,7 +1,7 @@
{
"name": "effect-fc",
"description": "Write React function components with Effect",
"version": "0.3.0",
"version": "0.3.1",
"type": "module",
"files": [
"./README.md",
@@ -9,7 +9,7 @@
],
"license": "MIT",
"repository": {
"url": "git+https://github.com/Thiladev/effect-fc.git"
"url": "git+https://github.com/Thiladev/effect-view.git"
},
"types": "./dist/index.d.ts",
"exports": {
@@ -29,19 +29,19 @@
]
},
"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.76.0",
"@testing-library/react": "^16.3.0",
"jsdom": "^26.1.0",
"jsdom": "^30.0.0",
"vitest": "^3.2.4"
},
"peerDependencies": {
@@ -50,6 +50,6 @@
"react": "^19.2.0"
},
"dependencies": {
"effect-lens": "^0.2.0"
"effect-lens": "^0.2.3"
}
}
@@ -2,8 +2,8 @@ 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 "../src/Component.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
class ValueService extends Context.Tag("ValueService")<ValueService, { readonly value: string }>() {}
@@ -273,6 +273,7 @@ describe("Component", () => {
)
await screen.findByText("first")
vi.useFakeTimers()
view.rerender(
<runtime.context.Provider value={effectRuntime}>
@@ -280,16 +281,19 @@ describe("Component", () => {
</runtime.context.Provider>
)
await screen.findByText("second")
expect(screen.getByText("second")).toBeTruthy()
expect(cleanup).not.toHaveBeenCalled()
await new Promise(resolve => setTimeout(resolve, 5))
await vi.advanceTimersByTimeAsync(19)
expect(cleanup).not.toHaveBeenCalled()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"), { timeout: 100 })
await vi.advanceTimersByTimeAsync(1)
expect(cleanup).toHaveBeenCalledWith("first")
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"), { timeout: 100 })
await vi.advanceTimersByTimeAsync(20)
expect(cleanup).toHaveBeenCalledWith("second")
vi.useRealTimers()
await Effect.runPromise(runtime.runtime.disposeEffect)
})
@@ -2,9 +2,9 @@ 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 "../src/Component.js"
import * as Lens from "../src/Lens.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as Component from "./Component.js"
import * as Lens from "./Lens.js"
import * as ReactRuntime from "./ReactRuntime.js"
const makeRuntime = async () => {
@@ -18,6 +18,12 @@ const makeRuntime = async () => {
}
}
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()
@@ -30,7 +36,7 @@ describe("Lens", () => {
return (
<>
<div>{value}</div>
<button onClick={() => setValue(previous => previous + 1)}>increment</button>
<button type="button" onClick={() => setValue(previous => previous + 1)}>increment</button>
</>
)
}).pipe(
@@ -102,7 +108,7 @@ describe("Lens", () => {
lens = reactLens
}))
return <button onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
return <button type="button" onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
}).pipe(
Component.withRuntime(runtime.context)
)
@@ -118,7 +124,7 @@ describe("Lens", () => {
fireEvent.click(screen.getByRole("button", { name: "hello" }))
await screen.findByText("hello!")
await waitFor(async () => expect(await Effect.runPromise(Lens.get(lens!))).toBe("hello!"))
await waitFor(async () => expect(await Effect.runPromise(Lens.get(expectDefined(lens)))).toBe("hello!"))
view.unmount()
await dispose()
@@ -152,11 +158,11 @@ describe("Lens", () => {
await screen.findByText("first")
await waitFor(() => expect(lens).toBeDefined())
await Effect.runPromise(Lens.set(lens!, { id: 1, label: "ignored" }))
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(lens!, { id: 2, label: "updated" }))
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
@@ -1,8 +1,8 @@
import { Effect, Option, type Scope, Stream } from "effect"
import { describe, expect, it } from "vitest"
import * as Query from "../src/Query.js"
import * as QueryClient from "../src/QueryClient.js"
import * as Result from "../src/Result.js"
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>) =>
@@ -2,9 +2,9 @@ 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 "../src/Component.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as Subscribable from "../src/Subscribable.js"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
import * as Subscribable from "./Subscribable.js"
const makeRuntime = async () => {
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["**/setup-tests.ts", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"]
}
-1
View File
@@ -36,5 +36,4 @@
},
"include": ["./src"],
"exclude": ["**/*.test.ts", "**/*.spec.ts"]
}
+1 -1
View File
@@ -4,6 +4,6 @@ import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
environment: "jsdom",
include: ["test/**/*.test.ts?(x)"],
include: ["./src/**/*.test.ts?(x)"],
},
})
@@ -1,6 +1,6 @@
<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" />
<img src="https://github.com/Thiladev/effect-view/raw/master/packages/docs/static/img/logo.svg" width="104" height="104" alt="Effect View logo" />
</a>
</p>
@@ -136,9 +136,6 @@ Effect View is renderer-independent and does not require `react-dom`.
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).
+115
View File
@@ -0,0 +1,115 @@
{
"name": "effect-view",
"description": "Write React function components with Effect",
"version": "0.1.0",
"type": "module",
"files": [
"./README.md",
"./dist"
],
"license": "MIT",
"repository": {
"url": "git+https://github.com/Thiladev/effect-view.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.101",
"@testing-library/react": "^16.3.0",
"effect": "4.0.0-beta.101",
"jsdom": "^30.0.0",
"vitest": "^3.2.4"
},
"peerDependencies": {
"@types/react": "^19.2.0",
"effect": "4.0.0-beta.101",
"react": "^19.2.0"
},
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"effect-lens": "^2.0.1-beta.101"
}
}
@@ -2,10 +2,10 @@ 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 "../src/Async.js"
import * as Component from "../src/Component.js"
import * as Memoized from "../src/Memoized.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
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 () => {
@@ -4,7 +4,7 @@ import * as React from "react"
import * as Component from "./Component.js"
export const AsyncTypeId: unique symbol = Symbol.for("@effect-fc/Async/Async")
export const AsyncTypeId: unique symbol = Symbol.for("@effect-view/Async/Async")
export type AsyncTypeId = typeof AsyncTypeId
@@ -37,7 +37,7 @@ export type AsyncProps = Omit<React.SuspenseProps, "children">
export const AsyncPrototype: AsyncPrototype = Object.freeze({
[AsyncTypeId]: AsyncTypeId,
asFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Component.Signature>(
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>>>,
) {
@@ -2,9 +2,10 @@ 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 "../src/Component.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as ScopeRegistry from "../src/ScopeRegistry.js"
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") {}
@@ -276,6 +277,7 @@ describe("Component", () => {
)
await screen.findByText("first")
vi.useFakeTimers()
view.rerender(
<runtime.context.Provider value={effectRuntime}>
@@ -283,16 +285,19 @@ describe("Component", () => {
</runtime.context.Provider>
)
await screen.findByText("second")
expect(screen.getByText("second")).toBeTruthy()
expect(cleanup).not.toHaveBeenCalled()
await new Promise(resolve => setTimeout(resolve, 5))
await vi.advanceTimersByTimeAsync(19)
expect(cleanup).not.toHaveBeenCalled()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("first"), { timeout: 100 })
await vi.advanceTimersByTimeAsync(1)
expect(cleanup).toHaveBeenCalledWith("first")
view.unmount()
await waitFor(() => expect(cleanup).toHaveBeenCalledWith("second"), { timeout: 100 })
await vi.advanceTimersByTimeAsync(20)
expect(cleanup).toHaveBeenCalledWith("second")
vi.useRealTimers()
await runtime.runtime.dispose()
})
@@ -311,7 +316,7 @@ describe("Component", () => {
yield* Effect.addFinalizer(() => Effect.sync(() => unmounts()))
}))
return <button onClick={() => setCount(value => value + 1)}>{`${service.value}:${count}`}</button>
return <button type="button" onClick={() => setCount(value => value + 1)}>{`${service.value}:${count}`}</button>
}).pipe(
Component.withOptions({
nonReactiveTags: [...Component.defaultOptions.nonReactiveTags, ValueService],
@@ -529,4 +534,42 @@ describe("Component", () => {
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()
})
})
@@ -5,7 +5,7 @@ import * as React from "react"
import * as ScopeRegistry from "./ScopeRegistry.js"
export const ComponentTypeId: unique symbol = Symbol.for("@effect-fc/Component/Component")
export const ComponentTypeId: unique symbol = Symbol.for("@effect-view/Component/Component")
export type ComponentTypeId = typeof ComponentTypeId
/**
@@ -44,10 +44,15 @@ export declare namespace Component {
export interface ComponentImpl<P extends {}, A extends React.ReactNode, E, R, F extends Component.Signature>
extends Component<P, A, E, R, F>, ComponentImplPrototype<R, F> {}
export declare namespace ComponentImpl {
export type Any = ComponentImpl<any, any, any, any, any>
}
export interface ComponentImplPrototype<R, F extends Component.Signature> {
readonly use: Effect.Effect<F, never, Exclude<R, Scope.Scope>>
asFunctionComponent(contextRef: React.Ref<Context.Context<Exclude<R, Scope.Scope>>>): F
makeFunctionComponent(contextRef: React.Ref<Context.Context<Exclude<R, Scope.Scope>>>): F
setFunctionComponentName(f: F): void
transformFunctionComponent(f: F): F
}
@@ -55,7 +60,7 @@ export interface ComponentImplPrototype<R, F extends Component.Signature> {
export const ComponentImplPrototype: ComponentImplPrototype<any, any> = Object.freeze({
get use() { return use(this) },
asFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Signature>(
makeFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Signature>(
this: ComponentImpl<P, A, E, R, F>,
contextRef: React.RefObject<Context.Context<Exclude<R, Scope.Scope>>>,
) {
@@ -67,6 +72,13 @@ export const ComponentImplPrototype: ComponentImplPrototype<any, any> = Object.f
)
},
asFunctionComponent<P extends {}, A extends React.ReactNode, E, R, F extends Component.Signature>(
this: ComponentImpl<P, A, E, R, F>,
contextRef: React.RefObject<Context.Context<Exclude<R, Scope.Scope>>>,
) {
return this.makeFunctionComponent(contextRef)
},
setFunctionComponentName<P extends {}, A extends React.ReactNode, E, R, F extends Component.Signature>(
this: ComponentImpl<P, A, E, R, F>,
f: React.FC<P>,
@@ -404,9 +416,9 @@ export declare namespace make {
}
/**
* Creates an Effect-FC Component using the same overloads and pipeline composition style as `Effect.fn`.
* Creates an Effect View Component using the same overloads and pipeline composition style as `Effect.fn`.
*
* This is the **recommended** approach for defining Effect-FC components. It provides comprehensive
* This is the **recommended** approach for defining Effect View components. It provides comprehensive
* support for multiple component definition patterns:
*
* - **Generator syntax** (yield* style): Most ergonomic and readable approach for sequential operations
@@ -479,7 +491,7 @@ export const make: (
}
/**
* Creates an Effect-FC Component without automatic distributed tracing.
* Creates an Effect View Component without automatic distributed tracing.
*
* This function provides the same API surface as `make`, but does not create automatic tracing spans.
* It follows the exact same overload structure as `Effect.fnUntraced`.
@@ -596,19 +608,19 @@ export const withOptions: {
))
/**
* Wraps an Effect-FC Component and converts it into a standard React function component,
* serving as an **entrypoint** into an Effect-FC component hierarchy.
* Wraps an Effect View Component and converts it into a standard React function component,
* serving as an **entrypoint** into an Effect View component hierarchy.
*
* This is how Effect-FC components are integrated with the broader React ecosystem,
* This is how Effect View components are integrated with the broader React ecosystem,
* particularly when:
* - Using client-side routers (TanStack Router, React Router, etc.)
* - Implementing lazy-loaded or code-split routes
* - Connecting to third-party libraries expecting standard React components
* - Creating component boundaries between Effect-FC and non-Effect-FC code
* - Creating component boundaries between Effect View and non-Effect View code
*
* The Effect runtime is obtained from the provided React Context.
*
* @param self - The Effect-FC Component to be rendered as a standard React component
* @param self - The Effect View Component to be rendered as a standard React component
* @param context - React Context providing the Effect Runtime for this component tree.
* Create this using the `ReactRuntime` module.
*
@@ -6,7 +6,7 @@ import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const FormTypeId: unique symbol = Symbol.for("@effect-fc/Form/Form")
export const FormTypeId: unique symbol = Symbol.for("@effect-view/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>
@@ -2,9 +2,9 @@ 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 "../src/Component.js"
import * as Lens from "../src/Lens.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as Component from "./Component.js"
import * as Lens from "./Lens.js"
import * as ReactRuntime from "./ReactRuntime.js"
const makeRuntime = async () => {
@@ -18,6 +18,12 @@ const makeRuntime = async () => {
}
}
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()
@@ -30,7 +36,7 @@ describe("Lens", () => {
return (
<>
<div>{value}</div>
<button onClick={() => setValue(previous => previous + 1)}>increment</button>
<button type="button" onClick={() => setValue(previous => previous + 1)}>increment</button>
</>
)
}).pipe(
@@ -102,7 +108,7 @@ describe("Lens", () => {
lens = reactLens
}))
return <button onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
return <button type="button" onClick={() => setValue(previous => `${previous}!`)}>{value}</button>
}).pipe(
Component.withContext(runtime.context)
)
@@ -118,7 +124,7 @@ describe("Lens", () => {
fireEvent.click(screen.getByRole("button", { name: "hello" }))
await screen.findByText("hello!")
await waitFor(async () => expect(await Effect.runPromise(Lens.get(lens!))).toBe("hello!"))
await waitFor(async () => expect(await Effect.runPromise(Lens.get(expectDefined(lens)))).toBe("hello!"))
view.unmount()
await dispose()
@@ -152,11 +158,11 @@ describe("Lens", () => {
await screen.findByText("first")
await waitFor(() => expect(lens).toBeDefined())
await Effect.runPromise(Lens.set(lens!, { id: 1, label: "ignored" }))
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(lens!, { id: 2, label: "updated" }))
await Effect.runPromise(Lens.set(expectDefined(lens), { id: 2, label: "updated" }))
await screen.findByText("updated")
view.unmount()
@@ -5,7 +5,7 @@ import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const LensFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/LensForm")
export const LensFormTypeId: unique symbol = Symbol.for("@effect-view/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>
@@ -4,7 +4,7 @@ import * as React from "react"
import type * as Component from "./Component.js"
export const MemoizedTypeId: unique symbol = Symbol.for("@effect-fc/Memoized/Memoized")
export const MemoizedTypeId: unique symbol = Symbol.for("@effect-view/Memoized/Memoized")
export type MemoizedTypeId = typeof MemoizedTypeId
@@ -4,7 +4,7 @@ import * as Lens from "./Lens.js"
import * as View from "./View.js"
export const MutationTypeId: unique symbol = Symbol.for("@effect-fc/Mutation/Mutation")
export const MutationTypeId: unique symbol = Symbol.for("@effect-view/Mutation/Mutation")
export type MutationTypeId = typeof MutationTypeId
export interface Mutation<in out K, out A, out E = never, in out R = never>
@@ -7,7 +7,7 @@ import * as Mutation from "./Mutation.js"
import * as View from "./View.js"
export const MutationFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/MutationForm")
export const MutationFormTypeId: unique symbol = Symbol.for("@effect-view/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>
@@ -1,9 +1,9 @@
import { Effect, type Scope, Stream } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import { describe, expect, it } from "vitest"
import * as Query from "../src/Query.js"
import * as QueryClient from "../src/QueryClient.js"
import * as View from "../src/View.js"
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>) =>
@@ -5,7 +5,7 @@ import * as QueryClient from "./QueryClient.js"
import * as View from "./View.js"
export const QueryTypeId: unique symbol = Symbol.for("@effect-fc/Query/Query")
export const QueryTypeId: unique symbol = Symbol.for("@effect-view/Query/Query")
export type QueryTypeId = typeof QueryTypeId
export interface Query<in out K, out A, out E = never, in out R = never>
@@ -4,7 +4,7 @@ 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 const QueryClientServiceTypeId: unique symbol = Symbol.for("@effect-view/QueryClient/QueryClientService")
export type QueryClientServiceTypeId = typeof QueryClientServiceTypeId
export interface QueryClientService extends Pipeable.Pipeable {
@@ -27,7 +27,7 @@ export interface QueryClientService extends Pipeable.Pipeable {
}
export class QueryClient extends Context.Service<QueryClient, QueryClientService>()(
"@effect-fc/QueryClient/QueryClient"
"@effect-view/QueryClient/QueryClient"
) {}
export class QueryClientServiceImpl
@@ -129,7 +129,7 @@ export const service = (
export const layer = (options?: service.Options) => Layer.effect(QueryClient, service(options))
export const QueryClientCacheKeyTypeId: unique symbol = Symbol.for("@effect-fc/QueryClient/QueryClientCacheKey")
export const QueryClientCacheKeyTypeId: unique symbol = Symbol.for("@effect-view/QueryClient/QueryClientCacheKey")
export type QueryClientCacheKeyTypeId = typeof QueryClientCacheKeyTypeId
export class QueryClientCacheKey
@@ -155,7 +155,7 @@ implements Pipeable.Pipeable, Equal.Equal {
export const isQueryClientCacheKey = (u: unknown): u is QueryClientCacheKey => Predicate.hasProperty(u, QueryClientCacheKeyTypeId)
export const QueryClientCacheEntryTypeId: unique symbol = Symbol.for("@effect-fc/QueryClient/QueryClientCacheEntry")
export const QueryClientCacheEntryTypeId: unique symbol = Symbol.for("@effect-view/QueryClient/QueryClientCacheEntry")
export type QueryClientCacheEntryTypeId = typeof QueryClientCacheEntryTypeId
export class QueryClientCacheEntry
@@ -5,7 +5,7 @@ import * as Component from "./Component.js"
import * as ScopeRegistry from "./ScopeRegistry.js"
export const ReactRuntimeTypeId: unique symbol = Symbol.for("@effect-fc/ReactRuntime/ReactRuntime")
export const ReactRuntimeTypeId: unique symbol = Symbol.for("@effect-view/ReactRuntime/ReactRuntime")
export type ReactRuntimeTypeId = typeof ReactRuntimeTypeId
export interface ReactRuntime<R, ER> {
@@ -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
}
@@ -2,9 +2,9 @@ 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 "../src/Component.js"
import * as ReactRuntime from "../src/ReactRuntime.js"
import * as View from "../src/View.js"
import * as Component from "./Component.js"
import * as ReactRuntime from "./ReactRuntime.js"
import * as View from "./View.js"
const makeRuntime = async () => {
@@ -1,6 +1,5 @@
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 LensForm from "./LensForm.js"
@@ -11,6 +10,7 @@ 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"

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