@fridgedoor/storybook-effect-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Initial release of the Storybook 11 framework for Effect UI. Use the Vite
6
+ builder to render HTML and headless components with schema-derived Controls,
7
+ story presets and component events in the Actions panel.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeremy Kreutzbender
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # @fridgedoor/storybook-effect-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Storybook 11 framework for Effect UI components. It pairs Storybook's Vite
4
+ builder with a renderer that mounts components through `BrowserHost`. Configure
5
+ themes, CSS and toolbar globals in your project's `.storybook/preview.ts`.
6
+
7
+ ## Install
8
+
9
+ Use Node 22.12 or later. Install the framework and its peer dependencies in
10
+ your Storybook project.
11
+
12
+ ```sh
13
+ pnpm add -D @fridgedoor/storybook-effect-ui effect@^4.2.0 vite@^8.4.0 \
14
+ storybook@11.0.2 @storybook/builder-vite@11.0.2
15
+ ```
16
+
17
+ ## Compatibility
18
+
19
+ The package check covers Effect 4.2.0, Storybook and builder-vite 11.0.2,
20
+ Vite 8.4.0 and TypeScript 7.0.2 with `skipLibCheck`. Keep `storybook` and
21
+ `@storybook/builder-vite` on the same version when upgrading.
22
+
23
+ ## Setup
24
+
25
+ Set the framework and story globs in `.storybook/main.ts`.
26
+
27
+ ```ts
28
+ // .storybook/main.ts
29
+ import type { StorybookConfig } from "@fridgedoor/storybook-effect-ui/node";
30
+
31
+ const config: StorybookConfig = {
32
+ framework: { name: "@fridgedoor/storybook-effect-ui", options: {} },
33
+ stories: ["../test/**/*.stories.ts"],
34
+ };
35
+
36
+ export default config;
37
+ ```
38
+
39
+ The framework preset also turns off the onboarding checklists, the
40
+ Interactions panel and the Backgrounds toolbar. Set
41
+ `core.disableWhatsNewNotifications` in the app's main config to turn off the
42
+ "what's new" notifications as well. Run `pnpm exec storybook dev -p 6006`
43
+ to start Storybook or `pnpm exec storybook build` to build the static site.
44
+
45
+ If your TypeScript project checks dependency declarations, Storybook's own
46
+ declarations also need React types. Add `@types/react` or enable
47
+ `skipLibCheck`.
48
+
49
+ ## Writing stories
50
+
51
+ A story's `component` comes from one of two helpers:
52
+
53
+ - `headlessStory(Component, view)` takes a headless component and a view of its
54
+ parts. The view receives the render's args and toolbar globals.
55
+ - `componentStory(Component, { target })` takes an HTML component. Set `target`
56
+ when it wraps the component under story, as an example or demo does.
57
+
58
+ `fromCase(Cases["name"])` reuses a Case's component, props and Layer, so a
59
+ story can start from a test fixture.
60
+
61
+ ```ts
62
+ import { headlessStory, type Meta, type StoryObj } from "@fridgedoor/storybook-effect-ui";
63
+
64
+ const meta: Meta<MonthGridProps> = {
65
+ title: "Calendar/Month",
66
+ component: headlessStory(MonthGrid, (h, grid) => MonthMarkup(h, grid)),
67
+ parameters: {
68
+ effect: {
69
+ presets: { Household: householdMonth, Empty: emptyMonth },
70
+ eventArgs: { PressedDay: ({ day }) => ({ selectedDay: day }) },
71
+ },
72
+ },
73
+ };
74
+
75
+ export default meta;
76
+
77
+ export const Month: StoryObj<MonthGridProps> = {};
78
+ ```
79
+
80
+ Controls come from the props Schema's JSON Schema. Literal unions get radios or
81
+ selects, booleans and numbers get their own controls (numbers keep their
82
+ bounds), strings get text, and objects and arrays are edited as JSON. A string
83
+ prop that starts as a UTC timestamp gets a date control. Storybook revives
84
+ timestamp text as a `Date`, which a text control would show blank. The
85
+ renderer turns revived Dates and date-control milliseconds back into ISO text,
86
+ then decodes every prop through its Schema, or else through its canonical
87
+ JSON form. Invalid args show Storybook's error screen with `Cause.pretty`.
88
+
89
+ An arg change reaches the mounted component through `setProps`, so the
90
+ component is not remounted. A new story, component, Layer or `key` does
91
+ remount it.
92
+
93
+ ### `parameters.effect`
94
+
95
+ | Option | Purpose |
96
+ | ------------ | ---------------------------------------------------------------------------------------------------------------------- |
97
+ | `presets` | Named sets of args. A `preset` select fills the other controls and clears args that other presets set. |
98
+ | `layer` | Services around the mount, given as a Layer or as a function of the args. A new Layer remounts the story. |
99
+ | `key` | A value computed from the args. A change of key remounts the story, for components that read props only in `init`. |
100
+ | `actions` | `"component"` (the default) logs the events of the first instance of the target. `"all"` logs every instance's events. |
101
+ | `eventArgs` | Arg updates by event tag. A controlled component then behaves as it would under a parent that owns its state. |
102
+ | `globalArgs` | Args filled from toolbar globals, given as `{ arg: global }`. These args are hidden from Controls. |
103
+
104
+ Options set on a story are merged over the meta's.
105
+
106
+ ## Actions and DevTools
107
+
108
+ The Actions panel logs events emitted by the target component. Set
109
+ `parameters.effect.actions` to `"all"` to see events from every mounted
110
+ component. Use `eventArgs` to turn events into updates to controlled props.
111
+
112
+ The renderer provides a `MessageLog` to each mount. That log reports `Failed`
113
+ entries to Storybook's error screen and sends the target's events to the
114
+ Actions panel. When the DevTools Vite plugin's overlay is on the page,
115
+ `BrowserHost` fans the same log out to DevTools as well. Both rely on Effect UI
116
+ APIs marked unstable, including `BrowserHost.mountEffect`, `MessageLog`
117
+ entries and the identity of `component.definition`. The framework also
118
+ uses unstable `storybook/internal` APIs for types and core events. Check
119
+ compatibility when upgrading either peer, including within the ranges
120
+ above.
121
+
122
+ ## Verify the npm package
123
+
124
+ From the repository root, run the same check as CI. It packs the framework,
125
+ lints the tarball, and uses npm to install it in a temporary consumer where
126
+ TypeScript, Storybook and Chromium exercise it. The consumer runs only its own
127
+ binaries and installs the Chromium its own Playwright needs.
128
+
129
+ ```sh
130
+ pnpm --filter @fridgedoor/storybook-effect-ui verify:package
131
+ ```
132
+
133
+ Pass an absolute `.tgz` path as the final argument to keep the verified tarball.
134
+ The preview server listens on port 6173. Set `CONSUMER_PORT` to use another
135
+ port, for example when two checkouts run the check at once.
136
+ See the repository's [release guide](https://github.com/jer-k/fridgedoor/blob/main/docs/releasing.md).
@@ -0,0 +1,16 @@
1
+ import type { Component, MessageLog } from "effect/ui";
2
+ /** An event a component emitted, as the message log records it. */
3
+ export type EmittedEvent = MessageLog.Update["events"][number];
4
+ /** An event a story reports, with the name its action is logged under. */
5
+ export interface StoryEvent {
6
+ readonly name: string;
7
+ readonly event: EmittedEvent;
8
+ }
9
+ /** The action name of an event: its tag, or `Emitted` for an untagged event. */
10
+ export declare const eventName: (event: EmittedEvent) => string;
11
+ /**
12
+ * Picks the events a story reports from message log entries: by default
13
+ * those of the first mounted instance of `target`, the instance the story
14
+ * renders, and with `all` those of every instance.
15
+ */
16
+ export declare function storyEvents(target: Component.Definition.Any, all: boolean): (entry: MessageLog.Entry) => ReadonlyArray<StoryEvent>;
@@ -0,0 +1,24 @@
1
+ import { Predicate } from "effect";
2
+ /** The action name of an event: its tag, or `Emitted` for an untagged event. */
3
+ export const eventName = (event) => Predicate.hasProperty(event, "_tag") && Predicate.isString(event._tag) ? event._tag : "Emitted";
4
+ const isInstanceEntry = (entry) => Predicate.isTagged(entry, "Update") || Predicate.isTagged(entry, "Mounted");
5
+ /**
6
+ * Picks the events a story reports from message log entries: by default
7
+ * those of the first mounted instance of `target`, the instance the story
8
+ * renders, and with `all` those of every instance.
9
+ */
10
+ export function storyEvents(target, all) {
11
+ let targetPath;
12
+ return (entry) => {
13
+ if (!isInstanceEntry(entry))
14
+ return [];
15
+ if (!all) {
16
+ if (entry.component.definition !== target)
17
+ return [];
18
+ targetPath ??= entry.path;
19
+ if (entry.path !== targetPath)
20
+ return [];
21
+ }
22
+ return entry.events.map((event) => ({ name: eventName(event), event }));
23
+ };
24
+ }
package/dist/args.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { Schema } from "effect";
2
+ import type { Args, ArgsEnhancer, Globals, Parameters } from "storybook/internal/types";
3
+ import type { EffectParameters, EffectRenderer } from "./types.ts";
4
+ /**
5
+ * ISO text for a `Date`, without milliseconds when they are zero. Storybook
6
+ * revives UTC timestamp strings as Dates when args cross its channel.
7
+ */
8
+ export declare function isoText(date: Date): string;
9
+ /** Whether `u` is UTC timestamp text, which Storybook revives as a `Date`. */
10
+ export declare const isTimestampText: (u: unknown) => u is string;
11
+ /**
12
+ * Turns Storybook's revived Dates back into ISO text and drops `undefined`
13
+ * entries, deeply through arrays and plain objects. Other values are kept.
14
+ */
15
+ export declare function normalizeArgs(args: Readonly<Args>): Args;
16
+ /** The fields of a Struct props Schema, or `undefined` for any other Schema. */
17
+ export declare function structFields(schema: Schema.Top): Readonly<Record<string, Schema.Top>> | undefined;
18
+ /**
19
+ * The props a story mounts with: its args, normalized and decoded through
20
+ * the props Schema. Each field decodes as the type or as canonical JSON, and
21
+ * args that are not props are dropped. Throws the decoding error.
22
+ */
23
+ export declare function propsFromArgs<Props>(schema: Schema.Codec<Props, any>, args: Args): Props;
24
+ /** The `effect` parameters of a story, or none. */
25
+ export declare function effectParameters(parameters: Parameters): EffectParameters;
26
+ /** The name of the arg that selects a preset. */
27
+ export declare const presetArg = "preset";
28
+ /**
29
+ * The arg update that applies preset `name`: its args, and `undefined` for
30
+ * args that only other presets set.
31
+ */
32
+ export declare function presetUpdate(presets: Readonly<Record<string, Readonly<Args>>>, name: string): Args;
33
+ /** The args of the preset a story starts from, or none. */
34
+ export declare function startingPreset(presets: Readonly<Record<string, Readonly<Args>>> | undefined, initialArgs: Readonly<Args>): Readonly<Args>;
35
+ /**
36
+ * Starts a story with presets from its preset's args. Args the story sets
37
+ * itself win.
38
+ */
39
+ export declare const presetArgsEnhancer: ArgsEnhancer<EffectRenderer>;
40
+ /** Copies the toolbar globals named in `globalArgs` into the args. */
41
+ export declare function withGlobalArgs(args: Args, globalArgs: EffectParameters["globalArgs"], globals: Globals): Args;
package/dist/args.js ADDED
@@ -0,0 +1,141 @@
1
+ import { Exit, Predicate, Schema } from "effect";
2
+ const isPlainObject = (u) => {
3
+ if (!Predicate.isObject(u) || Array.isArray(u))
4
+ return false;
5
+ const prototype = Object.getPrototypeOf(u);
6
+ return prototype === Object.prototype || prototype === null;
7
+ };
8
+ /**
9
+ * ISO text for a `Date`, without milliseconds when they are zero. Storybook
10
+ * revives UTC timestamp strings as Dates when args cross its channel.
11
+ */
12
+ export function isoText(date) {
13
+ const text = date.toISOString();
14
+ return date.getUTCMilliseconds() === 0 ? text.replace(".000Z", "Z") : text;
15
+ }
16
+ const timestampText = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
17
+ /** Whether `u` is UTC timestamp text, which Storybook revives as a `Date`. */
18
+ export const isTimestampText = (u) => Predicate.isString(u) && timestampText.test(u);
19
+ /**
20
+ * Turns Storybook's revived Dates back into ISO text and drops `undefined`
21
+ * entries, deeply through arrays and plain objects. Other values are kept.
22
+ */
23
+ export function normalizeArgs(args) {
24
+ const normalized = {};
25
+ for (const [key, entry] of Object.entries(args)) {
26
+ if (entry !== undefined)
27
+ normalized[key] = normalizeValue(entry);
28
+ }
29
+ return normalized;
30
+ }
31
+ function normalizeValue(value) {
32
+ if (Predicate.isDate(value))
33
+ return isoText(value);
34
+ if (Array.isArray(value))
35
+ return value.map(normalizeValue);
36
+ return isPlainObject(value) ? normalizeArgs(value) : value;
37
+ }
38
+ /** The fields of a Struct props Schema, or `undefined` for any other Schema. */
39
+ export function structFields(schema) {
40
+ // SAFETY: a Schema with an object of `fields` is a Struct, whose fields are Schemas.
41
+ return Predicate.hasProperty(schema, "fields") && Predicate.isObject(schema.fields)
42
+ ? schema.fields
43
+ : undefined;
44
+ }
45
+ /**
46
+ * Decodes one value as the Schema's type, or else from its canonical JSON
47
+ * form, which is what an object control edits. A number that is neither is
48
+ * tried as ISO text: a date control sets milliseconds.
49
+ */
50
+ function decodeField(schema, value) {
51
+ const type = Schema.toType(schema);
52
+ const attempts = [
53
+ Schema.decodeUnknownExit(type),
54
+ Schema.decodeUnknownExit(Schema.toCodecJson(type)),
55
+ ];
56
+ for (const decode of attempts) {
57
+ const exit = decode(value);
58
+ if (Exit.isSuccess(exit))
59
+ return exit.value;
60
+ }
61
+ if (Predicate.isNumber(value) && Number.isFinite(value)) {
62
+ const text = isoText(new Date(value));
63
+ const exit = Schema.decodeUnknownExit(type)(text);
64
+ if (Exit.isSuccess(exit))
65
+ return exit.value;
66
+ }
67
+ return Schema.decodeUnknownSync(type)(value);
68
+ }
69
+ /**
70
+ * The props a story mounts with: its args, normalized and decoded through
71
+ * the props Schema. Each field decodes as the type or as canonical JSON, and
72
+ * args that are not props are dropped. Throws the decoding error.
73
+ */
74
+ export function propsFromArgs(schema, args) {
75
+ const input = normalizeArgs(args);
76
+ const fields = structFields(schema);
77
+ if (fields === undefined)
78
+ return decodeField(schema, input);
79
+ const props = {};
80
+ for (const [key, field] of Object.entries(fields)) {
81
+ if (!Object.hasOwn(input, key))
82
+ continue;
83
+ props[key] = decodeField(field, input[key]);
84
+ }
85
+ return Schema.decodeUnknownSync(Schema.toType(schema))(props);
86
+ }
87
+ /** The `effect` parameters of a story, or none. */
88
+ export function effectParameters(parameters) {
89
+ const effect = parameters["effect"];
90
+ return effect ?? {};
91
+ }
92
+ /** The name of the arg that selects a preset. */
93
+ export const presetArg = "preset";
94
+ /**
95
+ * The arg update that applies preset `name`: its args, and `undefined` for
96
+ * args that only other presets set.
97
+ */
98
+ export function presetUpdate(presets, name) {
99
+ const update = {};
100
+ for (const preset of Object.values(presets)) {
101
+ for (const key of Object.keys(preset))
102
+ update[key] = undefined;
103
+ }
104
+ return { ...update, ...presets[name], [presetArg]: name };
105
+ }
106
+ /** The name of the preset a story starts from: `args.preset`, or the first. */
107
+ function startingPresetName(presets, initialArgs) {
108
+ const chosen = initialArgs[presetArg];
109
+ return Predicate.isString(chosen) ? chosen : Object.keys(presets)[0];
110
+ }
111
+ /** The args of the preset a story starts from, or none. */
112
+ export function startingPreset(presets, initialArgs) {
113
+ if (presets === undefined)
114
+ return {};
115
+ const name = startingPresetName(presets, initialArgs);
116
+ return name === undefined ? {} : (presets[name] ?? {});
117
+ }
118
+ /**
119
+ * Starts a story with presets from its preset's args. Args the story sets
120
+ * itself win.
121
+ */
122
+ export const presetArgsEnhancer = ({ parameters, initialArgs }) => {
123
+ const { presets } = effectParameters(parameters);
124
+ if (presets === undefined)
125
+ return {};
126
+ const name = startingPresetName(presets, initialArgs);
127
+ if (name === undefined)
128
+ return {};
129
+ return Object.fromEntries(Object.entries({ ...presets[name], [presetArg]: name }).filter(([key]) => key === presetArg || !Object.hasOwn(initialArgs, key)));
130
+ };
131
+ /** Copies the toolbar globals named in `globalArgs` into the args. */
132
+ export function withGlobalArgs(args, globalArgs, globals) {
133
+ if (globalArgs === undefined)
134
+ return args;
135
+ const filled = { ...args };
136
+ for (const [arg, global] of Object.entries(globalArgs)) {
137
+ if (Predicate.isString(global) && globals[global] !== undefined)
138
+ filled[arg] = globals[global];
139
+ }
140
+ return filled;
141
+ }
@@ -0,0 +1,12 @@
1
+ import { render, renderToCanvas } from "./render.ts";
2
+ export { render, renderToCanvas };
3
+ /** Marks stories as rendered by the Effect UI renderer. */
4
+ export declare const parameters: {
5
+ renderer: string;
6
+ };
7
+ /** Derives Controls from each story component's props Schema. */
8
+ export declare const argTypesEnhancers: import("storybook/internal/csf").ArgTypesEnhancer<import("./types.ts").EffectRenderer>[];
9
+ /** Starts stories with presets from their preset's args. */
10
+ export declare const argsEnhancers: import("storybook/internal/csf").ArgsEnhancer<import("./types.ts").EffectRenderer>[];
11
+ /** Applies a newly chosen preset. */
12
+ export declare const decorators: import("storybook/internal/csf").DecoratorFunction<import("./types.ts").EffectRenderer>[];
@@ -0,0 +1,12 @@
1
+ import { presetArgsEnhancer } from "./args.js";
2
+ import { presetDecorator, render, renderToCanvas } from "./render.js";
3
+ import { argTypesEnhancer } from "./schema-arg-types.js";
4
+ export { render, renderToCanvas };
5
+ /** Marks stories as rendered by the Effect UI renderer. */
6
+ export const parameters = { renderer: "effect-ui" };
7
+ /** Derives Controls from each story component's props Schema. */
8
+ export const argTypesEnhancers = [argTypesEnhancer];
9
+ /** Starts stories with presets from their preset's args. */
10
+ export const argsEnhancers = [presetArgsEnhancer];
11
+ /** Applies a newly chosen preset. */
12
+ export const decorators = [presetDecorator];
@@ -0,0 +1,6 @@
1
+ export { eventName, storyEvents, type EmittedEvent, type StoryEvent } from "./actions.ts";
2
+ export { isoText, normalizeArgs, presetUpdate, propsFromArgs } from "./args.ts";
3
+ export { renderStory, type RenderCallbacks, type RenderRequest, type Teardown } from "./render.ts";
4
+ export { schemaArgTypes } from "./schema-arg-types.ts";
5
+ export { componentStory, fromCase, headlessStory, isStoryComponent, type CaseStory, type ComponentStoryOptions, } from "./story.ts";
6
+ export type { ArgValue, Decorator, EffectParameters, EffectRenderer, EffectStoryParameters, PresetArgs, Meta, Preview, StoryComponent, StoryContext, StoryEnv, StoryKey, StoryLayer, StoryObj, StoryResult, UpdateStory, } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { eventName, storyEvents } from "./actions.js";
2
+ export { isoText, normalizeArgs, presetUpdate, propsFromArgs } from "./args.js";
3
+ export { renderStory } from "./render.js";
4
+ export { schemaArgTypes } from "./schema-arg-types.js";
5
+ export { componentStory, fromCase, headlessStory, isStoryComponent, } from "./story.js";
package/dist/node.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { BuilderOptions, StorybookConfigVite } from "@storybook/builder-vite";
2
+ import type { CompatibleString, StorybookConfig as StorybookConfigBase } from "storybook/internal/types";
3
+ type FrameworkName = CompatibleString<"@fridgedoor/storybook-effect-ui">;
4
+ /** Options of the `@fridgedoor/storybook-effect-ui` framework. */
5
+ export interface FrameworkOptions {
6
+ readonly builder?: BuilderOptions;
7
+ }
8
+ /** The type of `.storybook/main.ts` with the `@fridgedoor/storybook-effect-ui` framework. */
9
+ export type StorybookConfig = Omit<StorybookConfigBase, keyof StorybookConfigVite | "framework"> & StorybookConfigVite & {
10
+ framework: FrameworkName | {
11
+ name: FrameworkName;
12
+ options: FrameworkOptions;
13
+ };
14
+ };
15
+ /** Types a main config without changing it. */
16
+ export declare const defineMain: (config: StorybookConfig) => StorybookConfig;
17
+ export {};
package/dist/node.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Types a main config without changing it. */
2
+ export const defineMain = (config) => config;
@@ -0,0 +1,13 @@
1
+ import type { StorybookConfigRaw } from "storybook/internal/types";
2
+ /** Pairs the Vite builder with the Effect UI renderer. */
3
+ export declare const core: {
4
+ builder: string;
5
+ renderer: string;
6
+ };
7
+ /**
8
+ * Turns off the onboarding checklist and the panels Effect UI stories don't
9
+ * use: Interactions, without play functions, and Backgrounds, which a
10
+ * preview's own theme replaces. The project's main config can turn them
11
+ * back on.
12
+ */
13
+ export declare const features: (existing?: StorybookConfigRaw["features"]) => StorybookConfigRaw["features"];
package/dist/preset.js ADDED
@@ -0,0 +1,19 @@
1
+ import { fileURLToPath } from "node:url";
2
+ /** Pairs the Vite builder with the Effect UI renderer. */
3
+ export const core = {
4
+ builder: fileURLToPath(import.meta.resolve("@storybook/builder-vite")),
5
+ renderer: fileURLToPath(import.meta.resolve("@fridgedoor/storybook-effect-ui/renderer/preset")),
6
+ };
7
+ /**
8
+ * Turns off the onboarding checklist and the panels Effect UI stories don't
9
+ * use: Interactions, without play functions, and Backgrounds, which a
10
+ * preview's own theme replaces. The project's main config can turn them
11
+ * back on.
12
+ */
13
+ export const features = (existing = {}) => ({
14
+ ...existing,
15
+ sidebarOnboardingChecklist: false,
16
+ menuOnboardingChecklist: false,
17
+ interactions: false,
18
+ backgrounds: false,
19
+ });
@@ -0,0 +1,44 @@
1
+ import type { Args, ArgsStoryFn, DecoratorFunction, Parameters, RenderToCanvas } from "storybook/internal/types";
2
+ import { type EmittedEvent } from "./actions.ts";
3
+ import type { EffectRenderer, StoryResult } from "./types.ts";
4
+ /** What a render needs from Storybook: its story, args and parameters. */
5
+ export interface RenderRequest {
6
+ readonly id: string;
7
+ readonly forceRemount: boolean;
8
+ readonly story: () => StoryResult;
9
+ readonly args: Args;
10
+ readonly parameters: Parameters;
11
+ }
12
+ /** What a render reports to Storybook. */
13
+ export interface RenderCallbacks {
14
+ readonly showMain: () => void;
15
+ readonly showError: (error: {
16
+ readonly title: string;
17
+ readonly description: string;
18
+ }) => void;
19
+ readonly action: (name: string) => (event: EmittedEvent) => void;
20
+ readonly updateArgs: (args: Args) => void;
21
+ }
22
+ /** Ends a mounted story: interrupts its fiber and removes its element. */
23
+ export type Teardown = () => Promise<void>;
24
+ /**
25
+ * Mounts a story into `canvas`, or gives the mounted one new props when only
26
+ * its args or globals changed. A new story, component, Layer or key, or a
27
+ * forced remount, interrupts the previous fiber first. The latest call owns
28
+ * the canvas: an earlier call still waiting on a previous mount gives up and
29
+ * returns a no-op teardown. Returns the teardown.
30
+ */
31
+ export declare function renderStory(request: RenderRequest, canvas: HTMLElement, callbacks: RenderCallbacks): Promise<Teardown>;
32
+ /**
33
+ * Renders a story from its args: decodes them through the props Schema,
34
+ * fills args from globals and picks the story's Layer.
35
+ */
36
+ export declare const render: ArgsStoryFn<EffectRenderer>;
37
+ /** Storybook's entry to `renderStory`, reporting actions and arg updates. */
38
+ export declare const renderToCanvas: RenderToCanvas<EffectRenderer>;
39
+ /**
40
+ * Applies a preset when the `preset` control changes, or when the story
41
+ * opens on a preset other than its initial one (from the URL): this render
42
+ * uses its args, and Controls are updated to match.
43
+ */
44
+ export declare const presetDecorator: DecoratorFunction<EffectRenderer>;
package/dist/render.js ADDED
@@ -0,0 +1,188 @@
1
+ import { Cause, Context, Effect, Fiber, Layer, Predicate } from "effect";
2
+ import { MessageLog } from "effect/ui";
3
+ import { action } from "storybook/actions";
4
+ import { UPDATE_STORY_ARGS } from "storybook/internal/core-events";
5
+ import { addons, useArgs, useEffect, useRef } from "storybook/preview-api";
6
+ import { storyEvents } from "./actions.js";
7
+ import { effectParameters, presetArg, presetUpdate, propsFromArgs, withGlobalArgs, } from "./args.js";
8
+ import { isStoryComponent } from "./story.js";
9
+ const mounts = new WeakMap();
10
+ const claims = new WeakMap();
11
+ const noTeardown = () => Promise.resolve();
12
+ function setDataset(element, dataset) {
13
+ for (const [key, value] of Object.entries(dataset ?? {})) {
14
+ if (value === undefined)
15
+ delete element.dataset[key];
16
+ else
17
+ element.dataset[key] = value;
18
+ }
19
+ }
20
+ const describe = (cause) => Cause.pretty(cause);
21
+ /**
22
+ * Mounts a story into `canvas`, or gives the mounted one new props when only
23
+ * its args or globals changed. A new story, component, Layer or key, or a
24
+ * forced remount, interrupts the previous fiber first. The latest call owns
25
+ * the canvas: an earlier call still waiting on a previous mount gives up and
26
+ * returns a no-op teardown. Returns the teardown.
27
+ */
28
+ export async function renderStory(request, canvas, callbacks) {
29
+ const claim = {};
30
+ const superseded = () => claims.get(canvas) !== claim;
31
+ claims.set(canvas, claim);
32
+ const previous = mounts.get(canvas);
33
+ let story;
34
+ try {
35
+ story = request.story();
36
+ }
37
+ catch (error) {
38
+ callbacks.showError({ title: "Invalid story args", description: describe(Cause.die(error)) });
39
+ return previous?.stop ?? noTeardown;
40
+ }
41
+ if (previous !== undefined &&
42
+ previous.id === request.id &&
43
+ previous.component === story.component &&
44
+ previous.layer === story.layer &&
45
+ Object.is(previous.key, story.key) &&
46
+ !request.forceRemount) {
47
+ await previous.ready;
48
+ if (superseded())
49
+ return noTeardown;
50
+ if (mounts.get(canvas) === previous && previous.update !== undefined) {
51
+ previous.request = request;
52
+ try {
53
+ previous.update(story.props, story.env);
54
+ setDataset(previous.wrapper, story.dataset);
55
+ callbacks.showMain();
56
+ }
57
+ catch (error) {
58
+ callbacks.showError({
59
+ title: "Invalid story props",
60
+ description: describe(Cause.die(error)),
61
+ });
62
+ }
63
+ return previous.stop;
64
+ }
65
+ }
66
+ await previous?.stop();
67
+ if (superseded())
68
+ return noTeardown;
69
+ const wrapper = canvas.ownerDocument.createElement("div");
70
+ wrapper.className = "effect-story";
71
+ setDataset(wrapper, story.dataset);
72
+ canvas.replaceChildren(wrapper);
73
+ const { promise: ready, resolve } = Promise.withResolvers();
74
+ const events = storyEvents(story.component.target, effectParameters(request.parameters).actions === "all");
75
+ const report = (title, cause) => {
76
+ if (mounts.get(canvas) === current)
77
+ callbacks.showError({ title, description: describe(cause) });
78
+ };
79
+ const record = (entry) => {
80
+ if (mounts.get(canvas) !== current)
81
+ return;
82
+ if (Predicate.isTagged(entry, "Failed")) {
83
+ queueMicrotask(() => report(`${entry.path} failed in ${entry.in}`, entry.cause));
84
+ }
85
+ for (const { name, event } of events(entry)) {
86
+ try {
87
+ callbacks.action(name)(event);
88
+ const { args, parameters } = current.request;
89
+ const update = effectParameters(parameters).eventArgs?.[name]?.(event, args);
90
+ if (update !== undefined)
91
+ callbacks.updateArgs(update);
92
+ }
93
+ catch (error) {
94
+ queueMicrotask(() => report(`Reporting ${name} failed`, Cause.die(error)));
95
+ }
96
+ }
97
+ };
98
+ const mount = Effect.gen(function* () {
99
+ const services = story.layer === undefined
100
+ ? Context.empty()
101
+ : yield* Layer.build(
102
+ // SAFETY: a story's Layer meets its own requirements; a missing service fails the mount, which the story reports.
103
+ story.layer);
104
+ // SAFETY: the story's Layer provides what its component's mount needs, as above; the mount's own scope is the story's.
105
+ current.update = yield* story.component.mount(story.props, story.env, wrapper).pipe(Effect.provide(services));
106
+ resolve();
107
+ return yield* Effect.never;
108
+ });
109
+ const current = {
110
+ id: request.id,
111
+ component: story.component,
112
+ layer: story.layer,
113
+ key: story.key,
114
+ wrapper,
115
+ ready,
116
+ request,
117
+ update: undefined,
118
+ stop: async () => {
119
+ if (mounts.get(canvas) === current)
120
+ mounts.delete(canvas);
121
+ await Effect.runPromise(Fiber.interrupt(fiber));
122
+ wrapper.remove();
123
+ },
124
+ };
125
+ mounts.set(canvas, current);
126
+ callbacks.showMain();
127
+ const fiber = Effect.runFork(Effect.scoped(mount).pipe(Effect.tapCause((cause) => Effect.sync(() => {
128
+ if (!Cause.hasInterruptsOnly(cause))
129
+ report("Effect UI story failed to mount", cause);
130
+ })), Effect.ensuring(Effect.sync(resolve)), Effect.provideService(MessageLog.MessageLog, { enabled: true, record }), Effect.ignoreCause));
131
+ await ready;
132
+ return current.stop;
133
+ }
134
+ /**
135
+ * Renders a story from its args: decodes them through the props Schema,
136
+ * fills args from globals and picks the story's Layer.
137
+ */
138
+ export const render = (args, context) => {
139
+ const { component, parameters, globals } = context;
140
+ if (!isStoryComponent(component)) {
141
+ throw new Error(`${context.title} needs a component made with headlessStory or componentStory.`);
142
+ }
143
+ const { globalArgs, layer, key } = effectParameters(parameters);
144
+ const filled = withGlobalArgs(args, globalArgs, globals);
145
+ return {
146
+ component,
147
+ props: propsFromArgs(component.props, filled),
148
+ env: { args: filled, globals },
149
+ layer: Predicate.isFunction(layer) ? layer(filled) : layer,
150
+ key: key?.(filled),
151
+ };
152
+ };
153
+ /** Storybook's entry to `renderStory`, reporting actions and arg updates. */
154
+ export const renderToCanvas = (context, canvas) => renderStory({
155
+ id: context.id,
156
+ forceRemount: context.forceRemount,
157
+ story: () => context.storyFn(),
158
+ args: context.storyContext.args,
159
+ parameters: context.storyContext.parameters,
160
+ }, canvas, {
161
+ showMain: context.showMain,
162
+ showError: context.showError,
163
+ action: (name) => action(name),
164
+ updateArgs: (updatedArgs) => addons.getChannel().emit(UPDATE_STORY_ARGS, { storyId: context.id, updatedArgs }),
165
+ });
166
+ /**
167
+ * Applies a preset when the `preset` control changes, or when the story
168
+ * opens on a preset other than its initial one (from the URL): this render
169
+ * uses its args, and Controls are updated to match.
170
+ */
171
+ export const presetDecorator = (storyFn, context) => {
172
+ const [, updateArgs] = useArgs();
173
+ const shown = useRef(context.initialArgs[presetArg]);
174
+ const { presets } = effectParameters(context.parameters);
175
+ const name = context.args[presetArg];
176
+ const update = presets !== undefined &&
177
+ Predicate.isString(name) &&
178
+ name !== shown.current &&
179
+ Object.hasOwn(presets, name)
180
+ ? presetUpdate(presets, name)
181
+ : undefined;
182
+ shown.current = name;
183
+ useEffect(() => {
184
+ if (update !== undefined)
185
+ updateArgs(update);
186
+ }, [update]);
187
+ return update === undefined ? storyFn() : storyFn({ args: { ...context.args, ...update } });
188
+ };
@@ -0,0 +1,2 @@
1
+ /** Adds the Effect UI renderer's preview annotations to the preview. */
2
+ export declare const previewAnnotations: (input?: ReadonlyArray<string>) => Array<string>;
@@ -0,0 +1,6 @@
1
+ import { fileURLToPath } from "node:url";
2
+ /** Adds the Effect UI renderer's preview annotations to the preview. */
3
+ export const previewAnnotations = (input = []) => [
4
+ ...input,
5
+ fileURLToPath(import.meta.resolve("@fridgedoor/storybook-effect-ui/entry-preview")),
6
+ ];
@@ -0,0 +1,17 @@
1
+ import { Schema } from "effect";
2
+ import type { Args, ArgTypes, ArgTypesEnhancer } from "storybook/internal/types";
3
+ import type { EffectRenderer } from "./types.ts";
4
+ /**
5
+ * Controls for the top-level props of a Schema, from its canonical JSON
6
+ * Schema: radios or selects for literals, booleans, numbers with their
7
+ * bounds, text, and JSON for objects and arrays. A string prop whose value in
8
+ * `sample` is a UTC timestamp gets a date control, because Storybook turns
9
+ * such text into a Date that a text control can't show.
10
+ */
11
+ export declare function schemaArgTypes(schema: Schema.Top, sample?: Readonly<Args>): ArgTypes;
12
+ /**
13
+ * Derives argTypes from the story component's props Schema and adds the
14
+ * preset select. ArgTypes the story declares are merged over them, and args
15
+ * filled from globals are hidden.
16
+ */
17
+ export declare const argTypesEnhancer: ArgTypesEnhancer<EffectRenderer>;
@@ -0,0 +1,143 @@
1
+ import { Predicate, Schema } from "effect";
2
+ import { combineParameters } from "storybook/preview-api";
3
+ import { effectParameters, isTimestampText, presetArg, startingPreset } from "./args.js";
4
+ import { isStoryComponent } from "./story.js";
5
+ function resolve(field, definitions) {
6
+ const ref = field["$ref"];
7
+ if (!Predicate.isString(ref))
8
+ return field;
9
+ const target = definitions[ref.replace(/^#\/\$defs\//, "")];
10
+ return target === undefined ? field : resolve(target, definitions);
11
+ }
12
+ /** The JSON Schemas a field may take, with `null` left out. */
13
+ function branches(field, definitions) {
14
+ const resolved = resolve(field, definitions);
15
+ const union = resolved["anyOf"] ?? resolved["oneOf"];
16
+ if (!Array.isArray(union))
17
+ return [resolved];
18
+ // SAFETY: the subschemas of a JSON Schema document are JSON Schema objects.
19
+ const subschemas = union.filter(Predicate.isObject);
20
+ const options = subschemas
21
+ .flatMap((branch) => branches(branch, definitions))
22
+ .filter((branch) => branch["type"] !== "null");
23
+ return options.some(isNumberBranch) ? options.filter((branch) => !isNonFinite(branch)) : options;
24
+ }
25
+ const isNumberBranch = (branch) => branch["type"] === "number" || branch["type"] === "integer";
26
+ const nonFinite = new Set(["Infinity", "-Infinity", "NaN"]);
27
+ /** The branch through which `Schema.Number` admits non-finite numbers as text. */
28
+ const isNonFinite = (branch) => branch["type"] === "string" &&
29
+ Array.isArray(branch["enum"]) &&
30
+ branch["enum"].every((value) => nonFinite.has(value));
31
+ /** A numeric bound worth showing: not the safe-integer range every Int carries. */
32
+ const bound = (value) => Predicate.isNumber(value) && Math.abs(value) < Number.MAX_SAFE_INTEGER ? value : undefined;
33
+ /** The literal values of a field made only of `const` and `enum` branches. */
34
+ function literals(options) {
35
+ const values = [];
36
+ for (const option of options) {
37
+ if (Object.hasOwn(option, "const"))
38
+ values.push(option["const"]);
39
+ else if (Array.isArray(option["enum"]))
40
+ values.push(...option["enum"]);
41
+ else
42
+ return undefined;
43
+ }
44
+ return values;
45
+ }
46
+ function summary(options) {
47
+ return options
48
+ .map((option) => Object.hasOwn(option, "const")
49
+ ? JSON.stringify(option["const"])
50
+ : Predicate.isString(option["type"])
51
+ ? option["type"]
52
+ : "unknown")
53
+ .join(" | ");
54
+ }
55
+ function inputType(name, field, required, definitions, sample) {
56
+ const options = branches(field, definitions);
57
+ const description = resolve(field, definitions)["description"] ?? options[0]?.["description"];
58
+ const base = {
59
+ name,
60
+ type: { name: "other", value: summary(options), required },
61
+ table: { type: { summary: summary(options) } },
62
+ ...(Predicate.isString(description) && { description }),
63
+ };
64
+ const values = literals(options);
65
+ if (values !== undefined && values.length > 0) {
66
+ return {
67
+ ...base,
68
+ control: { type: values.length <= 4 ? "inline-radio" : "select" },
69
+ options: values,
70
+ };
71
+ }
72
+ const [only] = options;
73
+ if (options.length !== 1 || only === undefined)
74
+ return { ...base, control: { type: "object" } };
75
+ switch (only["type"]) {
76
+ case "boolean":
77
+ return { ...base, control: { type: "boolean" } };
78
+ case "integer":
79
+ case "number":
80
+ return {
81
+ ...base,
82
+ control: {
83
+ type: "number",
84
+ ...(bound(only["minimum"]) !== undefined && { min: only["minimum"] }),
85
+ ...(bound(only["maximum"]) !== undefined && { max: only["maximum"] }),
86
+ ...(only["type"] === "integer" && { step: 1 }),
87
+ },
88
+ };
89
+ case "string":
90
+ return { ...base, control: { type: isTimestampText(sample) ? "date" : "text" } };
91
+ default:
92
+ return { ...base, control: { type: "object" } };
93
+ }
94
+ }
95
+ /**
96
+ * Controls for the top-level props of a Schema, from its canonical JSON
97
+ * Schema: radios or selects for literals, booleans, numbers with their
98
+ * bounds, text, and JSON for objects and arrays. A string prop whose value in
99
+ * `sample` is a UTC timestamp gets a date control, because Storybook turns
100
+ * such text into a Date that a text control can't show.
101
+ */
102
+ export function schemaArgTypes(schema, sample = {}) {
103
+ const { schema: root, definitions } = Schema.toJsonSchemaDocument(Schema.toType(schema));
104
+ const resolved = resolve(root, definitions);
105
+ const properties = resolved["properties"];
106
+ const required = Array.isArray(resolved["required"]) ? resolved["required"] : [];
107
+ if (!Predicate.isObject(properties))
108
+ return {};
109
+ const argTypes = {};
110
+ for (const [name, field] of Object.entries(properties)) {
111
+ if (!Predicate.isObject(field))
112
+ continue;
113
+ argTypes[name] = inputType(name,
114
+ // SAFETY: the properties of a JSON Schema object are JSON Schema objects.
115
+ field, required.includes(name), definitions, sample[name]);
116
+ }
117
+ return argTypes;
118
+ }
119
+ /**
120
+ * Derives argTypes from the story component's props Schema and adds the
121
+ * preset select. ArgTypes the story declares are merged over them, and args
122
+ * filled from globals are hidden.
123
+ */
124
+ export const argTypesEnhancer = (context) => {
125
+ const { component, parameters, argTypes, initialArgs } = context;
126
+ if (!isStoryComponent(component))
127
+ return argTypes;
128
+ const { presets, globalArgs } = effectParameters(parameters);
129
+ const derived = {
130
+ ...(presets !== undefined && {
131
+ [presetArg]: {
132
+ name: presetArg,
133
+ description: "Fills the other controls with a named set of args.",
134
+ control: { type: "select" },
135
+ options: Object.keys(presets),
136
+ },
137
+ }),
138
+ ...schemaArgTypes(component.props, { ...startingPreset(presets, initialArgs), ...initialArgs }),
139
+ };
140
+ const hidden = Object.fromEntries(Object.keys(globalArgs ?? {}).map((name) => [name, { table: { disable: true } }]));
141
+ // SAFETY: merging argTypes records yields an argTypes record.
142
+ return combineParameters(derived, argTypes, hidden);
143
+ };
@@ -0,0 +1,39 @@
1
+ import type { Component, View } from "effect/ui";
2
+ import type { Case } from "effect/ui/testing";
3
+ import { BrowserHost, Html } from "effect/ui/html";
4
+ import { type StoryComponent, type StoryEnv, type StoryLayer } from "./types.ts";
5
+ /** Whether `u` is a component prepared by `headlessStory` or `componentStory`. */
6
+ export declare const isStoryComponent: (u: unknown) => u is StoryComponent;
7
+ /**
8
+ * Prepares a headless component for Storybook. Controls edit its props, and
9
+ * `view` draws its parts as a consumer would, with the render's args and
10
+ * toolbar globals at hand. Its events are the story's actions.
11
+ */
12
+ export declare function headlessStory<H extends Component.Headless.Any>(component: H, view: (h: Html.Tags<never>, parts: Component.Headless.Parts<H>, story: StoryEnv) => View.Content<never>): StoryComponent<Component.Props<H>>;
13
+ /** Options of `componentStory`. */
14
+ export interface ComponentStoryOptions {
15
+ /**
16
+ * The component whose events are the story's actions, for a wrapper that
17
+ * renders the component under story. Defaults to the component itself.
18
+ */
19
+ readonly target?: {
20
+ readonly definition: Component.Definition.Any;
21
+ } | undefined;
22
+ }
23
+ /**
24
+ * Prepares an HTML component for Storybook. Controls edit its props, and
25
+ * arg changes reach it as new props without a remount. Services it needs
26
+ * come from `parameters.effect.layer`.
27
+ */
28
+ export declare function componentStory<Name extends string, Props, Model, Message, Events, R, V extends View.Elements>(component: Component.Members<Name, Props, Model, Message, Events, R, V, any> & BrowserHost.HtmlRoot<V>, options?: ComponentStoryOptions): StoryComponent<Props>;
29
+ /** What a story reuses from a Case: its component, props and Layer. */
30
+ export interface CaseStory<C extends Case.AnyComponent> {
31
+ readonly component: C;
32
+ readonly args: Component.Props<C>;
33
+ readonly layer: StoryLayer | undefined;
34
+ }
35
+ /**
36
+ * The component, props and Layer of a Case, to start a story from the same
37
+ * fixture. Throws for a missing Case or one whose props are an Effect.
38
+ */
39
+ export declare function fromCase<C extends Case.AnyComponent>(testCase: Case.Case<C, any> | undefined): CaseStory<C>;
package/dist/story.js ADDED
@@ -0,0 +1,69 @@
1
+ import { Effect, Predicate, Schema } from "effect";
2
+ import { BrowserHost, Html } from "effect/ui/html";
3
+ import { StoryComponentTypeId, } from "./types.js";
4
+ const StoryEnvSchema = Schema.Struct({
5
+ args: Schema.Record(Schema.String, Schema.Unknown),
6
+ globals: Schema.Record(Schema.String, Schema.Unknown),
7
+ });
8
+ /** Whether `u` is a component prepared by `headlessStory` or `componentStory`. */
9
+ export const isStoryComponent = (u) => Predicate.hasProperty(u, StoryComponentTypeId);
10
+ /**
11
+ * Prepares a headless component for Storybook. Controls edit its props, and
12
+ * `view` draws its parts as a consumer would, with the render's args and
13
+ * toolbar globals at hand. Its events are the story's actions.
14
+ */
15
+ export function headlessStory(component, view) {
16
+ // SAFETY: `H` is a headless component of these props and parts; the alias only names them.
17
+ const headless = component;
18
+ const Host = Html.component({
19
+ name: `${headless.definition.name}Story`,
20
+ props: Schema.Struct({ props: headless.props, story: StoryEnvSchema }),
21
+ model: Schema.Void,
22
+ message: Schema.Never,
23
+ }).make({
24
+ init: () => undefined,
25
+ update: () => undefined,
26
+ view: (h) => headless(h, {
27
+ props: h.props.props,
28
+ view: (parts) => view(h, parts, h.props.story),
29
+ }),
30
+ });
31
+ return {
32
+ [StoryComponentTypeId]: StoryComponentTypeId,
33
+ name: headless.definition.name,
34
+ props: headless.props,
35
+ target: headless.definition,
36
+ mount: (props, env, container) => Effect.map(BrowserHost.mountEffect(Host, { props, story: env }, container, { head: false }), (root) => (props, env) => root.setProps({ props, story: env })),
37
+ };
38
+ }
39
+ /**
40
+ * Prepares an HTML component for Storybook. Controls edit its props, and
41
+ * arg changes reach it as new props without a remount. Services it needs
42
+ * come from `parameters.effect.layer`.
43
+ */
44
+ export function componentStory(component, options) {
45
+ return {
46
+ [StoryComponentTypeId]: StoryComponentTypeId,
47
+ name: component.definition.name,
48
+ props: component.props,
49
+ target: options?.target?.definition ?? component.definition,
50
+ mount: (props, _env, container) => Effect.map(BrowserHost.mountEffect(component, Effect.succeed(props), container, { head: false }), (root) => (props) => root.setProps(props)),
51
+ };
52
+ }
53
+ /**
54
+ * The component, props and Layer of a Case, to start a story from the same
55
+ * fixture. Throws for a missing Case or one whose props are an Effect.
56
+ */
57
+ export function fromCase(testCase) {
58
+ if (testCase === undefined)
59
+ throw new Error("The story names a case that does not exist.");
60
+ const props = testCase.props;
61
+ if (Effect.isEffect(props))
62
+ throw new Error(`${testCase.name} has Effect props.`);
63
+ return {
64
+ component: testCase.component,
65
+ // SAFETY: a Case's props are the component's props or an Effect of them, ruled out above.
66
+ args: props,
67
+ layer: testCase.layer,
68
+ };
69
+ }
@@ -0,0 +1,111 @@
1
+ import type { Effect, Layer } from "effect";
2
+ import type { Schema } from "effect";
3
+ import type { Component } from "effect/ui";
4
+ import type { Args, ComponentAnnotations, DecoratorFunction, Globals, Parameters, ProjectAnnotations, StoryAnnotations, StoryContext as StorybookStoryContext, WebRenderer } from "storybook/internal/types";
5
+ /** Brands the values that `headlessStory` and `componentStory` return. */
6
+ export declare const StoryComponentTypeId: "~@fridgedoor/storybook-effect-ui/StoryComponent";
7
+ /** The args and toolbar globals of one render, readable by a story's view. */
8
+ export interface StoryEnv {
9
+ readonly args: Args;
10
+ readonly globals: Globals;
11
+ }
12
+ /** Gives a mounted story the props and environment of a later render. */
13
+ export type UpdateStory<Props> = (props: Props, env: StoryEnv) => void;
14
+ /**
15
+ * A component prepared for Storybook: the Schema its Controls edit, the
16
+ * component whose events are the story's actions, and how it mounts.
17
+ */
18
+ export interface StoryComponent<Props = any> {
19
+ readonly [StoryComponentTypeId]: typeof StoryComponentTypeId;
20
+ readonly name: string;
21
+ readonly props: Schema.Codec<Props, any>;
22
+ readonly target: Component.Definition.Any;
23
+ readonly mount: (props: Props, env: StoryEnv, container: HTMLElement) => Effect.Effect<UpdateStory<Props>, never, any>;
24
+ }
25
+ /** One arg's value, as Storybook holds it. */
26
+ export type ArgValue = Args[string];
27
+ /** Identifies a story's mount; a different key remounts it. */
28
+ export type StoryKey = string | number | boolean | null | undefined;
29
+ /** A Layer a story provides around its mount, of any services. */
30
+ export type StoryLayer = Layer.Layer<never, never, any>;
31
+ /** What `render` returns and `renderToCanvas` mounts or updates. */
32
+ export interface StoryResult {
33
+ readonly component: StoryComponent;
34
+ readonly props: unknown;
35
+ readonly env: StoryEnv;
36
+ readonly layer: StoryLayer | undefined;
37
+ /** Identifies the mount: a different key remounts the story. */
38
+ readonly key: StoryKey;
39
+ /** Data attributes set on the element that wraps the story, such as a theme. */
40
+ readonly dataset?: Readonly<Record<string, string | undefined>> | undefined;
41
+ }
42
+ /** The Storybook renderer for Effect UI components. */
43
+ export interface EffectRenderer extends WebRenderer {
44
+ component: StoryComponent;
45
+ storyResult: StoryResult;
46
+ }
47
+ /** The arg that names the chosen preset. */
48
+ export interface PresetArgs {
49
+ readonly preset?: string | undefined;
50
+ }
51
+ /**
52
+ * Story options read from `parameters.effect`. Story parameters are merged
53
+ * over the meta's, so a story can override any of them.
54
+ */
55
+ export interface EffectParameters<A extends Args = Args> {
56
+ /**
57
+ * Named sets of args. A `preset` select appears in Controls; choosing an
58
+ * entry writes all of its args, and clears args other presets set. The
59
+ * story starts from `args.preset`, or the first entry.
60
+ */
61
+ readonly presets?: Readonly<Record<string, Partial<A>>> | undefined;
62
+ /**
63
+ * Services provided around the mount, or a function of the args. A change
64
+ * of Layer (by reference) remounts the story.
65
+ */
66
+ readonly layer?: StoryLayer | ((args: A & PresetArgs) => StoryLayer | undefined) | undefined;
67
+ /**
68
+ * A key from the args. When it changes the story remounts, as a keyed
69
+ * child restarts: for a component that reads props only in `init`.
70
+ */
71
+ readonly key?: ((args: A & PresetArgs) => StoryKey) | undefined;
72
+ /**
73
+ * `"component"` (the default) logs the events of the component under
74
+ * story only: the first instance of its target. `"all"` logs every
75
+ * instance's events.
76
+ */
77
+ readonly actions?: "component" | "all" | undefined;
78
+ /**
79
+ * Arg updates for the target's events, by event tag. A controlled
80
+ * component then behaves as it would under a parent that owns its state,
81
+ * and Controls show that state.
82
+ */
83
+ readonly eventArgs?: {
84
+ readonly [tag: string]: ((event: any, args: A & PresetArgs) => Partial<A>) | undefined;
85
+ } | undefined;
86
+ /**
87
+ * Args filled from toolbar globals, as `{ arg: global }`. They are hidden
88
+ * from Controls.
89
+ */
90
+ readonly globalArgs?: {
91
+ readonly [K in keyof A]?: string;
92
+ } | undefined;
93
+ }
94
+ /** `parameters` with typed Effect UI options. */
95
+ export type EffectStoryParameters<A extends Args = Args> = Parameters & {
96
+ readonly effect?: EffectParameters<A> | undefined;
97
+ };
98
+ /** Metadata for a component's stories: its title, component and options. */
99
+ export type Meta<A extends Args = Args> = Omit<ComponentAnnotations<EffectRenderer, A>, "parameters"> & {
100
+ parameters?: EffectStoryParameters<A>;
101
+ };
102
+ /** One story: args, argTypes and options over the meta's. */
103
+ export type StoryObj<A extends Args = Args> = Omit<StoryAnnotations<EffectRenderer, A>, "parameters"> & {
104
+ parameters?: EffectStoryParameters<A>;
105
+ };
106
+ /** A story decorator. */
107
+ export type Decorator<A extends Args = Args> = DecoratorFunction<EffectRenderer, A>;
108
+ /** The context a decorator or render function receives. */
109
+ export type StoryContext<A extends Args = Args> = StorybookStoryContext<EffectRenderer, A>;
110
+ /** The annotations of `.storybook/preview.ts`. */
111
+ export type Preview = ProjectAnnotations<EffectRenderer>;
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Brands the values that `headlessStory` and `componentStory` return. */
2
+ export const StoryComponentTypeId = "~@fridgedoor/storybook-effect-ui/StoryComponent";
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@fridgedoor/storybook-effect-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Storybook framework and renderer for Effect UI components",
5
+ "keywords": [
6
+ "effect",
7
+ "effect-ui",
8
+ "storybook",
9
+ "storybook-framework",
10
+ "vite"
11
+ ],
12
+ "homepage": "https://github.com/jer-k/fridgedoor/tree/main/packages/storybook-effect-ui",
13
+ "bugs": {
14
+ "url": "https://github.com/jer-k/fridgedoor/issues"
15
+ },
16
+ "license": "MIT",
17
+ "author": "Jeremy Kreutzbender",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/jer-k/fridgedoor.git",
21
+ "directory": "packages/storybook-effect-ui"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./node": {
35
+ "types": "./dist/node.d.ts",
36
+ "default": "./dist/node.js"
37
+ },
38
+ "./preset": {
39
+ "types": "./dist/preset.d.ts",
40
+ "default": "./dist/preset.js"
41
+ },
42
+ "./renderer/preset": {
43
+ "types": "./dist/renderer/preset.d.ts",
44
+ "default": "./dist/renderer/preset.js"
45
+ },
46
+ "./entry-preview": {
47
+ "types": "./dist/entry-preview.d.ts",
48
+ "default": "./dist/entry-preview.js"
49
+ }
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "provenance": true
54
+ },
55
+ "devDependencies": {
56
+ "@arethetypeswrong/cli": "0.18.5",
57
+ "@effect/vitest": "^4.2.0",
58
+ "@storybook/builder-vite": "11.0.2",
59
+ "@types/node": "^26.6.11",
60
+ "effect": "^4.2.0",
61
+ "happy-dom": "^21.0.4",
62
+ "publint": "0.3.25",
63
+ "storybook": "11.0.2",
64
+ "typescript": "^7.0.2",
65
+ "vite": "^8.4.0"
66
+ },
67
+ "peerDependencies": {
68
+ "@storybook/builder-vite": "^11.0.2",
69
+ "effect": "^4.2.0",
70
+ "storybook": "^11.0.2",
71
+ "vite": "^8.4.0"
72
+ },
73
+ "engines": {
74
+ "node": ">=22.12.0"
75
+ },
76
+ "scripts": {
77
+ "build": "tsc -p tsconfig.build.json",
78
+ "verify:package": "bash scripts/verify-package.sh"
79
+ },
80
+ "types": "./dist/index.d.ts"
6
81
  }