Release 0.5.0: untraced Component.make by default, cheaper remount check (#84)
## Summary Releases **effect-view 0.5.0** and **@effect-view/vite-plugin 0.5.0**. Both changes cut the per-render cost of effect-view components. ### Breaking: `Component.make` is untraced, `makeTraced` added, `makeUntraced` removed A component body runs on every render. With `Effect.fn`, every render of every component created a span and pushed a stack frame, even with no tracer exporting them. - `Component.make` now behaves like the former `makeUntraced`: the name only sets `displayName`. - `Component.makeTraced` behaves like the former `make` (same overloads as `Effect.fn`, span options included). It is mostly useful for `Async` components, where the span measures how long the body waits. - `Component.makeUntraced` is removed. Migration: replace `makeUntraced` with `make`, and `make` with `makeTraced` where the span is wanted. ### Cheaper remount check in `.use` A component used with `.use` is built again (and remounted) when a service outside its `nonReactiveTags` changes. The check used to copy the context with `Context.omit`, copy its services into an array and compare them with a new `Equivalence.Array` on every render. It now compares the services in one pass with no copy, in a `useReactiveServicesChanged` hook. Same behavior. ### Numbers Framework overhead per component render (running a minimal body plus the check), micro-benchmark outside React: | Services | Before (V8 / JSC) | After (V8 / JSC) | |---|---|---| | 10 | 6.6 / 4.1 µs | 2.1 / 1.5 µs | | 40 | 12.5 / 5.6 µs | 5.0 / 2.9 µs | | 150 | 28.5 / 11.2 µs | 12.7 / 6.9 µs | What's left grows with the number of services: reading `context.mapUnsafe` flattens a copy of the context, and that can't be avoided through the public API. ### vite-plugin - Recognizes `Component.make` and `Component.makeTraced`, and no longer `makeUntraced`. - Version `0.4.0` → `0.5.0`, peer dependency `effect-view` `^0.4.0` → `^0.5.0` (on 0.x a caret range only allows the same minor version). `bun.lock` updated to match. ### Docs `getting-started.md`, `ai-docs/Component.md` and the plugin README describe `make` as untraced and `makeTraced` as the traced variant. CHANGELOG has the 0.5.0 entry. --------- Co-authored-by: Julien Valverdé <julien.valverde@mailo.com> Reviewed-on: #84
This commit was merged in pull request #84.
This commit is contained in:
1 parent
ccd96f18d5
commit
5a65a67260
17 files changed
+215
-145
No files matched your search
@@ -138,7 +138,7 @@
|
||||
"vitest": "^3.2.4",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"effect-view": "^0.4.0",
|
||||
"effect-view": "^0.5.0",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -123,8 +123,8 @@ boundary above `ReactRuntime.Provider` as well.
|
||||
## Write your first component
|
||||
|
||||
`Component.make` defines a component body using the same generator style as
|
||||
`Effect.gen` and `Effect.fn`. Providing a name creates a tracing span and also
|
||||
sets the React DevTools display name:
|
||||
`Effect.gen` and `Effect.fn`. Providing a name sets the React DevTools display
|
||||
name:
|
||||
|
||||
```tsx title="src/HelloView.tsx"
|
||||
import { Effect } from "effect"
|
||||
@@ -139,8 +139,9 @@ export const HelloView = Component.make("HelloView")(
|
||||
)
|
||||
```
|
||||
|
||||
Use `Component.makeUntraced("HelloView")` when you want the display name but do
|
||||
not want an automatic tracing span.
|
||||
Use `Component.makeTraced("HelloView")` to also wrap the body in a tracing span,
|
||||
created on every render. It is mostly useful for async components, where the
|
||||
span measures how long the body waits.
|
||||
|
||||
`HelloView` is an Effect View component description, not yet a normal React
|
||||
component. Convert it at the point where plain React, a router, or a third-party
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
# effect-view
|
||||
|
||||
## 0.5.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [`8d419cc`](https://git.valverde.cloud/Thilawyn/effect-view/commit/8d419cc80ca796e17dce66e199506c369d48bacd) - **Breaking:** `Component.make` no longer wraps the body in a tracing span, `Component.makeUntraced` is removed, and `Component.makeTraced` is added.
|
||||
|
||||
A component body runs on every render, so a span per render (and the stack frame pushed with it) cost a few microseconds per component per render, even with no tracer exporting it. `make` now behaves like the former `makeUntraced`: a name only sets the `displayName`. `makeTraced` behaves like the former `make`, with the same overloads as `Effect.fn` and its span options. It is mostly useful for `Async` components, where the span measures how long the body waits.
|
||||
|
||||
```ts
|
||||
// Before
|
||||
Component.make("PostView")(body) // traced
|
||||
Component.makeUntraced("PostView")(body) // untraced
|
||||
|
||||
// After
|
||||
Component.makeTraced("PostView")(body) // traced
|
||||
Component.make("PostView")(body) // untraced
|
||||
```
|
||||
|
||||
Replace `makeUntraced` with `make`, and `make` with `makeTraced` where the span is wanted.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [`8d419cc`](https://git.valverde.cloud/Thilawyn/effect-view/commit/8d419cc80ca796e17dce66e199506c369d48bacd) - Make the check that decides whether a component used with `.use` must be mounted again (a service outside its `nonReactiveTags` changed) cheaper. It now compares the services in one pass, without copying the context or allocating on every render.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -14,8 +14,8 @@ export const HelloView = Component.make("HelloView")(function* (props: { readonl
|
||||
})
|
||||
```
|
||||
|
||||
- `Component.make(spanName?)(generatorBody, ...pipeArgs)` — same overloads as `Effect.fn`/`Effect.gen`: a generator body, or a body plus `(_, props) => next` pipeline steps. Passing a `spanName` wraps the body in a tracing span and sets `displayName`.
|
||||
- `Component.makeUntraced` is identical but skips the automatic span (still sets `displayName` from the name argument).
|
||||
- `Component.make(name?)(generatorBody, ...pipeArgs)` — same overloads as `Effect.fnUntraced`/`Effect.gen`: a generator body, or a body plus `(_, props) => next` pipeline steps. Passing a `name` sets `displayName`. The body is not traced.
|
||||
- `Component.makeTraced(spanName?, spanOptions?)` is identical but wraps the body in a tracing span (same overloads as `Effect.fn`), created on every render. Use it where the duration means something, such as an `Async` component.
|
||||
- The component's props type, return type, error channel, and required services (`R`) are all inferred from the generator body.
|
||||
|
||||
## Cross into React
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "effect-view",
|
||||
"description": "Write React function components with Effect",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"./README.md",
|
||||
|
||||
@@ -39,7 +39,7 @@ const PlainItem = () => React.createElement(
|
||||
React.createElement(PlainInner, { promise: Promise.resolve(<i />) }),
|
||||
)
|
||||
|
||||
const EffectItem = Component.makeUntraced("AsyncEffectItem")(function*() {
|
||||
const EffectItem = Component.make("AsyncEffectItem")(function*() {
|
||||
yield* Effect.void
|
||||
return <i />
|
||||
}).pipe(
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("Component", () => {
|
||||
}))
|
||||
const runtime = ReactRuntime.make(Layer.succeed(ParentService, { prefix: "provided" }))
|
||||
|
||||
const Probe = Component.makeUntraced("ProvidedServiceProbe")(function*() {
|
||||
const Probe = Component.make("ProvidedServiceProbe")(function*() {
|
||||
const service = yield* ValueService
|
||||
return <div>{service.value}</div>
|
||||
}).pipe(
|
||||
@@ -69,7 +69,7 @@ describe("Component", () => {
|
||||
const onMount = vi.fn(() => Effect.succeed("mounted"))
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const Probe = Component.makeUntraced("UseOnMountProbe")(function*() {
|
||||
const Probe = Component.make("UseOnMountProbe")(function*() {
|
||||
const value = yield* Component.useOnMount(onMount)
|
||||
return <div>{value}</div>
|
||||
}).pipe(
|
||||
@@ -100,7 +100,7 @@ describe("Component", () => {
|
||||
const onChange = vi.fn((value: number) => Effect.succeed(`value:${value}`))
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const Probe = Component.makeUntraced("UseOnChangeProbe")(function*(props: { readonly value: number }) {
|
||||
const Probe = Component.make("UseOnChangeProbe")(function*(props: { readonly value: number }) {
|
||||
const result = yield* Component.useOnChange(() => onChange(props.value), [props.value], {
|
||||
finalizerExecutionDebounce: 0,
|
||||
})
|
||||
@@ -144,7 +144,7 @@ describe("Component", () => {
|
||||
const cleanup = vi.fn()
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const Probe = Component.makeUntraced("ScopeCleanupProbe")(function*(props: { readonly value: string }) {
|
||||
const Probe = Component.make("ScopeCleanupProbe")(function*(props: { readonly value: string }) {
|
||||
const result = yield* Component.useOnChange(
|
||||
() => Effect.gen(function*() {
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
|
||||
@@ -188,7 +188,7 @@ describe("Component", () => {
|
||||
const lifecycle = vi.fn<(message: string) => void>()
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const Probe = Component.makeUntraced("UseReactEffectProbe")(function*(props: { readonly value: string }) {
|
||||
const Probe = Component.make("UseReactEffectProbe")(function*(props: { readonly value: string }) {
|
||||
yield* Component.useReactEffect(() =>
|
||||
Effect.gen(function*() {
|
||||
yield* Effect.sync(() => lifecycle(`mount:${props.value}`))
|
||||
@@ -237,7 +237,7 @@ describe("Component", () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
const seenCallbacks: Array<(value: number) => string> = []
|
||||
|
||||
const Probe = Component.makeUntraced("UseCallbackSyncProbe")(function*(props: { readonly prefix: string }) {
|
||||
const Probe = Component.make("UseCallbackSyncProbe")(function*(props: { readonly prefix: string }) {
|
||||
const callback = yield* Component.useCallbackSync(
|
||||
(value: number) => Effect.succeed(`${props.prefix}:${value}`),
|
||||
[props.prefix],
|
||||
@@ -294,7 +294,7 @@ describe("Component", () => {
|
||||
const cleanup = vi.fn()
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const Probe = Component.makeUntraced("DebouncedCleanupProbe")(function*(props: { readonly value: string }) {
|
||||
const Probe = Component.make("DebouncedCleanupProbe")(function*(props: { readonly value: string }) {
|
||||
const result = yield* Component.useOnChange(
|
||||
() => Effect.gen(function*() {
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => cleanup(props.value)))
|
||||
@@ -348,7 +348,7 @@ describe("Component", () => {
|
||||
const unmounts = vi.fn()
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const SubComponent = Component.makeUntraced("NonReactiveSubComponent")(function*() {
|
||||
const SubComponent = Component.make("NonReactiveSubComponent")(function*() {
|
||||
const service = yield* ValueService
|
||||
const [count, setCount] = React.useState(0)
|
||||
|
||||
@@ -364,7 +364,7 @@ describe("Component", () => {
|
||||
})
|
||||
)
|
||||
|
||||
const Parent = Component.makeUntraced("NonReactiveParent")(function*(props: { readonly value: string }) {
|
||||
const Parent = Component.make("NonReactiveParent")(function*(props: { readonly value: string }) {
|
||||
const serviceLayer = React.useMemo(
|
||||
() => Layer.succeed(ValueService, { value: props.value }),
|
||||
[props.value],
|
||||
@@ -415,7 +415,7 @@ describe("Component", () => {
|
||||
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
|
||||
const pending = new Promise<void>(() => {})
|
||||
|
||||
const Probe = Component.makeUntraced("DiscardedSuspenseProbe")(function*() {
|
||||
const Probe = Component.make("DiscardedSuspenseProbe")(function*() {
|
||||
yield* Component.useReactEffect(() => Effect.sync(setup), [])
|
||||
React.use(pending)
|
||||
return <div>committed</div>
|
||||
@@ -454,7 +454,7 @@ describe("Component", () => {
|
||||
const effectRuntime = await managed.context()
|
||||
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
|
||||
|
||||
const Probe = Component.makeUntraced("CommittedScopeProbe")(function*() {
|
||||
const Probe = Component.make("CommittedScopeProbe")(function*() {
|
||||
yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
yield* Effect.sync(acquisitions)
|
||||
yield* Effect.addFinalizer(() => Effect.sync(releases))
|
||||
@@ -534,7 +534,7 @@ describe("Component", () => {
|
||||
resolve = complete
|
||||
})
|
||||
|
||||
const Probe = Component.makeUntraced("RetriedSuspenseProbe")(function*() {
|
||||
const Probe = Component.make("RetriedSuspenseProbe")(function*() {
|
||||
React.use(pending)
|
||||
yield* Component.useReactEffect(() => Effect.gen(function*() {
|
||||
yield* Effect.sync(() => lifecycle("mount"))
|
||||
@@ -580,7 +580,7 @@ describe("Component", () => {
|
||||
it("refreshes a registered body while preserving or resetting local state", async () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const makeProbe = (label: string) => Component.makeUntraced("RefreshProbe")(function*() {
|
||||
const makeProbe = (label: string) => Component.make("RefreshProbe")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
return <button type="button" onClick={() => setCount(value => value + 1)}>{label}:{count}</button>
|
||||
})
|
||||
@@ -616,7 +616,7 @@ describe("Component", () => {
|
||||
it("refreshes a component derived from a registered descriptor, which keeps its own traits", async () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const makeBase = (label: string) => Component.makeUntraced("RefreshAsyncBase")(function*() {
|
||||
const makeBase = (label: string) => Component.make("RefreshAsyncBase")(function*() {
|
||||
yield* Effect.sleep("5 millis")
|
||||
return <div>{label}</div>
|
||||
})
|
||||
@@ -649,11 +649,11 @@ describe("Component", () => {
|
||||
it("refreshes a child used with .use, and remounts only the child when its hooks change", async () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
|
||||
const makeChild = (label: string) => Component.makeUntraced("RefreshChild")(function*() {
|
||||
const makeChild = (label: string) => Component.make("RefreshChild")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
return <button type="button" aria-label="child" onClick={() => setCount(value => value + 1)}>{label}:{count}</button>
|
||||
})
|
||||
const makeChildWithMoreHooks = (label: string) => Component.makeUntraced("RefreshChild")(function*() {
|
||||
const makeChildWithMoreHooks = (label: string) => Component.make("RefreshChild")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
const [suffix] = React.useState("!")
|
||||
return <button type="button" aria-label="child" onClick={() => setCount(value => value + 1)}>{label}:{count}{suffix}</button>
|
||||
@@ -662,7 +662,7 @@ describe("Component", () => {
|
||||
const cell = Refreshable.makeCell(child, "one hook", false)
|
||||
Refreshable.attach(child, cell)
|
||||
|
||||
const Parent = Component.makeUntraced("RefreshParent")(function*() {
|
||||
const Parent = Component.make("RefreshParent")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
const Child = yield* child.use
|
||||
|
||||
@@ -708,7 +708,7 @@ describe("Component", () => {
|
||||
const effectRuntime = await managed.context()
|
||||
const scopeRegistry = Context.get(effectRuntime, ScopeRegistry.ScopeRegistry)
|
||||
|
||||
const Probe = Component.makeUntraced("ActivityProbe")(function*() {
|
||||
const Probe = Component.make("ActivityProbe")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
const id = yield* Component.useOnMount(() => Effect.gen(function*() {
|
||||
const id = ++acquired
|
||||
@@ -790,7 +790,7 @@ describe("Component", () => {
|
||||
const managed = ManagedRuntime.make(ReactRuntime.preludeLayer)
|
||||
const effectRuntime = await managed.context()
|
||||
|
||||
const Probe = Component.makeUntraced("ActivityHookProbe")(function*() {
|
||||
const Probe = Component.make("ActivityHookProbe")(function*() {
|
||||
const [count, setCount] = React.useState(0)
|
||||
const id = yield* Component.useOnChange(
|
||||
() => Effect.gen(function*() {
|
||||
@@ -850,7 +850,7 @@ describe("Component", () => {
|
||||
return { value: `layer ${id}` }
|
||||
}))
|
||||
|
||||
const Probe = Component.makeUntraced("ActivityProvideProbe")(function*() {
|
||||
const Probe = Component.make("ActivityProvideProbe")(function*() {
|
||||
const service = yield* ValueService
|
||||
const [count, setCount] = React.useState(0)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** biome-ignore-all lint/complexity/noBannedTypes: {} is the default type for React props */
|
||||
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
|
||||
import { Context, type Duration, Effect, Equivalence, Exit, Function, identity, Layer, Option, Pipeable, Predicate, References, Scheduler, Scope, Tracer } from "effect"
|
||||
import { Context, type Duration, Effect, Exit, Function, identity, Layer, Option, Pipeable, Predicate, References, Scheduler, Scope, Tracer } from "effect"
|
||||
import * as React from "react"
|
||||
import * as Refreshable from "./Refreshable.js"
|
||||
import * as ScopeRegistry from "./ScopeRegistry.js"
|
||||
@@ -109,31 +109,30 @@ const useFunctionComponent = <P extends {}, A extends React.ReactNode, E, R, F e
|
||||
contextRef: React.RefObject<Context.Context<R>>,
|
||||
): F => {
|
||||
const componentRef = React.useRef<F | null>(null)
|
||||
const previousServicesRef = React.useRef<readonly any[] | null>(null)
|
||||
const previousRevisionRef = React.useRef<number | undefined>(undefined)
|
||||
|
||||
const services = Array.from(
|
||||
Context.omit(...self.nonReactiveTags)(contextRef.current).mapUnsafe.values()
|
||||
)
|
||||
const servicesChanged = useReactiveServicesChanged(contextRef.current, self.nonReactiveTags)
|
||||
|
||||
// Development only: a descriptor connected to a refresh cell. When the hooks of its body change, the function
|
||||
// component is built again, which makes React mount it again with fresh state.
|
||||
const cell = (self as Partial<Refreshable.Refreshable>)[Refreshable.RefreshableTypeId]
|
||||
if (cell) {
|
||||
const cell = Refreshable.isRefreshable(self)
|
||||
? self[Refreshable.RefreshableTypeId]
|
||||
: null
|
||||
const revision = cell
|
||||
// biome-ignore lint/correctness/useHookAtTopLevel: a descriptor either has a cell or not for its whole life
|
||||
services.push(React.useSyncExternalStore(
|
||||
? React.useSyncExternalStore(
|
||||
cell.subscribe,
|
||||
() => cell.getSnapshot().resetRevision,
|
||||
() => cell.getSnapshot().resetRevision,
|
||||
))
|
||||
}
|
||||
)
|
||||
: undefined
|
||||
|
||||
if (
|
||||
!componentRef.current ||
|
||||
!previousServicesRef.current ||
|
||||
services.length !== previousServicesRef.current.length ||
|
||||
!Equivalence.Array(Equivalence.strictEqual())(services, previousServicesRef.current)
|
||||
servicesChanged ||
|
||||
revision !== previousRevisionRef.current
|
||||
) {
|
||||
previousServicesRef.current = services
|
||||
previousRevisionRef.current = revision
|
||||
const f = self.asFunctionComponent(contextRef)
|
||||
self.setFunctionComponentName(f)
|
||||
componentRef.current = self.transformFunctionComponent(f)
|
||||
@@ -142,6 +141,51 @@ const useFunctionComponent = <P extends {}, A extends React.ReactNode, E, R, F e
|
||||
return componentRef.current
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a service of `context` outside `nonReactiveTags` changed since the last render where one did (always true on
|
||||
* the first render). Compares in one pass, without copying the services.
|
||||
*/
|
||||
const useReactiveServicesChanged = (
|
||||
context: Context.Context<any>,
|
||||
nonReactiveTags: readonly Context.Key<any, any>[],
|
||||
): boolean => {
|
||||
const previousRef = React.useRef<ReadonlyMap<string, unknown> | null>(null)
|
||||
const nonReactiveKeys = React.useMemo(() => new Set(nonReactiveTags.map(tag => tag.key)), [nonReactiveTags])
|
||||
|
||||
const services = context.mapUnsafe
|
||||
if (previousRef.current && reactiveServicesEqual(services, previousRef.current, nonReactiveKeys))
|
||||
return false
|
||||
|
||||
previousRef.current = services
|
||||
return true
|
||||
}
|
||||
|
||||
const reactiveServicesEqual = (
|
||||
self: ReadonlyMap<string, unknown>,
|
||||
that: ReadonlyMap<string, unknown>,
|
||||
nonReactiveKeys: ReadonlySet<string>,
|
||||
): boolean => {
|
||||
if (self === that)
|
||||
return true
|
||||
if (reactiveSize(self, nonReactiveKeys) !== reactiveSize(that, nonReactiveKeys))
|
||||
return false
|
||||
for (const [key, value] of self) {
|
||||
if (nonReactiveKeys.has(key))
|
||||
continue
|
||||
if (that.get(key) !== value || (value === undefined && !that.has(key)))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const reactiveSize = (services: ReadonlyMap<string, unknown>, nonReactiveKeys: ReadonlySet<string>): number => {
|
||||
let size = services.size
|
||||
for (const key of nonReactiveKeys)
|
||||
if (services.has(key))
|
||||
size--
|
||||
return size
|
||||
}
|
||||
|
||||
|
||||
export interface ComponentPrototype<R, F extends Component.Signature>
|
||||
extends Pipeable.Pipeable {
|
||||
@@ -440,19 +484,18 @@ export declare namespace make {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an Effect View Component using the same overloads and pipeline composition style as `Effect.fn`.
|
||||
* Creates an Effect View Component without automatic distributed tracing.
|
||||
*
|
||||
* This is the **recommended** approach for defining Effect View components. It provides comprehensive
|
||||
* support for multiple component definition patterns:
|
||||
* This function provides the same API surface as `makeTraced`, but does not create automatic tracing spans.
|
||||
* It follows the exact same overload structure as `Effect.fnUntraced`.
|
||||
*
|
||||
* - **Generator syntax** (yield* style): Most ergonomic and readable approach for sequential operations
|
||||
* - **Direct Effect return**: For simple components that return an Effect directly
|
||||
* - **Chained transformation functions**: Enables Effect.fn-style pipelines for composable transformations
|
||||
* - **Automatic tracing**: Optional tracing span creation with automatic `displayName` assignment
|
||||
* Use this variant when you need:
|
||||
* - Full manual control over tracing instrumentation
|
||||
* - To reduce tracing overhead in deeply nested component hierarchies
|
||||
* - To avoid span noise in performance-sensitive applications
|
||||
*
|
||||
* When a `spanName` string is provided, the following occurs automatically:
|
||||
* 1. A distributed tracing span is created with the specified name
|
||||
* 2. The resulting React component receives `displayName = spanName` for DevTools visibility
|
||||
* When a `spanName` string is provided, it is used **exclusively** as the React component's
|
||||
* `displayName` for DevTools identification. No tracing span is created.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
@@ -487,6 +530,73 @@ export declare namespace make {
|
||||
* ```
|
||||
*/
|
||||
export const make: (
|
||||
& make.Gen
|
||||
& make.NonGen
|
||||
& ((name: string) => make.Gen & make.NonGen)
|
||||
) = (nameOrBody: Function | string, ...pipeables: any[]): any => (
|
||||
typeof nameOrBody !== "string"
|
||||
? Object.setPrototypeOf(
|
||||
Object.assign(function() {}, defaultOptions, {
|
||||
body: Effect.fnUntraced(nameOrBody as any, ...pipeables as []),
|
||||
}),
|
||||
ComponentPrototype,
|
||||
)
|
||||
: (body: any, ...pipeables: any[]) => Object.setPrototypeOf(
|
||||
Object.assign(function() {}, defaultOptions, {
|
||||
body: Effect.fnUntraced(body, ...pipeables as []),
|
||||
displayName: nameOrBody,
|
||||
}),
|
||||
ComponentPrototype,
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates an Effect View Component using the same overloads and pipeline composition style as `Effect.fn`.
|
||||
*
|
||||
* It provides comprehensive support for multiple component definition patterns:
|
||||
*
|
||||
* - **Generator syntax** (yield* style): Most ergonomic and readable approach for sequential operations
|
||||
* - **Direct Effect return**: For simple components that return an Effect directly
|
||||
* - **Chained transformation functions**: Enables Effect.fn-style pipelines for composable transformations
|
||||
* - **Automatic tracing**: Optional tracing span creation with automatic `displayName` assignment
|
||||
*
|
||||
* When a `spanName` string is provided, the following occurs automatically:
|
||||
* 1. A distributed tracing span is created with the specified name
|
||||
* 2. The resulting React component receives `displayName = spanName` for DevTools visibility
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const MyComponent = Component.makeTraced("MyComponent")(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @example As an opaque type using class syntax
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeTraced("MyComponent")(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* }) {}
|
||||
* ```
|
||||
*
|
||||
* @example Without name
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeTraced(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* }) {}
|
||||
* ```
|
||||
*
|
||||
* @example Using pipeline
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeTraced("MyComponent")(
|
||||
* (props: { count: number }) => someEffect,
|
||||
* Effect.map(value => <div>{value}</div>),
|
||||
* ) {}
|
||||
* ```
|
||||
*/
|
||||
export const makeTraced: (
|
||||
& make.Gen
|
||||
& make.NonGen
|
||||
& ((
|
||||
@@ -514,73 +624,6 @@ export const make: (
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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`.
|
||||
*
|
||||
* Use this variant when you need:
|
||||
* - Full manual control over tracing instrumentation
|
||||
* - To reduce tracing overhead in deeply nested component hierarchies
|
||||
* - To avoid span noise in performance-sensitive applications
|
||||
*
|
||||
* When a `spanName` string is provided, it is used **exclusively** as the React component's
|
||||
* `displayName` for DevTools identification. No tracing span is created.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const MyComponent = Component.makeUntraced("MyComponent")(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @example As an opaque type using class syntax
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeUntraced("MyComponent")(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* }) {}
|
||||
* ```
|
||||
*
|
||||
* @example Without name
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeUntraced(function* (props: { count: number }) {
|
||||
* const value = yield* someEffect
|
||||
* return <div>{value}</div>
|
||||
* }) {}
|
||||
* ```
|
||||
*
|
||||
* @example Using pipeline
|
||||
* ```tsx
|
||||
* class MyComponent extends Component.makeUntraced("MyComponent")(
|
||||
* (props: { count: number }) => someEffect,
|
||||
* Effect.map(value => <div>{value}</div>),
|
||||
* ) {}
|
||||
* ```
|
||||
*/
|
||||
export const makeUntraced: (
|
||||
& make.Gen
|
||||
& make.NonGen
|
||||
& ((name: string) => make.Gen & make.NonGen)
|
||||
) = (spanNameOrBody: Function | string, ...pipeables: any[]): any => (
|
||||
typeof spanNameOrBody !== "string"
|
||||
? Object.setPrototypeOf(
|
||||
Object.assign(function() {}, defaultOptions, {
|
||||
body: Effect.fnUntraced(spanNameOrBody as any, ...pipeables as []),
|
||||
}),
|
||||
ComponentPrototype,
|
||||
)
|
||||
: (body: any, ...pipeables: any[]) => Object.setPrototypeOf(
|
||||
Object.assign(function() {}, defaultOptions, {
|
||||
body: Effect.fnUntraced(body, ...pipeables as []),
|
||||
displayName: spanNameOrBody,
|
||||
}),
|
||||
ComponentPrototype,
|
||||
)
|
||||
)
|
||||
|
||||
export declare namespace withSignature {
|
||||
export type Result<T extends Component.Any, F extends Component.Signature> = (
|
||||
& Omit<T, keyof Component.AsComponent<T>>
|
||||
|
||||
@@ -25,7 +25,7 @@ describe("Lens", () => {
|
||||
const ref = await Effect.runPromise(SubscriptionRef.make(0))
|
||||
const lens = Lens.fromSubscriptionRef(ref)
|
||||
|
||||
const Probe = Component.makeUntraced("LensUseStateProbe")(function*() {
|
||||
const Probe = Component.make("LensUseStateProbe")(function*() {
|
||||
const [value, setValue] = yield* Lens.useState(lens)
|
||||
|
||||
return (
|
||||
@@ -61,7 +61,7 @@ describe("Lens", () => {
|
||||
const ref = await Effect.runPromise(SubscriptionRef.make({ id: 1, label: "first" }))
|
||||
const lens = Lens.fromSubscriptionRef(ref)
|
||||
|
||||
const Probe = Component.makeUntraced("LensUseStateEquivalenceProbe")(function*() {
|
||||
const Probe = Component.make("LensUseStateEquivalenceProbe")(function*() {
|
||||
const [value] = yield* Lens.useState(lens, {
|
||||
equivalence: (self, that) => self.id === that.id,
|
||||
})
|
||||
@@ -93,7 +93,7 @@ describe("Lens", () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
let lens: Lens.Lens<string, never, never, never, never> | undefined
|
||||
|
||||
const Probe = Component.makeUntraced("LensUseFromReactStateProbe")(function*() {
|
||||
const Probe = Component.make("LensUseFromReactStateProbe")(function*() {
|
||||
const [value, setValue] = React.useState("hello")
|
||||
const reactLens = yield* Lens.useFromReactState([value, setValue])
|
||||
|
||||
@@ -126,7 +126,7 @@ describe("Lens", () => {
|
||||
const runtime = ReactRuntime.make(Layer.empty)
|
||||
let lens: Lens.Lens<{ readonly id: number; readonly label: string }, never, never, never, never> | undefined
|
||||
|
||||
const Probe = Component.makeUntraced("LensUseFromReactStateEquivalenceProbe")(function*() {
|
||||
const Probe = Component.make("LensUseFromReactStateEquivalenceProbe")(function*() {
|
||||
const [value, setValue] = React.useState({ id: 1, label: "first" })
|
||||
const reactLens = yield* Lens.useFromReactState([value, setValue], {
|
||||
equivalence: (self, that) => self.id === that.id,
|
||||
|
||||
@@ -19,7 +19,7 @@ describe("ReactRuntime", () => {
|
||||
return { value: "built" }
|
||||
})))
|
||||
|
||||
const Probe = Component.makeUntraced("Probe")(function*() {
|
||||
const Probe = Component.make("Probe")(function*() {
|
||||
return <div>{(yield* ValueService).value}</div>
|
||||
}).pipe(Component.withContext(runtime.context))
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("ReactRuntime.extend", () => {
|
||||
return { id: `${ root.name }:user` }
|
||||
})))
|
||||
|
||||
const Edit = Component.makeUntraced("Edit")(function*() {
|
||||
const Edit = Component.make("Edit")(function*() {
|
||||
const root = yield* RootService
|
||||
const user = yield* UserService
|
||||
return <div>{root.name} {user.id}</div>
|
||||
@@ -110,7 +110,7 @@ describe("ReactRuntime.extend", () => {
|
||||
const userCleanup = vi.fn()
|
||||
const { runtime, UserRuntime, Edit } = makeRuntimes({ rootSetup, userSetup, userCleanup })
|
||||
|
||||
const Layout = Component.makeUntraced("Layout")(function*(props: { readonly shown: boolean }) {
|
||||
const Layout = Component.make("Layout")(function*(props: { readonly shown: boolean }) {
|
||||
yield* RootService // the layout itself only needs the root context
|
||||
return props.shown
|
||||
? <ReactRuntime.Provider runtime={UserRuntime}><Edit /></ReactRuntime.Provider>
|
||||
@@ -143,7 +143,7 @@ describe("ReactRuntime.extend", () => {
|
||||
return { title: `draft of ${ (yield* UserService).id }` }
|
||||
})))
|
||||
|
||||
const Probe = Component.makeUntraced("Probe")(function*() {
|
||||
const Probe = Component.make("Probe")(function*() {
|
||||
return <div>{(yield* DraftService).title}</div>
|
||||
}).pipe(Component.withContext(DraftRuntime.context))
|
||||
|
||||
@@ -178,7 +178,7 @@ describe("ReactRuntime.extend", () => {
|
||||
|
||||
it("only accepts components and layers whose requirements are provided", () => {
|
||||
const { runtime, UserRuntime } = makeRuntimes()
|
||||
const NeedsUser = Component.makeUntraced(function*() { return <div>{(yield* UserService).id}</div> })
|
||||
const NeedsUser = Component.make(function*() { return <div>{(yield* UserService).id}</div> })
|
||||
|
||||
// @ts-expect-error UserService is not provided by the root context
|
||||
Component.withContext(NeedsUser, runtime.context)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Predicate } from "effect"
|
||||
import * as React from "react"
|
||||
import type * as Component from "./Component.js"
|
||||
|
||||
@@ -61,8 +62,8 @@ export interface Refreshable {
|
||||
* `Component.provide`, ...) is refreshable too: it runs the body of the cell.
|
||||
*/
|
||||
export const isRefreshable = <A extends object>(
|
||||
value: A,
|
||||
): value is A & Refreshable => Object.hasOwn(value, RefreshableTypeId)
|
||||
u: A,
|
||||
): u is A & Refreshable => Predicate.hasProperty(u, RefreshableTypeId)
|
||||
|
||||
/**
|
||||
* The body a descriptor was defined with, without the one that `attach` put in
|
||||
|
||||
@@ -62,7 +62,7 @@ afterAll(() => managed.dispose())
|
||||
|
||||
const PlainItem = () => <i />
|
||||
|
||||
const EffectItem = Component.makeUntraced("EffectItem")(function*() {
|
||||
const EffectItem = Component.make("EffectItem")(function*() {
|
||||
yield* Effect.void
|
||||
return <i />
|
||||
}).pipe(Component.withContext(runtime.context))
|
||||
@@ -110,12 +110,12 @@ describe.each([500, 2_000])("react, in batches: mount and unmount %d components"
|
||||
})
|
||||
|
||||
|
||||
const UsedItem = Component.makeUntraced("UsedItem")(function*() {
|
||||
const UsedItem = Component.make("UsedItem")(function*() {
|
||||
yield* Effect.void
|
||||
return <i />
|
||||
})
|
||||
|
||||
const EffectList = Component.makeUntraced("EffectList")(function*(props: { readonly count: number }) {
|
||||
const EffectList = Component.make("EffectList")(function*(props: { readonly count: number }) {
|
||||
const Item = yield* UsedItem.use
|
||||
return <div>{range(props.count).map(i => <Item key={i} />)}</div>
|
||||
}).pipe(Component.withContext(runtime.context))
|
||||
|
||||
@@ -21,7 +21,7 @@ describe("View", () => {
|
||||
const count = Lens.fromSubscriptionRef(countRef)
|
||||
const label = Lens.fromSubscriptionRef(labelRef)
|
||||
|
||||
const Probe = Component.makeUntraced("ViewUseAllProbe")(function*() {
|
||||
const Probe = Component.make("ViewUseAllProbe")(function*() {
|
||||
const [currentCount, currentLabel] = yield* View.useAll([count, label])
|
||||
|
||||
return <div>{`${currentCount}:${currentLabel}`}</div>
|
||||
@@ -53,7 +53,7 @@ describe("View", () => {
|
||||
const item = Lens.fromSubscriptionRef(itemRef)
|
||||
const flag = Lens.fromSubscriptionRef(flagRef)
|
||||
|
||||
const Probe = Component.makeUntraced("ViewUseAllEquivalenceProbe")(function*() {
|
||||
const Probe = Component.make("ViewUseAllEquivalenceProbe")(function*() {
|
||||
const [currentItem, currentFlag] = yield* View.useAll([item, flag], {
|
||||
equivalence: ([selfItem, selfFlag], [thatItem, thatFlag]) =>
|
||||
selfItem.id === thatItem.id && selfFlag === thatFlag,
|
||||
|
||||
@@ -15,7 +15,7 @@ export default defineConfig({
|
||||
})
|
||||
```
|
||||
|
||||
The plugin recognizes `Component.make` and `Component.makeUntraced`
|
||||
The plugin recognizes `Component.make` and `Component.makeTraced`
|
||||
definitions imported from `effect-view`. The legacy `effect-fc` package is
|
||||
not supported. `effect-view` owns the bundler-neutral refresh cell protocol;
|
||||
this package is the Vite adapter that retains those cells in HMR data. The
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@effect-view/vite-plugin",
|
||||
"description": "Vite Fast Refresh support for Effect View components",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"./README.md",
|
||||
@@ -41,7 +41,7 @@
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"effect-view": "^0.4.0",
|
||||
"effect-view": "^0.5.0",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ const defaultExclude = /\/node_modules\//
|
||||
const runtimeImport = "@effect-view/vite-plugin/runtime"
|
||||
const refreshIdentifier = "__effectViewRefresh"
|
||||
const acceptIdentifier = "__effectViewAccept"
|
||||
const factoryNames: ReadonlySet<string> = new Set(["make", "makeTraced"])
|
||||
|
||||
const isSupportedPackage = (source: string): boolean =>
|
||||
source === "effect-view"
|
||||
@@ -78,7 +79,7 @@ const collectImports = (
|
||||
|
||||
for (const element of clause.namedBindings.elements) {
|
||||
const importedName = element.propertyName?.text ?? element.name.text
|
||||
if (source.endsWith("/Component") && (importedName === "make" || importedName === "makeUntraced"))
|
||||
if (source.endsWith("/Component") && factoryNames.has(importedName))
|
||||
directFactories.add(element.name.text)
|
||||
else if (!source.endsWith("/Component") && importedName === "Component")
|
||||
componentNamespaces.add(element.name.text)
|
||||
@@ -102,7 +103,7 @@ const isFactoryCallee = (
|
||||
if (!ts.isPropertyAccessExpression(expression))
|
||||
return false
|
||||
|
||||
if (expression.name.text !== "make" && expression.name.text !== "makeUntraced")
|
||||
if (!factoryNames.has(expression.name.text))
|
||||
return false
|
||||
|
||||
if (ts.isIdentifier(expression.expression))
|
||||
|
||||
@@ -88,12 +88,12 @@ class PostView extends Component.make("PostView")(function*() {
|
||||
// @refresh reset
|
||||
import { Component as View } from "effect-view"
|
||||
|
||||
const Probe = View.makeUntraced(function*() {
|
||||
const Probe = View.makeTraced(function*() {
|
||||
return null
|
||||
})
|
||||
`)
|
||||
|
||||
expect(result).toContain("__effectViewRefresh(View.makeUntraced")
|
||||
expect(result).toContain("__effectViewRefresh(View.makeTraced")
|
||||
expect(result).toMatch(/"src\/View\.tsx:Probe", "[a-z0-9]+", true/)
|
||||
})
|
||||
|
||||
@@ -112,7 +112,7 @@ export function View() {
|
||||
|
||||
await runTransform(plugin, `
|
||||
import { Component } from "effect-view"
|
||||
export const Probe = Component.makeUntraced(function*() {
|
||||
export const Probe = Component.make(function*() {
|
||||
return null
|
||||
})
|
||||
`, id)
|
||||
@@ -128,7 +128,7 @@ export const value = 1
|
||||
it("ignores the legacy effect-fc package", async () => {
|
||||
expect(await transform(`
|
||||
import { Component } from "effect-fc"
|
||||
export const Legacy = Component.makeUntraced(function*() {
|
||||
export const Legacy = Component.make(function*() {
|
||||
return null
|
||||
})
|
||||
`)).toBeUndefined()
|
||||
|
||||
Reference in new issue
Block a user