Add Effect v4 support, Fast Refresh tooling, and revamped docs (#56)
## 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
This commit was merged in pull request #56.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
.tanstack
|
||||
@@ -0,0 +1,10 @@
|
||||
# Effect FC Next Example
|
||||
|
||||
Minimal React example for `effect-fc-next`, Effect V4, and `effect-lens@2`.
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
The counter demonstrates a V4 `SubscriptionRef` exposed as an Effect Lens and
|
||||
rendered through an Effect-FC component.
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/latest/schema.json",
|
||||
"root": false,
|
||||
"extends": "//",
|
||||
"files": {
|
||||
"includes": ["./src/**", "!src/routeTree.gen.ts"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + React + TS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@effect-fc/example-next",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc -b && vite build",
|
||||
"dev": "vite",
|
||||
"lint:tsc": "tsc -b --noEmit",
|
||||
"lint:biome": "biome lint",
|
||||
"preview": "vite preview",
|
||||
"clean:cache": "rm -rf .turbo node_modules/.tmp node_modules/.vite* .tanstack",
|
||||
"clean:dist": "rm -rf dist",
|
||||
"clean:modules": "rm -rf node_modules"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect-view/vite-plugin": "workspace:*",
|
||||
"@tanstack/react-router": "^1.170.10",
|
||||
"@tanstack/react-router-devtools": "^1.167.0",
|
||||
"@tanstack/router-plugin": "^1.168.13",
|
||||
"@types/react": "^19.2.15",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"globals": "^17.6.0",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"vite": "^8.0.16"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-browser": "4.0.0-beta.98",
|
||||
"@radix-ui/themes": "^3.3.0",
|
||||
"effect": "4.0.0-beta.98",
|
||||
"effect-fc-next": "workspace:*",
|
||||
"react-icons": "^5.6.0"
|
||||
},
|
||||
"overrides": {
|
||||
"@types/react": "^19.2.15",
|
||||
"effect": "4.0.0-beta.98",
|
||||
"react": "^19.2.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Callout, Flex, Spinner, TextField } from "@radix-ui/themes"
|
||||
import { Array, Option, Struct } from "effect"
|
||||
import { Component, Form, View } from "effect-fc-next"
|
||||
import type * as React from "react"
|
||||
|
||||
|
||||
export declare namespace TextFieldFormInputView {
|
||||
export interface Props<out P extends readonly PropertyKey[], A, ER, EW>
|
||||
extends Omit<TextField.RootProps, "form">, Form.useInput.Options {
|
||||
readonly form: Form.Form<P, A, string, ER, EW>
|
||||
}
|
||||
|
||||
export type Signature = <P extends readonly PropertyKey[], A, ER, EW>(props: Props<P, A, ER, EW>) => React.ReactNode
|
||||
}
|
||||
|
||||
export const TextFieldFormInputView = Component.make("TextFieldFormInputView")(function*(
|
||||
props: TextFieldFormInputView.Props<readonly PropertyKey[], any, any, any>
|
||||
) {
|
||||
const input = yield* Form.useInput(props.form, props)
|
||||
const [issues, isValidating, isCommitting] = yield* View.useAll([
|
||||
props.form.issues,
|
||||
props.form.isValidating,
|
||||
props.form.isCommitting,
|
||||
])
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap="1">
|
||||
<TextField.Root
|
||||
value={input.value}
|
||||
onChange={e => input.setValue(e.target.value)}
|
||||
disabled={isCommitting}
|
||||
{...Struct.omit(props, ["form"])}
|
||||
>
|
||||
{isValidating &&
|
||||
<TextField.Slot side="right">
|
||||
<Spinner />
|
||||
</TextField.Slot>
|
||||
}
|
||||
|
||||
{props.children}
|
||||
</TextField.Root>
|
||||
|
||||
{Option.match(Array.head(issues), {
|
||||
onSome: issue => (
|
||||
<Callout.Root>
|
||||
<Callout.Text>{issue.message}</Callout.Text>
|
||||
</Callout.Root>
|
||||
),
|
||||
|
||||
onNone: () => <></>,
|
||||
})}
|
||||
</Flex>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withSignature<TextFieldFormInputView.Signature>()
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Callout, Flex, Spinner, Switch, TextField } from "@radix-ui/themes"
|
||||
import { Array, Option, Struct } from "effect"
|
||||
import { Component, Form, View } from "effect-fc-next"
|
||||
import type * as React from "react"
|
||||
|
||||
|
||||
export declare namespace TextFieldOptionalFormInputView {
|
||||
export interface Props<out P extends readonly PropertyKey[], A, ER, EW>
|
||||
extends Omit<TextField.RootProps, "form" | "defaultValue">, Form.useOptionalInput.Options<string> {
|
||||
readonly form: Form.Form<P, A, Option.Option<string>, ER, EW>
|
||||
}
|
||||
|
||||
export type Signature = <P extends readonly PropertyKey[], A, ER, EW>(props: Props<P, A, ER, EW>) => React.ReactNode
|
||||
}
|
||||
|
||||
export const TextFieldOptionalFormInputView = Component.make("TextFieldOptionalFormInputView")(function*(
|
||||
props: TextFieldOptionalFormInputView.Props<readonly PropertyKey[], any, any, any>
|
||||
) {
|
||||
const input = yield* Form.useOptionalInput(props.form, props)
|
||||
const [issues, isValidating, isCommitting] = yield* View.useAll([
|
||||
props.form.issues,
|
||||
props.form.isValidating,
|
||||
props.form.isCommitting,
|
||||
])
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap="1">
|
||||
<TextField.Root
|
||||
value={input.value}
|
||||
onChange={e => input.setValue(e.target.value)}
|
||||
disabled={!input.enabled || isCommitting}
|
||||
{...Struct.omit(props, ["form", "defaultValue"])}
|
||||
>
|
||||
<TextField.Slot side="left">
|
||||
<Switch
|
||||
size="1"
|
||||
checked={input.enabled}
|
||||
onCheckedChange={input.setEnabled}
|
||||
/>
|
||||
</TextField.Slot>
|
||||
|
||||
{isValidating &&
|
||||
<TextField.Slot side="right">
|
||||
<Spinner />
|
||||
</TextField.Slot>
|
||||
}
|
||||
|
||||
{props.children}
|
||||
</TextField.Root>
|
||||
|
||||
{Option.match(Array.head(issues), {
|
||||
onSome: issue => (
|
||||
<Callout.Root>
|
||||
<Callout.Text>{issue.message}</Callout.Text>
|
||||
</Callout.Root>
|
||||
),
|
||||
|
||||
onNone: () => <></>,
|
||||
})}
|
||||
</Flex>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withSignature<TextFieldOptionalFormInputView.Signature>()
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createRouter, RouterProvider } from "@tanstack/react-router"
|
||||
import { ReactRuntime } from "effect-fc-next"
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { routeTree } from "./routeTree.gen"
|
||||
import { runtime } from "./runtime"
|
||||
|
||||
const router = createRouter({ routeTree })
|
||||
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register { router: typeof router }
|
||||
}
|
||||
|
||||
// biome-ignore lint/style/noNonNullAssertion: the Vite template provides this element
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<ReactRuntime.Provider runtime={runtime}>
|
||||
<RouterProvider router={router} />
|
||||
</ReactRuntime.Provider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,149 @@
|
||||
/* eslint-disable */
|
||||
|
||||
// @ts-nocheck
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
// This file was automatically generated by TanStack Router.
|
||||
// You should NOT make any changes in this file as it will be overwritten.
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as AsyncRouteImport } from './routes/async'
|
||||
import { Route as BlankRouteImport } from './routes/blank'
|
||||
import { Route as FormRouteImport } from './routes/form'
|
||||
import { Route as LensformRouteImport } from './routes/lensform'
|
||||
import { Route as QueryRouteImport } from './routes/query'
|
||||
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AsyncRoute = AsyncRouteImport.update({
|
||||
id: '/async',
|
||||
path: '/async',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const BlankRoute = BlankRouteImport.update({
|
||||
id: '/blank',
|
||||
path: '/blank',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const FormRoute = FormRouteImport.update({
|
||||
id: '/form',
|
||||
path: '/form',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const LensformRoute = LensformRouteImport.update({
|
||||
id: '/lensform',
|
||||
path: '/lensform',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const QueryRoute = QueryRouteImport.update({
|
||||
id: '/query',
|
||||
path: '/query',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/async': typeof AsyncRoute
|
||||
'/blank': typeof BlankRoute
|
||||
'/form': typeof FormRoute
|
||||
'/lensform': typeof LensformRoute
|
||||
'/query': typeof QueryRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/async': typeof AsyncRoute
|
||||
'/blank': typeof BlankRoute
|
||||
'/form': typeof FormRoute
|
||||
'/lensform': typeof LensformRoute
|
||||
'/query': typeof QueryRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/async': typeof AsyncRoute
|
||||
'/blank': typeof BlankRoute
|
||||
'/form': typeof FormRoute
|
||||
'/lensform': typeof LensformRoute
|
||||
'/query': typeof QueryRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
|
||||
id: '__root__' | '/' | '/async' | '/blank' | '/form' | '/lensform' | '/query'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
AsyncRoute: typeof AsyncRoute
|
||||
BlankRoute: typeof BlankRoute
|
||||
FormRoute: typeof FormRoute
|
||||
LensformRoute: typeof LensformRoute
|
||||
QueryRoute: typeof QueryRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/': {
|
||||
id: '/'
|
||||
path: '/'
|
||||
fullPath: '/'
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/async': {
|
||||
id: '/async'
|
||||
path: '/async'
|
||||
fullPath: '/async'
|
||||
preLoaderRoute: typeof AsyncRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/blank': {
|
||||
id: '/blank'
|
||||
path: '/blank'
|
||||
fullPath: '/blank'
|
||||
preLoaderRoute: typeof BlankRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/form': {
|
||||
id: '/form'
|
||||
path: '/form'
|
||||
fullPath: '/form'
|
||||
preLoaderRoute: typeof FormRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/lensform': {
|
||||
id: '/lensform'
|
||||
path: '/lensform'
|
||||
fullPath: '/lensform'
|
||||
preLoaderRoute: typeof LensformRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/query': {
|
||||
id: '/query'
|
||||
path: '/query'
|
||||
fullPath: '/query'
|
||||
preLoaderRoute: typeof QueryRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
AsyncRoute: AsyncRoute,
|
||||
BlankRoute: BlankRoute,
|
||||
FormRoute: FormRoute,
|
||||
LensformRoute: LensformRoute,
|
||||
QueryRoute: QueryRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
._addFileTypes<FileRouteTypes>()
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Container, Flex, Theme } from "@radix-ui/themes"
|
||||
import { createRootRoute, Link, Outlet } from "@tanstack/react-router"
|
||||
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools"
|
||||
|
||||
import "@radix-ui/themes/styles.css"
|
||||
import "../index.css"
|
||||
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: Root,
|
||||
})
|
||||
|
||||
function Root() {
|
||||
return (
|
||||
<Theme>
|
||||
<Container mb="4">
|
||||
<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>
|
||||
|
||||
<Outlet />
|
||||
|
||||
<TanStackRouterDevtools />
|
||||
</Theme>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
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 * 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}.`,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
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],
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Heading>{post.title}</Heading>
|
||||
<Text>{post.body}</Text>
|
||||
</div>
|
||||
)
|
||||
}).pipe(
|
||||
Async.async,
|
||||
Async.withOptions({ defaultFallback: <Text>Loading post...</Text> }),
|
||||
Memoized.memoized,
|
||||
)
|
||||
|
||||
const AsyncRouteComponent = Component.make("AsyncRouteView")(function*() {
|
||||
const [text, setText] = React.useState("Typing here should not trigger a refetch of the post")
|
||||
const [id, setId] = React.useState(1)
|
||||
|
||||
const AsyncFetchPost = yield* AsyncFetchPostView.use
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Flex direction="column" align="stretch" gap="2">
|
||||
<TextField.Root
|
||||
value={text}
|
||||
onChange={event => setText(event.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<Slider
|
||||
value={[id]}
|
||||
min={1}
|
||||
max={10}
|
||||
onValueChange={([value]) => setId(value ?? 1)}
|
||||
/>
|
||||
|
||||
<AsyncFetchPost id={id} />
|
||||
</Flex>
|
||||
</Container>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withContext(runtime.context),
|
||||
)
|
||||
|
||||
export const Route = createFileRoute("/async")({
|
||||
component: AsyncRouteComponent,
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
|
||||
|
||||
export const Route = createFileRoute("/blank")({
|
||||
component: RouteComponent
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
return <div>Hello "/blank"!</div>
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Button, Container, Flex, Text } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Console, Effect, Schema } from "effect"
|
||||
import { Component, Form, MutationForm, View } from "effect-fc-next"
|
||||
import { TextFieldFormInputView } from "@/lib/form/TextFieldFormInputView"
|
||||
import { runtime } from "@/runtime"
|
||||
|
||||
|
||||
const RegisterSchema = Schema.Struct({
|
||||
email: Schema.String.check(
|
||||
Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, {
|
||||
message: "Enter a valid email address",
|
||||
}),
|
||||
),
|
||||
password: Schema.String.check(
|
||||
Schema.isMinLength(5, {
|
||||
message: "Password must be at least 5 characters long",
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
const RegisterRouteComponent = Component.make("RegisterRouteView")(function*() {
|
||||
yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
yield* Effect.addFinalizer(() => Console.log("Form route unmounted"))
|
||||
yield* Console.log("Form route mounted")
|
||||
}))
|
||||
|
||||
const [form, emailField, passwordField] = yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
const form = yield* MutationForm.service({
|
||||
schema: RegisterSchema,
|
||||
initialEncodedValue: { email: "", password: "" },
|
||||
f: ([value]) => Effect.log(`Registered ${value.email}`),
|
||||
})
|
||||
|
||||
const emailField = Form.focusObjectOn(form, "email")
|
||||
const passwordField = Form.focusObjectOn(form, "password")
|
||||
|
||||
return [form, emailField, passwordField] as const
|
||||
}))
|
||||
|
||||
const [canCommit, isCommitting] = yield* View.useAll([
|
||||
form.canCommit,
|
||||
form.isCommitting,
|
||||
])
|
||||
|
||||
const TextFieldFormInput = yield* TextFieldFormInputView.use
|
||||
const runPromise = yield* Component.useRunPromise()
|
||||
|
||||
|
||||
return (
|
||||
<Container width="300">
|
||||
<form onSubmit={event => {
|
||||
event.preventDefault()
|
||||
void runPromise(form.submit)
|
||||
}}>
|
||||
<Flex direction="column" gap="2">
|
||||
<TextFieldFormInput
|
||||
form={emailField}
|
||||
placeholder="Email"
|
||||
debounce="250 millis"
|
||||
/>
|
||||
<TextFieldFormInput
|
||||
form={passwordField}
|
||||
placeholder="Password"
|
||||
type="password"
|
||||
debounce="250 millis"
|
||||
/>
|
||||
<Button disabled={!canCommit || isCommitting}>
|
||||
{isCommitting ? "Submitting…" : "Submit"}
|
||||
</Button>
|
||||
</Flex>
|
||||
</form>
|
||||
<Text size="2">A MutationForm validates local input, then submits it.</Text>
|
||||
</Container>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withContext(runtime.context),
|
||||
)
|
||||
|
||||
export const Route = createFileRoute("/form")({
|
||||
component: RegisterRouteComponent,
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Button, Container, Flex, Text, TextField } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Effect, SubscriptionRef } from "effect"
|
||||
import { Component, Lens, View } from "effect-fc-next"
|
||||
import { runtime } from "@/runtime"
|
||||
|
||||
|
||||
const TodoRouteComponent = Component.make("TodoRouteView")(function*() {
|
||||
const todosLens = yield* Component.useOnMount(() => Effect.map(
|
||||
SubscriptionRef.make<readonly string[]>([]),
|
||||
Lens.fromSubscriptionRef,
|
||||
))
|
||||
const draftLens = yield* Component.useOnMount(() => Effect.map(
|
||||
SubscriptionRef.make(""),
|
||||
Lens.fromSubscriptionRef,
|
||||
))
|
||||
|
||||
const [todos] = yield* View.useAll([todosLens])
|
||||
const [draft, setDraft] = yield* Lens.useState(draftLens)
|
||||
const runPromise = yield* Component.useRunPromise()
|
||||
|
||||
const addTodo = Lens.update(todosLens, todos =>
|
||||
draft.trim() === ""
|
||||
? todos
|
||||
: [...todos, draft.trim()],
|
||||
).pipe(
|
||||
Effect.andThen(Lens.set(draftLens, "")),
|
||||
)
|
||||
|
||||
return (
|
||||
<Container width="480">
|
||||
<Flex direction="column" gap="3">
|
||||
<Text size="2">A small Effect v4 todo state example backed by a Lens.</Text>
|
||||
|
||||
<Flex gap="2">
|
||||
<TextField.Root
|
||||
value={draft}
|
||||
onChange={event => setDraft(event.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<Button onClick={() => void runPromise(addTodo)}>
|
||||
Add
|
||||
</Button>
|
||||
</Flex>
|
||||
|
||||
{todos.map(todo => <Text key={todo}>• {todo}</Text>)}
|
||||
</Flex>
|
||||
</Container>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withContext(runtime.context),
|
||||
)
|
||||
|
||||
export const Route = createFileRoute("/")({
|
||||
component: TodoRouteComponent,
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Container, Flex } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Console, Context, Effect, Layer, Schema, Stream, SubscriptionRef } from "effect"
|
||||
import { Component, Form, Lens, LensForm } from "effect-fc-next"
|
||||
import { TextFieldFormInputView } from "@/lib/form/TextFieldFormInputView"
|
||||
import { runtime } from "@/runtime"
|
||||
|
||||
|
||||
const UserProfileSchema = Schema.Struct({
|
||||
email: Schema.String.check(
|
||||
Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, {
|
||||
message: "Enter a valid email address",
|
||||
}),
|
||||
),
|
||||
password: Schema.String.check(
|
||||
Schema.isMinLength(5, {
|
||||
message: "Password must be at least 5 characters long",
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
const AppStateSchema = Schema.Struct({
|
||||
currentUser: UserProfileSchema,
|
||||
})
|
||||
|
||||
class AppState extends Context.Service<AppState, {
|
||||
readonly lens: Lens.Lens<typeof AppStateSchema.Type>
|
||||
}>()("AppState") {
|
||||
static readonly layer = Layer.effect(AppState, Effect.gen(function*() {
|
||||
return {
|
||||
lens: Lens.fromSubscriptionRef(
|
||||
yield* SubscriptionRef.make<typeof AppStateSchema.Type>({
|
||||
currentUser: {
|
||||
email: "",
|
||||
password: "",
|
||||
},
|
||||
})
|
||||
),
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
const LensFormPageView = Component.make("LensFormPageView")(function*() {
|
||||
yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
yield* Effect.addFinalizer(() => Console.log("LensForm route unmounted"))
|
||||
yield* Console.log("LensForm route mounted")
|
||||
}))
|
||||
|
||||
const context = yield* Component.useLayer(AppState.layer)
|
||||
const UserProfileEditor = yield* Effect.provide(UserProfileEditorView.use, context)
|
||||
|
||||
return <UserProfileEditor />
|
||||
})
|
||||
|
||||
|
||||
const UserProfileEditorView = Component.make("UserProfileEditorView")(function*() {
|
||||
const appState = yield* AppState
|
||||
|
||||
const [
|
||||
emailField,
|
||||
passwordField,
|
||||
] = yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Lens.changes(appState.lens), Console.log)
|
||||
)
|
||||
|
||||
const form = yield* LensForm.service({
|
||||
schema: UserProfileSchema,
|
||||
target: Lens.focusObjectOn(appState.lens, "currentUser"),
|
||||
initialEncodedValue: {
|
||||
email: "",
|
||||
password: "",
|
||||
},
|
||||
})
|
||||
|
||||
const emailField = Form.focusObjectOn(form, "email")
|
||||
const passwordField = Form.focusObjectOn(form, "password")
|
||||
|
||||
return [emailField, passwordField] as const
|
||||
}))
|
||||
|
||||
const TextFieldFormInput = yield* TextFieldFormInputView.use
|
||||
|
||||
|
||||
return (
|
||||
<Container width="300">
|
||||
<form onSubmit={event => {
|
||||
event.preventDefault()
|
||||
}}>
|
||||
<Flex direction="column" gap="2">
|
||||
<TextFieldFormInput
|
||||
form={emailField}
|
||||
placeholder="Email"
|
||||
debounce="250 millis"
|
||||
/>
|
||||
<TextFieldFormInput
|
||||
form={passwordField}
|
||||
placeholder="Password"
|
||||
type="password"
|
||||
debounce="250 millis"
|
||||
/>
|
||||
</Flex>
|
||||
</form>
|
||||
</Container>
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
export const Route = createFileRoute("/lensform")({
|
||||
component: Component.withContext(LensFormPageView, runtime.context),
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Button, Container, Flex, Heading, Slider, Text } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Effect, Schema, SubscriptionRef } from "effect"
|
||||
import { HttpClient } from "effect/unstable/http"
|
||||
import { AsyncResult } from "effect/unstable/reactivity"
|
||||
import { Component, Lens, Mutation, Query, View } from "effect-fc-next"
|
||||
import { runtime } from "@/runtime"
|
||||
|
||||
|
||||
const Post = Schema.Struct({
|
||||
userId: Schema.Int,
|
||||
id: Schema.Int,
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
})
|
||||
|
||||
|
||||
interface PostResultViewProps {
|
||||
readonly result: AsyncResult.AsyncResult<typeof Post.Type, Error>
|
||||
}
|
||||
|
||||
const PostResultView = (props: PostResultViewProps) => AsyncResult.match(props.result, {
|
||||
onInitial: result => result.waiting
|
||||
? <Text>Loading...</Text>
|
||||
: <Text>No data.</Text>,
|
||||
onFailure: result => <Text>Request failed: { result.cause.toString() }</Text>,
|
||||
onSuccess: result => <>
|
||||
{result.waiting && <Text>Refreshing...</Text>}
|
||||
<Heading>{result.value.title}</Heading>
|
||||
<Text>{result.value.body}</Text>
|
||||
</>,
|
||||
})
|
||||
|
||||
const QueryRouteComponent = Component.make("QueryRouteView")(function*() {
|
||||
const [idLens, query, mutation] = yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
const keyLens = Lens.fromSubscriptionRef(yield* SubscriptionRef.make(["post", 1 as number] as const))
|
||||
const idLens = Lens.focusTupleAt(keyLens, 1)
|
||||
|
||||
const query = yield* Query.service({
|
||||
key: keyLens,
|
||||
f: ([, id]) => HttpClient.HttpClient.pipe(
|
||||
Effect.tap(Effect.sleep("1 second")),
|
||||
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ id }`)),
|
||||
Effect.andThen(response => response.json),
|
||||
Effect.andThen(Schema.decodeUnknownEffect(Post)),
|
||||
),
|
||||
staleTime: "10 seconds",
|
||||
})
|
||||
|
||||
const mutation = yield* Mutation.make({
|
||||
f: ([id]: [id: number]) => HttpClient.HttpClient.pipe(
|
||||
Effect.tap(Effect.sleep("1 second")),
|
||||
Effect.andThen(client => client.get(`https://jsonplaceholder.typicode.com/posts/${ id }`)),
|
||||
Effect.andThen(response => response.json),
|
||||
Effect.andThen(Schema.decodeUnknownEffect(Post)),
|
||||
),
|
||||
})
|
||||
|
||||
return [idLens, query, mutation] as const
|
||||
}))
|
||||
|
||||
const [id, setId] = yield* Lens.useState(idLens)
|
||||
const [queryState, mutationState] = yield* View.useAll([query.state, mutation.state])
|
||||
|
||||
const runSync = yield* Component.useRunSync()
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Flex direction="column" align="center" gap="2">
|
||||
<Slider
|
||||
value={[id]}
|
||||
min={1}
|
||||
max={10}
|
||||
onValueChange={([value]) => setId(value ?? 1)}
|
||||
/>
|
||||
|
||||
<PostResultView result={queryState.result} />
|
||||
|
||||
<Flex direction="row" justify="center" align="center" gap="1">
|
||||
<Button onClick={() => runSync(query.refreshView)}>
|
||||
Refresh
|
||||
</Button>
|
||||
<Button onClick={() => runSync(query.invalidateCache)}>
|
||||
Invalidate cache
|
||||
</Button>
|
||||
</Flex>
|
||||
|
||||
<PostResultView result={mutationState} />
|
||||
|
||||
<Button onClick={() => runSync(mutation.mutateView([id]))}>
|
||||
Mutate
|
||||
</Button>
|
||||
</Flex>
|
||||
</Container>
|
||||
)
|
||||
}).pipe(
|
||||
Component.withContext(runtime.context),
|
||||
)
|
||||
|
||||
export const Route = createFileRoute("/query")({
|
||||
component: QueryRouteComponent,
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
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"
|
||||
|
||||
|
||||
export const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(QueryClient.layer()),
|
||||
Layer.provideMerge(DateTime.layerCurrentZoneLocal),
|
||||
Layer.provideMerge(Clipboard.layer),
|
||||
Layer.provideMerge(Geolocation.layer),
|
||||
Layer.provideMerge(Permissions.layer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
)
|
||||
|
||||
export const runtime = ReactRuntime.make(layer)
|
||||
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
"plugins": [
|
||||
{ "name": "@effect/language-service" }
|
||||
]
|
||||
},
|
||||
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { tanstackRouter } from "@tanstack/router-plugin/vite"
|
||||
import react from "@vitejs/plugin-react"
|
||||
import { effectViewPlugin } from "@effect-view/vite-plugin"
|
||||
import path from "node:path"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
effectViewPlugin(),
|
||||
tanstackRouter({
|
||||
target: "react",
|
||||
autoCodeSplitting: true,
|
||||
}),
|
||||
react(),
|
||||
],
|
||||
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user