0.1.3 (#5)
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com> Reviewed-on: https://gitea:3000/Thilawyn/reffuse/pulls/5
This commit was merged in pull request #5.
This commit is contained in:
@@ -12,35 +12,41 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.21.0",
|
||||
"@tanstack/react-router": "^1.111.7",
|
||||
"@tanstack/router-devtools": "^1.111.7",
|
||||
"@tanstack/router-plugin": "^1.111.7",
|
||||
"@tanstack/react-router": "^1.112.7",
|
||||
"@tanstack/router-devtools": "^1.112.7",
|
||||
"@tanstack/router-plugin": "^1.112.7",
|
||||
"@thilawyn/thilaschema": "^0.1.4",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"eslint": "^9.21.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"typescript-eslint": "^8.25.0",
|
||||
"typescript-eslint": "^8.26.0",
|
||||
"vite": "^6.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform": "^0.77.2",
|
||||
"@effect/platform-browser": "^0.56.2",
|
||||
"@radix-ui/themes": "^3.2.0",
|
||||
"@effect/platform": "^0.77.6",
|
||||
"@effect/platform-browser": "^0.56.6",
|
||||
"@radix-ui/themes": "^3.2.1",
|
||||
"@reffuse/extension-lazyref": "workspace:*",
|
||||
"@reffuse/extension-query": "workspace:*",
|
||||
"@typed/async-data": "^0.13.1",
|
||||
"@typed/id": "^0.17.1",
|
||||
"@typed/lazy-ref": "^0.3.3",
|
||||
"effect": "^3.13.2",
|
||||
"lucide-react": "^0.476.0",
|
||||
"effect": "^3.13.6",
|
||||
"lucide-react": "^0.477.0",
|
||||
"mobx": "^6.13.6",
|
||||
"reffuse": "workspace:*"
|
||||
},
|
||||
"overrides": {
|
||||
"effect": "^3.13.2"
|
||||
"effect": "^3.13.6",
|
||||
"@effect/platform": "^0.77.6",
|
||||
"@effect/platform-browser": "^0.56.6",
|
||||
"@typed/lazy-ref": "^0.3.3",
|
||||
"@typed/async-data": "^0.13.1"
|
||||
}
|
||||
}
|
||||
|
||||
10
packages/example/src/query/reffuse.ts
Normal file
10
packages/example/src/query/reffuse.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { GlobalReffuse } from "@/reffuse"
|
||||
import { Reffuse, ReffuseContext } from "reffuse"
|
||||
import { Uuid4Query } from "./services"
|
||||
|
||||
|
||||
export const QueryContext = ReffuseContext.make<Uuid4Query.Uuid4Query>()
|
||||
|
||||
export const R = new class QueryReffuse extends GlobalReffuse.pipe(
|
||||
Reffuse.withContexts(QueryContext)
|
||||
) {}
|
||||
12
packages/example/src/query/services/Uuid4Query.ts
Normal file
12
packages/example/src/query/services/Uuid4Query.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { HttpClientError } from "@effect/platform"
|
||||
import { QueryService } from "@reffuse/extension-query"
|
||||
import { ParseResult, Schema } from "effect"
|
||||
|
||||
|
||||
export const Result = Schema.Array(Schema.String)
|
||||
|
||||
export class Uuid4Query extends QueryService.Tag("Uuid4Query")<Uuid4Query,
|
||||
readonly ["uuid4", number],
|
||||
typeof Result.Type,
|
||||
HttpClientError.HttpClientError | ParseResult.ParseError
|
||||
>() {}
|
||||
1
packages/example/src/query/services/index.ts
Normal file
1
packages/example/src/query/services/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * as Uuid4Query from "./Uuid4Query"
|
||||
32
packages/example/src/query/views/Uuid4QueryService.tsx
Normal file
32
packages/example/src/query/views/Uuid4QueryService.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Button, Container, Flex, Text } from "@radix-ui/themes"
|
||||
import * as AsyncData from "@typed/async-data"
|
||||
import { R } from "../reffuse"
|
||||
import { Uuid4Query } from "../services"
|
||||
|
||||
|
||||
export function Uuid4QueryService() {
|
||||
const runSync = R.useRunSync()
|
||||
|
||||
const query = R.useMemo(() => Uuid4Query.Uuid4Query, [])
|
||||
const [state] = R.useRefState(query.state)
|
||||
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Flex direction="column" align="center" gap="2">
|
||||
<Text>
|
||||
{AsyncData.match(state, {
|
||||
NoData: () => "No data yet",
|
||||
Loading: () => "Loading...",
|
||||
Success: (value, { isRefreshing, isOptimistic }) =>
|
||||
`Value: ${value} ${isRefreshing ? "(refreshing)" : ""} ${isOptimistic ? "(optimistic)" : ""}`,
|
||||
Failure: (cause, { isRefreshing }) =>
|
||||
`Error: ${cause} ${isRefreshing ? "(refreshing)" : ""}`,
|
||||
})}
|
||||
</Text>
|
||||
|
||||
<Button onClick={() => runSync(query.refresh)}>Refresh</Button>
|
||||
</Flex>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { HttpClient } from "@effect/platform"
|
||||
import { Clipboard, Geolocation, Permissions } from "@effect/platform-browser"
|
||||
import { LazyRefExtension } from "@reffuse/extension-lazyref"
|
||||
import { QueryExtension } from "@reffuse/extension-query"
|
||||
import { Reffuse, ReffuseContext } from "reffuse"
|
||||
|
||||
|
||||
@@ -13,6 +14,7 @@ export const GlobalContext = ReffuseContext.make<
|
||||
|
||||
export class GlobalReffuse extends Reffuse.Reffuse.pipe(
|
||||
Reffuse.withExtension(LazyRefExtension),
|
||||
Reffuse.withExtension(QueryExtension),
|
||||
Reffuse.withContexts(GlobalContext),
|
||||
) {}
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ import { Route as LazyrefImport } from './routes/lazyref'
|
||||
import { Route as CountImport } from './routes/count'
|
||||
import { Route as BlankImport } from './routes/blank'
|
||||
import { Route as IndexImport } from './routes/index'
|
||||
import { Route as QueryUsequeryImport } from './routes/query/usequery'
|
||||
import { Route as QueryServiceImport } from './routes/query/service'
|
||||
|
||||
// Create/Update Routes
|
||||
|
||||
@@ -63,6 +65,18 @@ const IndexRoute = IndexImport.update({
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
const QueryUsequeryRoute = QueryUsequeryImport.update({
|
||||
id: '/query/usequery',
|
||||
path: '/query/usequery',
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
const QueryServiceRoute = QueryServiceImport.update({
|
||||
id: '/query/service',
|
||||
path: '/query/service',
|
||||
getParentRoute: () => rootRoute,
|
||||
} as any)
|
||||
|
||||
// Populate the FileRoutesByPath interface
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -116,6 +130,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof TimeImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
'/query/service': {
|
||||
id: '/query/service'
|
||||
path: '/query/service'
|
||||
fullPath: '/query/service'
|
||||
preLoaderRoute: typeof QueryServiceImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
'/query/usequery': {
|
||||
id: '/query/usequery'
|
||||
path: '/query/usequery'
|
||||
fullPath: '/query/usequery'
|
||||
preLoaderRoute: typeof QueryUsequeryImport
|
||||
parentRoute: typeof rootRoute
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +157,8 @@ export interface FileRoutesByFullPath {
|
||||
'/promise': typeof PromiseRoute
|
||||
'/tests': typeof TestsRoute
|
||||
'/time': typeof TimeRoute
|
||||
'/query/service': typeof QueryServiceRoute
|
||||
'/query/usequery': typeof QueryUsequeryRoute
|
||||
}
|
||||
|
||||
export interface FileRoutesByTo {
|
||||
@@ -139,6 +169,8 @@ export interface FileRoutesByTo {
|
||||
'/promise': typeof PromiseRoute
|
||||
'/tests': typeof TestsRoute
|
||||
'/time': typeof TimeRoute
|
||||
'/query/service': typeof QueryServiceRoute
|
||||
'/query/usequery': typeof QueryUsequeryRoute
|
||||
}
|
||||
|
||||
export interface FileRoutesById {
|
||||
@@ -150,6 +182,8 @@ export interface FileRoutesById {
|
||||
'/promise': typeof PromiseRoute
|
||||
'/tests': typeof TestsRoute
|
||||
'/time': typeof TimeRoute
|
||||
'/query/service': typeof QueryServiceRoute
|
||||
'/query/usequery': typeof QueryUsequeryRoute
|
||||
}
|
||||
|
||||
export interface FileRouteTypes {
|
||||
@@ -162,8 +196,19 @@ export interface FileRouteTypes {
|
||||
| '/promise'
|
||||
| '/tests'
|
||||
| '/time'
|
||||
| '/query/service'
|
||||
| '/query/usequery'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/blank' | '/count' | '/lazyref' | '/promise' | '/tests' | '/time'
|
||||
to:
|
||||
| '/'
|
||||
| '/blank'
|
||||
| '/count'
|
||||
| '/lazyref'
|
||||
| '/promise'
|
||||
| '/tests'
|
||||
| '/time'
|
||||
| '/query/service'
|
||||
| '/query/usequery'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
@@ -173,6 +218,8 @@ export interface FileRouteTypes {
|
||||
| '/promise'
|
||||
| '/tests'
|
||||
| '/time'
|
||||
| '/query/service'
|
||||
| '/query/usequery'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
|
||||
@@ -184,6 +231,8 @@ export interface RootRouteChildren {
|
||||
PromiseRoute: typeof PromiseRoute
|
||||
TestsRoute: typeof TestsRoute
|
||||
TimeRoute: typeof TimeRoute
|
||||
QueryServiceRoute: typeof QueryServiceRoute
|
||||
QueryUsequeryRoute: typeof QueryUsequeryRoute
|
||||
}
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
@@ -194,6 +243,8 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
PromiseRoute: PromiseRoute,
|
||||
TestsRoute: TestsRoute,
|
||||
TimeRoute: TimeRoute,
|
||||
QueryServiceRoute: QueryServiceRoute,
|
||||
QueryUsequeryRoute: QueryUsequeryRoute,
|
||||
}
|
||||
|
||||
export const routeTree = rootRoute
|
||||
@@ -212,7 +263,9 @@ export const routeTree = rootRoute
|
||||
"/lazyref",
|
||||
"/promise",
|
||||
"/tests",
|
||||
"/time"
|
||||
"/time",
|
||||
"/query/service",
|
||||
"/query/usequery"
|
||||
]
|
||||
},
|
||||
"/": {
|
||||
@@ -235,6 +288,12 @@ export const routeTree = rootRoute
|
||||
},
|
||||
"/time": {
|
||||
"filePath": "time.tsx"
|
||||
},
|
||||
"/query/service": {
|
||||
"filePath": "query/service.tsx"
|
||||
},
|
||||
"/query/usequery": {
|
||||
"filePath": "query/usequery.tsx"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ function Root() {
|
||||
<Link to="/count">Count</Link>
|
||||
<Link to="/tests">Tests</Link>
|
||||
<Link to="/promise">Promise</Link>
|
||||
<Link to="/query/usequery">Query</Link>
|
||||
<Link to="/blank">Blank</Link>
|
||||
</Flex>
|
||||
</Container>
|
||||
|
||||
35
packages/example/src/routes/query/service.tsx
Normal file
35
packages/example/src/routes/query/service.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { QueryContext } from "@/query/reffuse"
|
||||
import { Uuid4Query } from "@/query/services"
|
||||
import { Uuid4QueryService } from "@/query/views/Uuid4QueryService"
|
||||
import { R } from "@/reffuse"
|
||||
import { HttpClient } from "@effect/platform"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Console, Effect, Schema } from "effect"
|
||||
import { useMemo } from "react"
|
||||
|
||||
|
||||
export const Route = createFileRoute("/query/service")({
|
||||
component: RouteComponent
|
||||
})
|
||||
|
||||
function RouteComponent() {
|
||||
const query = R.useQuery({
|
||||
key: R.useStreamFromValues(["uuid4", 10 as number]),
|
||||
query: ([, count]) => Console.log(`Querying ${ count } IDs...`).pipe(
|
||||
Effect.andThen(Effect.sleep("500 millis")),
|
||||
Effect.andThen(HttpClient.get(`https://www.uuidtools.com/api/generate/v4/count/${ count }`)),
|
||||
HttpClient.withTracerPropagation(false),
|
||||
Effect.flatMap(res => res.json),
|
||||
Effect.flatMap(Schema.decodeUnknown(Uuid4Query.Result)),
|
||||
Effect.scoped,
|
||||
),
|
||||
})
|
||||
|
||||
const layer = useMemo(() => query.layer(Uuid4Query.Uuid4Query), [query])
|
||||
|
||||
return (
|
||||
<QueryContext.Provider layer={layer}>
|
||||
<Uuid4QueryService />
|
||||
</QueryContext.Provider>
|
||||
)
|
||||
}
|
||||
66
packages/example/src/routes/query/usequery.tsx
Normal file
66
packages/example/src/routes/query/usequery.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import { R } from "@/reffuse"
|
||||
import { HttpClient } from "@effect/platform"
|
||||
import { Button, Container, Flex, Slider, Text } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import * as AsyncData from "@typed/async-data"
|
||||
import { Array, Console, Effect, flow, Option, Schema } from "effect"
|
||||
import { useState } from "react"
|
||||
|
||||
|
||||
export const Route = createFileRoute("/query/usequery")({
|
||||
component: RouteComponent
|
||||
})
|
||||
|
||||
|
||||
const Result = Schema.Array(Schema.String)
|
||||
|
||||
function RouteComponent() {
|
||||
const runSync = R.useRunSync()
|
||||
|
||||
const [count, setCount] = useState(1)
|
||||
|
||||
const query = R.useQuery({
|
||||
key: R.useStreamFromValues(["uuid4", count]),
|
||||
query: ([, count]) => Console.log(`Querying ${ count } IDs...`).pipe(
|
||||
Effect.andThen(Effect.sleep("500 millis")),
|
||||
Effect.andThen(HttpClient.get(`https://www.uuidtools.com/api/generate/v4/count/${ count }`)),
|
||||
HttpClient.withTracerPropagation(false),
|
||||
Effect.flatMap(res => res.json),
|
||||
Effect.flatMap(Schema.decodeUnknown(Result)),
|
||||
Effect.scoped,
|
||||
),
|
||||
})
|
||||
|
||||
const [state] = R.useRefState(query.state)
|
||||
|
||||
|
||||
return (
|
||||
<Container>
|
||||
<Flex direction="column" align="center" gap="2">
|
||||
<Slider
|
||||
min={1}
|
||||
max={100}
|
||||
value={[count]}
|
||||
onValueChange={flow(
|
||||
Array.head,
|
||||
Option.getOrThrow,
|
||||
setCount,
|
||||
)}
|
||||
/>
|
||||
|
||||
<Text>
|
||||
{AsyncData.match(state, {
|
||||
NoData: () => "No data yet",
|
||||
Loading: () => "Loading...",
|
||||
Success: (value, { isRefreshing, isOptimistic }) =>
|
||||
`Value: ${value} ${isRefreshing ? "(refreshing)" : ""} ${isOptimistic ? "(optimistic)" : ""}`,
|
||||
Failure: (cause, { isRefreshing }) =>
|
||||
`Error: ${cause} ${isRefreshing ? "(refreshing)" : ""}`,
|
||||
})}
|
||||
</Text>
|
||||
|
||||
<Button onClick={() => runSync(query.refresh)}>Refresh</Button>
|
||||
</Flex>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { R } from "@/reffuse"
|
||||
import { Button } from "@radix-ui/themes"
|
||||
import { Button, Flex } from "@radix-ui/themes"
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { Console, Effect } from "effect"
|
||||
import { GetRandomValues, makeUuid4 } from "@typed/id"
|
||||
import { Console, Effect, Stream } from "effect"
|
||||
import { useState } from "react"
|
||||
|
||||
|
||||
export const Route = createFileRoute("/tests")({
|
||||
@@ -20,12 +22,25 @@ function RouteComponent() {
|
||||
Effect.delay("1 second"),
|
||||
), [])
|
||||
|
||||
const [reactValue, setReactValue] = useState("initial")
|
||||
const reactValueStream = R.useStreamFromValues([reactValue])
|
||||
R.useFork(() => Stream.runForEach(reactValueStream, Console.log), [reactValueStream])
|
||||
|
||||
|
||||
const logValue = R.useCallbackSync(Effect.fn(function*(value: string) {
|
||||
yield* Effect.log(value)
|
||||
}), [])
|
||||
|
||||
const generateUuid = R.useCallbackSync(() => makeUuid4.pipe(
|
||||
Effect.provide(GetRandomValues.CryptoRandom),
|
||||
Effect.map(setReactValue),
|
||||
), [])
|
||||
|
||||
|
||||
return (
|
||||
<Button onClick={() => logValue("test")}>Log value</Button>
|
||||
<Flex direction="row" justify="center" align="center" gap="2">
|
||||
<Button onClick={() => logValue("test")}>Log value</Button>
|
||||
<Button onClick={() => generateUuid()}>Generate UUID</Button>
|
||||
</Flex>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,6 @@ Extension to integrate `@typed/lazy-ref` with Reffuse.
|
||||
|
||||
## Peer dependencies
|
||||
- `@typed/lazy-ref`
|
||||
- `reffuse` 0.1.2+
|
||||
- `reffuse` 0.1.3+
|
||||
- `effect` 3.13+
|
||||
- `react` & `@types/react` 19+
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
"build": "tsc",
|
||||
"lint:tsc": "tsc --noEmit",
|
||||
"pack": "npm pack",
|
||||
"publish": "npm publish --access public",
|
||||
"clean:cache": "rm -f tsconfig.tsbuildinfo",
|
||||
"clean:dist": "rm -rf dist",
|
||||
"clean:node": "rm -rf node_modules"
|
||||
@@ -34,10 +33,10 @@
|
||||
"reffuse": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@typed/lazy-ref": "^0.3.3",
|
||||
"@typed/lazy-ref": "^0.3.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"effect": "^3.13.0",
|
||||
"react": "^19.0.0",
|
||||
"reffuse": "^0.1.2"
|
||||
"reffuse": "^0.1.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,19 +9,17 @@ export const LazyRefExtension = ReffuseExtension.make(() => ({
|
||||
this: ReffuseHelpers.ReffuseHelpers<R>,
|
||||
ref: LazyRef.LazyRef<A, E, R>,
|
||||
): [A, React.Dispatch<React.SetStateAction<A>>] {
|
||||
const runSync = this.useRunSync()
|
||||
|
||||
const initialState = React.useMemo(() => runSync(ref), [])
|
||||
const initialState = this.useMemo(() => ref, [], { doNotReExecuteOnRuntimeOrContextChange: true })
|
||||
const [reactStateValue, setReactStateValue] = React.useState(initialState)
|
||||
|
||||
this.useFork(() => Stream.runForEach(ref.changes, v => Effect.sync(() =>
|
||||
setReactStateValue(v)
|
||||
)), [ref])
|
||||
|
||||
const setValue = React.useCallback((setStateAction: React.SetStateAction<A>) =>
|
||||
runSync(LazyRef.update(ref, prevState =>
|
||||
const setValue = this.useCallbackSync((setStateAction: React.SetStateAction<A>) =>
|
||||
LazyRef.update(ref, prevState =>
|
||||
SetStateAction.value(setStateAction, prevState)
|
||||
)),
|
||||
),
|
||||
[ref])
|
||||
|
||||
return [reactStateValue, setValue]
|
||||
|
||||
10
packages/extension-query/README.md
Normal file
10
packages/extension-query/README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# Reffuse Query
|
||||
|
||||
TanStack Query style hooks for Reffuse.
|
||||
|
||||
## Peer dependencies
|
||||
- `reffuse` 0.1.3+
|
||||
- `effect` 3.13+
|
||||
- `@effect/platform` & `@effect/platform-browser`
|
||||
- `react` & `@types/react` 19+
|
||||
- `@typed/async-data`
|
||||
44
packages/extension-query/package.json
Normal file
44
packages/extension-query/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@reffuse/extension-query",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"./README.md",
|
||||
"./dist"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"url": "git+https://github.com/Thiladev/reffuse.git"
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./*": {
|
||||
"types": "./dist/*.d.ts",
|
||||
"default": "./dist/*.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"lint:tsc": "tsc --noEmit",
|
||||
"pack": "npm pack",
|
||||
"clean:cache": "rm -f tsconfig.tsbuildinfo",
|
||||
"clean:dist": "rm -rf dist",
|
||||
"clean:node": "rm -rf node_modules"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reffuse": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@effect/platform": "^0.77.0",
|
||||
"@effect/platform-browser": "^0.56.0",
|
||||
"@typed/async-data": "^0.13.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"effect": "^3.13.0",
|
||||
"react": "^19.0.0",
|
||||
"reffuse": "^0.1.3"
|
||||
}
|
||||
}
|
||||
55
packages/extension-query/src/QueryExtension.ts
Normal file
55
packages/extension-query/src/QueryExtension.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type * as AsyncData from "@typed/async-data"
|
||||
import { type Cause, type Context, Effect, type Fiber, Layer, type Option, type Stream, type SubscriptionRef } from "effect"
|
||||
import * as React from "react"
|
||||
import { ReffuseExtension, type ReffuseHelpers } from "reffuse"
|
||||
import * as QueryRunner from "./QueryRunner.js"
|
||||
import type * as QueryService from "./QueryService.js"
|
||||
|
||||
|
||||
export interface UseQueryProps<K extends readonly unknown[], A, E, R> {
|
||||
readonly key: Stream.Stream<K>
|
||||
readonly query: (key: K) => Effect.Effect<A, E, R>
|
||||
readonly refreshOnWindowFocus?: boolean
|
||||
}
|
||||
|
||||
export interface UseQueryResult<K extends readonly unknown[], A, E> {
|
||||
readonly latestKey: SubscriptionRef.SubscriptionRef<Option.Option<K>>
|
||||
readonly state: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<A, E>>
|
||||
readonly refresh: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
|
||||
|
||||
readonly layer: <Self, Id extends string>(
|
||||
tag: Context.TagClass<Self, Id, QueryService.QueryService<K, A, E>>
|
||||
) => Layer.Layer<Self>
|
||||
}
|
||||
|
||||
|
||||
export const QueryExtension = ReffuseExtension.make(() => ({
|
||||
useQuery<K extends readonly unknown[], A, E, R>(
|
||||
this: ReffuseHelpers.ReffuseHelpers<R>,
|
||||
props: UseQueryProps<K, A, E, R>,
|
||||
): UseQueryResult<K, A, E> {
|
||||
const runner = this.useMemo(() => QueryRunner.make({
|
||||
key: props.key,
|
||||
query: props.query,
|
||||
}), [props.key])
|
||||
|
||||
this.useFork(() => runner.fetchOnKeyChange, [runner])
|
||||
|
||||
this.useFork(() => (props.refreshOnWindowFocus ?? true)
|
||||
? runner.refreshOnWindowFocus
|
||||
: Effect.void,
|
||||
[props.refreshOnWindowFocus, runner])
|
||||
|
||||
return React.useMemo(() => ({
|
||||
latestKey: runner.latestKeyRef,
|
||||
state: runner.stateRef,
|
||||
refresh: runner.forkRefresh,
|
||||
|
||||
layer: tag => Layer.succeed(tag, {
|
||||
latestKey: runner.latestKeyRef,
|
||||
state: runner.stateRef,
|
||||
refresh: runner.forkRefresh,
|
||||
}),
|
||||
}), [runner])
|
||||
}
|
||||
}))
|
||||
144
packages/extension-query/src/QueryRunner.ts
Normal file
144
packages/extension-query/src/QueryRunner.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { BrowserStream } from "@effect/platform-browser"
|
||||
import * as AsyncData from "@typed/async-data"
|
||||
import { type Cause, Effect, Fiber, identity, Option, Ref, type Scope, Stream, SubscriptionRef } from "effect"
|
||||
|
||||
|
||||
export interface QueryRunner<K extends readonly unknown[], A, E, R> {
|
||||
readonly query: (key: K) => Effect.Effect<A, E, R>
|
||||
|
||||
readonly latestKeyRef: SubscriptionRef.SubscriptionRef<Option.Option<K>>
|
||||
readonly stateRef: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<A, E>>
|
||||
readonly fiberRef: SubscriptionRef.SubscriptionRef<Option.Option<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>>
|
||||
|
||||
readonly forkInterrupt: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
|
||||
readonly forkFetch: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
|
||||
readonly forkRefresh: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
|
||||
|
||||
readonly fetchOnKeyChange: Effect.Effect<void, Cause.NoSuchElementException, Scope.Scope>
|
||||
readonly refreshOnWindowFocus: Effect.Effect<void>
|
||||
}
|
||||
|
||||
|
||||
export interface MakeProps<K extends readonly unknown[], A, E, R> {
|
||||
readonly key: Stream.Stream<K>
|
||||
readonly query: (key: K) => Effect.Effect<A, E, R>
|
||||
}
|
||||
|
||||
export const make = <K extends readonly unknown[], A, E, R>(
|
||||
{ key, query }: MakeProps<K, A, E, R>
|
||||
): Effect.Effect<QueryRunner<K, A, E, R>, never, R> => Effect.gen(function*() {
|
||||
const context = yield* Effect.context<R>()
|
||||
|
||||
const latestKeyRef = yield* SubscriptionRef.make(Option.none<K>())
|
||||
const stateRef = yield* SubscriptionRef.make(AsyncData.noData<A, E>())
|
||||
const fiberRef = yield* SubscriptionRef.make(Option.none<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>())
|
||||
|
||||
const interrupt = fiberRef.pipe(
|
||||
Effect.flatMap(Option.match({
|
||||
onSome: fiber => Ref.set(fiberRef, Option.none()).pipe(
|
||||
Effect.andThen(Fiber.interrupt(fiber))
|
||||
),
|
||||
onNone: () => Effect.void,
|
||||
}))
|
||||
)
|
||||
|
||||
const forkInterrupt = fiberRef.pipe(
|
||||
Effect.flatMap(Option.match({
|
||||
onSome: fiber => Ref.set(fiberRef, Option.none()).pipe(
|
||||
Effect.andThen(Fiber.interrupt(fiber).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.forkDaemon,
|
||||
))
|
||||
),
|
||||
onNone: () => Effect.forkDaemon(Effect.void),
|
||||
}))
|
||||
)
|
||||
|
||||
const forkFetch = interrupt.pipe(
|
||||
Effect.andThen(
|
||||
Ref.set(stateRef, AsyncData.loading()).pipe(
|
||||
Effect.andThen(latestKeyRef),
|
||||
Effect.flatMap(identity),
|
||||
Effect.flatMap(key => query(key).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onSuccess: v => Ref.set(stateRef, AsyncData.success(v)),
|
||||
onFailure: c => Ref.set(stateRef, AsyncData.failure(c)),
|
||||
})
|
||||
)),
|
||||
|
||||
Effect.provide(context),
|
||||
Effect.fork,
|
||||
)
|
||||
),
|
||||
|
||||
Effect.flatMap(fiber =>
|
||||
Ref.set(fiberRef, Option.some(fiber)).pipe(
|
||||
Effect.andThen(Fiber.join(fiber)),
|
||||
Effect.andThen(Ref.set(fiberRef, Option.none())),
|
||||
)
|
||||
),
|
||||
|
||||
Effect.forkDaemon,
|
||||
)
|
||||
|
||||
const forkRefresh = interrupt.pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(stateRef, previous => {
|
||||
if (AsyncData.isSuccess(previous) || AsyncData.isFailure(previous))
|
||||
return AsyncData.refreshing(previous)
|
||||
if (AsyncData.isRefreshing(previous))
|
||||
return AsyncData.refreshing(previous.previous)
|
||||
return AsyncData.loading()
|
||||
}).pipe(
|
||||
Effect.andThen(latestKeyRef),
|
||||
Effect.flatMap(identity),
|
||||
Effect.flatMap(key => query(key).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onSuccess: v => Ref.set(stateRef, AsyncData.success(v)),
|
||||
onFailure: c => Ref.set(stateRef, AsyncData.failure(c)),
|
||||
})
|
||||
)),
|
||||
|
||||
Effect.provide(context),
|
||||
Effect.fork,
|
||||
)
|
||||
),
|
||||
|
||||
Effect.flatMap(fiber =>
|
||||
Ref.set(fiberRef, Option.some(fiber)).pipe(
|
||||
Effect.andThen(Fiber.join(fiber)),
|
||||
Effect.andThen(Ref.set(fiberRef, Option.none())),
|
||||
)
|
||||
),
|
||||
|
||||
Effect.forkDaemon,
|
||||
)
|
||||
|
||||
const fetchOnKeyChange = Effect.addFinalizer(() => interrupt).pipe(
|
||||
Effect.andThen(Stream.runForEach(key, latestKey =>
|
||||
Ref.set(latestKeyRef, Option.some(latestKey)).pipe(
|
||||
Effect.andThen(forkFetch)
|
||||
)
|
||||
))
|
||||
)
|
||||
|
||||
const refreshOnWindowFocus = Stream.runForEach(
|
||||
BrowserStream.fromEventListenerWindow("focus"),
|
||||
() => forkRefresh,
|
||||
)
|
||||
|
||||
return {
|
||||
query,
|
||||
|
||||
latestKeyRef,
|
||||
stateRef,
|
||||
fiberRef,
|
||||
|
||||
forkInterrupt,
|
||||
forkFetch,
|
||||
forkRefresh,
|
||||
|
||||
fetchOnKeyChange,
|
||||
refreshOnWindowFocus,
|
||||
}
|
||||
})
|
||||
32
packages/extension-query/src/QueryService.ts
Normal file
32
packages/extension-query/src/QueryService.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type * as AsyncData from "@typed/async-data"
|
||||
import { type Cause, Effect, type Fiber, type Option, type SubscriptionRef } from "effect"
|
||||
|
||||
|
||||
export interface QueryService<K extends readonly unknown[], A, E> {
|
||||
readonly latestKey: SubscriptionRef.SubscriptionRef<Option.Option<K>>
|
||||
readonly state: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<A, E>>
|
||||
readonly refresh: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
|
||||
}
|
||||
|
||||
export const Tag = <const Id extends string>(id: Id) => <
|
||||
Self, K extends readonly unknown[], A, E = never,
|
||||
>() => Effect.Tag(id)<Self, QueryService<K, A, E>>()
|
||||
|
||||
|
||||
// export interface LayerProps<A, E, R> {
|
||||
// readonly query: Effect.Effect<A, E, R>
|
||||
// }
|
||||
|
||||
// export const layer = <Self, Id extends string, A, E, R>(
|
||||
// tag: Context.TagClass<Self, Id, QueryService<A, E>>,
|
||||
// props: LayerProps<A, E, R>,
|
||||
// ): Layer.Layer<Self, never, R> => Layer.effect(tag, Effect.gen(function*() {
|
||||
// const runner = yield* QueryRunner.make({
|
||||
// query: props.query
|
||||
// })
|
||||
|
||||
// return {
|
||||
// state: runner.stateRef,
|
||||
// refresh: runner.forkRefresh,
|
||||
// }
|
||||
// }))
|
||||
3
packages/extension-query/src/index.ts
Normal file
3
packages/extension-query/src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./QueryExtension.js"
|
||||
export * as QueryRunner from "./QueryRunner.js"
|
||||
export * as QueryService from "./QueryService.js"
|
||||
33
packages/extension-query/tsconfig.json
Normal file
33
packages/extension-query/tsconfig.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
// Enable latest features
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
// "allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "NodeNext",
|
||||
// "allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
// "noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false,
|
||||
|
||||
// Build
|
||||
"outDir": "./dist",
|
||||
"declaration": true
|
||||
},
|
||||
|
||||
"include": ["./src"]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "reffuse",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"./README.md",
|
||||
@@ -25,7 +25,6 @@
|
||||
"build": "tsc",
|
||||
"lint:tsc": "tsc --noEmit",
|
||||
"pack": "npm pack",
|
||||
"publish": "npm publish --access public",
|
||||
"clean:cache": "rm -f tsconfig.tsbuildinfo",
|
||||
"clean:dist": "rm -rf dist",
|
||||
"clean:node": "rm -rf node_modules"
|
||||
|
||||
@@ -97,15 +97,15 @@ export function useMergeAll<T extends Array<unknown>>(
|
||||
return React.useMemo(() => Context.mergeAll(...values), values)
|
||||
}
|
||||
|
||||
export function useMergeAllLayers<T extends Array.NonEmptyArray<unknown>>(
|
||||
export function useMergeAllLayers<T extends Array<unknown>>(
|
||||
...contexts: [...{ [K in keyof T]: ReffuseContext<T[K]> }]
|
||||
): Layer.Layer<T[number]> {
|
||||
const values = Array.map(
|
||||
contexts as Array.NonEmptyArray<ReffuseContext<T[number]>>,
|
||||
v => React.use(v.Context),
|
||||
)
|
||||
const values = contexts.map(v => React.use(v.Context))
|
||||
|
||||
return React.useMemo(() => Layer.mergeAll(
|
||||
...Array.map(values, context => Layer.effectContext(Effect.succeed(context)))
|
||||
), values)
|
||||
return React.useMemo(() => Array.isNonEmptyArray(values)
|
||||
? Layer.mergeAll(
|
||||
...Array.map(values, context => Layer.effectContext(Effect.succeed(context)))
|
||||
)
|
||||
: Layer.empty as Layer.Layer<T[number]>,
|
||||
values)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Context, Effect, ExecutionStrategy, Exit, type Fiber, Pipeable, Ref, Runtime, Scope, Stream, SubscriptionRef } from "effect"
|
||||
import { type Context, Effect, ExecutionStrategy, Exit, type Fiber, type Layer, Pipeable, Queue, Ref, Runtime, Scope, Stream, SubscriptionRef } from "effect"
|
||||
import * as React from "react"
|
||||
import * as ReffuseContext from "./ReffuseContext.js"
|
||||
import * as ReffuseRuntime from "./ReffuseRuntime.js"
|
||||
@@ -23,6 +23,10 @@ export abstract class ReffuseHelpers<R> {
|
||||
return ReffuseContext.useMergeAll(...this.constructor.contexts)
|
||||
}
|
||||
|
||||
useLayer<R>(this: ReffuseHelpers<R>): Layer.Layer<R> {
|
||||
return ReffuseContext.useMergeAllLayers(...this.constructor.contexts)
|
||||
}
|
||||
|
||||
|
||||
useRunSync<R>(this: ReffuseHelpers<R>): <A, E>(effect: Effect.Effect<A, E, R>) => A {
|
||||
const runtime = ReffuseRuntime.useRuntime()
|
||||
@@ -388,23 +392,34 @@ export abstract class ReffuseHelpers<R> {
|
||||
this: ReffuseHelpers<R>,
|
||||
ref: SubscriptionRef.SubscriptionRef<A>,
|
||||
): [A, React.Dispatch<React.SetStateAction<A>>] {
|
||||
const runSync = this.useRunSync()
|
||||
|
||||
const initialState = React.useMemo(() => runSync(ref), [])
|
||||
const initialState = this.useMemo(() => ref, [], { doNotReExecuteOnRuntimeOrContextChange: true })
|
||||
const [reactStateValue, setReactStateValue] = React.useState(initialState)
|
||||
|
||||
this.useFork(() => Stream.runForEach(ref.changes, v => Effect.sync(() =>
|
||||
setReactStateValue(v)
|
||||
)), [ref])
|
||||
|
||||
const setValue = React.useCallback((setStateAction: React.SetStateAction<A>) =>
|
||||
runSync(Ref.update(ref, prevState =>
|
||||
const setValue = this.useCallbackSync((setStateAction: React.SetStateAction<A>) =>
|
||||
Ref.update(ref, prevState =>
|
||||
SetStateAction.value(setStateAction, prevState)
|
||||
)),
|
||||
),
|
||||
[ref])
|
||||
|
||||
return [reactStateValue, setValue]
|
||||
}
|
||||
|
||||
useStreamFromValues<const A extends React.DependencyList, R>(
|
||||
this: ReffuseHelpers<R>,
|
||||
values: A,
|
||||
): Stream.Stream<A> {
|
||||
const [queue, stream] = this.useMemo(() => Queue.unbounded<A>().pipe(
|
||||
Effect.map(queue => [queue, Stream.fromQueue(queue)] as const)
|
||||
), [])
|
||||
|
||||
this.useEffect(() => Queue.offer(queue, values), values)
|
||||
|
||||
return stream
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user