@gtkx/storybook 0.0.1
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/dist/actions-panel.d.ts +7 -0
- package/dist/actions-panel.d.ts.map +1 -0
- package/dist/actions-panel.js +11 -0
- package/dist/actions-panel.js.map +1 -0
- package/dist/actions.d.ts +35 -0
- package/dist/actions.d.ts.map +1 -0
- package/dist/actions.js +161 -0
- package/dist/actions.js.map +1 -0
- package/dist/catalog.d.ts +71 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +158 -0
- package/dist/catalog.js.map +1 -0
- package/dist/compose.d.ts +27 -0
- package/dist/compose.d.ts.map +1 -0
- package/dist/compose.js +67 -0
- package/dist/compose.js.map +1 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -0
- package/dist/controls.d.ts +10 -0
- package/dist/controls.d.ts.map +1 -0
- package/dist/controls.js +94 -0
- package/dist/controls.js.map +1 -0
- package/dist/explorer-navigator.d.ts +11 -0
- package/dist/explorer-navigator.d.ts.map +1 -0
- package/dist/explorer-navigator.js +25 -0
- package/dist/explorer-navigator.js.map +1 -0
- package/dist/explorer-preview.d.ts +8 -0
- package/dist/explorer-preview.d.ts.map +1 -0
- package/dist/explorer-preview.js +89 -0
- package/dist/explorer-preview.js.map +1 -0
- package/dist/explorer-view.d.ts +15 -0
- package/dist/explorer-view.d.ts.map +1 -0
- package/dist/explorer-view.js +24 -0
- package/dist/explorer-view.js.map +1 -0
- package/dist/explorer.d.ts +22 -0
- package/dist/explorer.d.ts.map +1 -0
- package/dist/explorer.js +23 -0
- package/dist/explorer.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +143 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/upstream.d.ts +14 -0
- package/dist/upstream.d.ts.map +1 -0
- package/dist/upstream.js +5 -0
- package/dist/upstream.js.map +1 -0
- package/package.json +86 -0
- package/src/actions-panel.tsx +32 -0
- package/src/actions.ts +234 -0
- package/src/catalog.ts +263 -0
- package/src/compose.ts +94 -0
- package/src/config.ts +14 -0
- package/src/controls.tsx +206 -0
- package/src/explorer-navigator.tsx +120 -0
- package/src/explorer-preview.tsx +207 -0
- package/src/explorer-view.tsx +93 -0
- package/src/explorer.ts +44 -0
- package/src/index.ts +16 -0
- package/src/types.ts +205 -0
- package/src/upstream.ts +24 -0
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { Args, ArgTypes, ComponentMeta, ComposedStory, Preview, StoryAnnotations } from "./types.js";
|
|
2
|
+
import { composeStories } from "./compose.js";
|
|
3
|
+
import { storyNameFromExport } from "./upstream.js";
|
|
4
|
+
|
|
5
|
+
/** A lazily loaded CSF module discovered in a Storybook project. */
|
|
6
|
+
type StorySource = {
|
|
7
|
+
/** Stable module identifier used for caching and error reporting. */
|
|
8
|
+
id: string;
|
|
9
|
+
/** Fallback story group title when the module does not declare one. */
|
|
10
|
+
title: string;
|
|
11
|
+
/** Imports the module and resolves to its CSF exports. */
|
|
12
|
+
load: () => Promise<unknown>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** A composed story and the metadata used to display it in the explorer. */
|
|
16
|
+
type StoryEntry = {
|
|
17
|
+
/** Storybook identifier used to preserve the selected story across updates. */
|
|
18
|
+
id: string;
|
|
19
|
+
/** Component group title declared by the module or derived from its source. */
|
|
20
|
+
title: string;
|
|
21
|
+
/** Display name declared by the story or derived from its export name. */
|
|
22
|
+
name: string;
|
|
23
|
+
/** Name of the CSF export that defines this story. */
|
|
24
|
+
exportName: string;
|
|
25
|
+
/** Identifier of the module containing this story. */
|
|
26
|
+
source: string;
|
|
27
|
+
/** Renderable story with its metadata, decorators, and default args composed. */
|
|
28
|
+
story: ComposedStory;
|
|
29
|
+
/** Resolved arg types with explicitly configured explorer controls. */
|
|
30
|
+
controls: ArgTypes;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** A source loading or composition failure displayed alongside healthy stories. */
|
|
34
|
+
type StoryLoadError = {
|
|
35
|
+
/** Identifier of the failed source, or Storybook for a session failure. */
|
|
36
|
+
source: string;
|
|
37
|
+
/** Normalized error raised while loading or composing the source. */
|
|
38
|
+
error: Error;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Current explorer contents and loading state exposed to subscribers. */
|
|
42
|
+
type StoryCatalogSnapshot = {
|
|
43
|
+
/** Successfully composed stories with duplicate identifiers excluded. */
|
|
44
|
+
stories: StoryEntry[];
|
|
45
|
+
/** Failures encountered during the latest load or reported by the session. */
|
|
46
|
+
errors: StoryLoadError[];
|
|
47
|
+
/** Whether the catalog is waiting for the latest source load to finish. */
|
|
48
|
+
isLoading: boolean;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
type CachedStories = {
|
|
52
|
+
module: unknown;
|
|
53
|
+
title: string;
|
|
54
|
+
preview: Preview;
|
|
55
|
+
entries: StoryEntry[];
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
type LoadedSource = StoryLoadError | { source: StorySource; cached: CachedStories };
|
|
59
|
+
|
|
60
|
+
const EMPTY_PREVIEW: Preview = {};
|
|
61
|
+
|
|
62
|
+
const normalizeError = (cause: unknown): Error => cause instanceof Error ? cause : new Error(String(cause));
|
|
63
|
+
|
|
64
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
65
|
+
value !== null && typeof value === "object" && !Array.isArray(value);
|
|
66
|
+
|
|
67
|
+
const explicitControls = (
|
|
68
|
+
resolved: ArgTypes,
|
|
69
|
+
story: StoryAnnotations<Args> | undefined,
|
|
70
|
+
meta: ComponentMeta<Args>,
|
|
71
|
+
preview: Preview,
|
|
72
|
+
): ArgTypes => {
|
|
73
|
+
const controls: ArgTypes = {};
|
|
74
|
+
|
|
75
|
+
for (const [argument, annotation] of Object.entries(resolved)) {
|
|
76
|
+
const control = story?.argTypes?.[argument]?.control ??
|
|
77
|
+
meta.argTypes?.[argument]?.control ?? preview.argTypes?.[argument]?.control;
|
|
78
|
+
|
|
79
|
+
if (control === undefined) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
controls[argument] = { ...annotation, control: control === false ? false : annotation?.control ?? control };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return controls;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const displayName = (story: StoryAnnotations<Args> | undefined, exportName: string): string => {
|
|
90
|
+
const name = story?.name;
|
|
91
|
+
|
|
92
|
+
if (name === undefined) {
|
|
93
|
+
return storyNameFromExport(exportName);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (typeof name !== "string") {
|
|
97
|
+
throw new TypeError("Expected a story display name");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return name;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const composeSource = (source: StorySource, module: unknown, preview: Preview): StoryEntry[] => {
|
|
104
|
+
if (!isObject(module) || !isObject(module.default)) {
|
|
105
|
+
throw new TypeError(`Expected CSF3 component metadata in ${source.id}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const title = module.default.title ?? source.title;
|
|
109
|
+
|
|
110
|
+
if (typeof title !== "string" || title.trim().length === 0) {
|
|
111
|
+
throw new TypeError(`Expected a story title in ${source.id}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const annotations = {
|
|
115
|
+
...module,
|
|
116
|
+
default: { ...module.default, title },
|
|
117
|
+
} as Record<string, StoryAnnotations<Args>> & { default: ComponentMeta<Args> };
|
|
118
|
+
const stories = composeStories(annotations, preview);
|
|
119
|
+
|
|
120
|
+
return Object.entries(stories).map(([exportName, story]) => ({
|
|
121
|
+
id: story.id,
|
|
122
|
+
title,
|
|
123
|
+
name: displayName(annotations[exportName], exportName),
|
|
124
|
+
exportName,
|
|
125
|
+
source: source.id,
|
|
126
|
+
story,
|
|
127
|
+
controls: explicitControls(story.argTypes, annotations[exportName], annotations.default, preview),
|
|
128
|
+
}));
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const withoutDuplicateIds = (entries: StoryEntry[], errors: StoryLoadError[]): StoryEntry[] => {
|
|
132
|
+
const counts: Map<string, number> = new Map();
|
|
133
|
+
|
|
134
|
+
for (const entry of entries) {
|
|
135
|
+
counts.set(entry.id, (counts.get(entry.id) ?? 0) + 1);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return entries.filter((entry) => {
|
|
139
|
+
if (counts.get(entry.id) === 1) {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
errors.push({ source: entry.source, error: new Error(`Duplicate story ID: ${entry.id}`) });
|
|
144
|
+
|
|
145
|
+
return false;
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const collectSources = (loaded: LoadedSource[]) => {
|
|
150
|
+
const cache: Map<string, CachedStories> = new Map();
|
|
151
|
+
const entries: StoryEntry[] = [];
|
|
152
|
+
const errors: StoryLoadError[] = [];
|
|
153
|
+
|
|
154
|
+
for (const result of loaded) {
|
|
155
|
+
if ("error" in result) {
|
|
156
|
+
errors.push(result);
|
|
157
|
+
} else {
|
|
158
|
+
cache.set(result.source.id, result.cached);
|
|
159
|
+
entries.push(...result.cached.entries);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return { cache, stories: withoutDuplicateIds(entries, errors), errors };
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const createSourceCache = (): Map<string, CachedStories> => new Map();
|
|
167
|
+
|
|
168
|
+
const loadSource = async (
|
|
169
|
+
source: StorySource,
|
|
170
|
+
preview: Preview,
|
|
171
|
+
getCache: () => Map<string, CachedStories>,
|
|
172
|
+
): Promise<LoadedSource> => {
|
|
173
|
+
try {
|
|
174
|
+
const module = await source.load();
|
|
175
|
+
const previous = getCache().get(source.id);
|
|
176
|
+
const cached = previous !== undefined && previous.module === module &&
|
|
177
|
+
previous.title === source.title && previous.preview === preview
|
|
178
|
+
? previous
|
|
179
|
+
: { module, title: source.title, preview, entries: composeSource(source, module, preview) };
|
|
180
|
+
|
|
181
|
+
return { source, cached };
|
|
182
|
+
} catch (error) {
|
|
183
|
+
return { source: source.id, error: normalizeError(error) };
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/** Loads CSF modules and publishes subscribable explorer snapshots. */
|
|
188
|
+
class StoryCatalog {
|
|
189
|
+
private snapshot: StoryCatalogSnapshot = { stories: [], errors: [], isLoading: false };
|
|
190
|
+
private readonly listeners: Set<() => void> = new Set();
|
|
191
|
+
private readonly loadFailures: WeakSet<Error> = new WeakSet();
|
|
192
|
+
private cache = createSourceCache();
|
|
193
|
+
private sessionError: StoryLoadError | undefined;
|
|
194
|
+
private revision = 0;
|
|
195
|
+
|
|
196
|
+
/** Returns the current snapshot, retaining its identity until the next update. */
|
|
197
|
+
getSnapshot = (): StoryCatalogSnapshot => this.snapshot;
|
|
198
|
+
|
|
199
|
+
/** Registers a snapshot listener and returns a function that unsubscribes it. */
|
|
200
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
201
|
+
this.listeners.add(listener);
|
|
202
|
+
|
|
203
|
+
return () => {
|
|
204
|
+
this.listeners.delete(listener);
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
private publish(snapshot: StoryCatalogSnapshot): void {
|
|
209
|
+
this.snapshot = snapshot;
|
|
210
|
+
|
|
211
|
+
for (const listener of this.listeners) {
|
|
212
|
+
listener();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Replaces the catalog with stories composed from the supplied sources and preview.
|
|
218
|
+
* Only the latest load publishes results; unchanged module identities reuse composed stories.
|
|
219
|
+
* Rejects with an AggregateError after publishing healthy stories when any source fails.
|
|
220
|
+
*/
|
|
221
|
+
async load(sources: StorySource[], preview: Preview = EMPTY_PREVIEW): Promise<void> {
|
|
222
|
+
const revision = ++this.revision;
|
|
223
|
+
this.publish({ ...this.snapshot, isLoading: true });
|
|
224
|
+
const loaded = await Promise.all(sources.map((source) => loadSource(source, preview, () => this.cache)));
|
|
225
|
+
|
|
226
|
+
if (revision !== this.revision) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const { cache, stories, errors } = collectSources(loaded);
|
|
231
|
+
this.cache = cache;
|
|
232
|
+
this.sessionError = undefined;
|
|
233
|
+
this.publish({ stories, errors, isLoading: false });
|
|
234
|
+
|
|
235
|
+
if (errors.length > 0) {
|
|
236
|
+
const failure = new AggregateError(errors.map(({ error }) => error), "Some stories could not be loaded");
|
|
237
|
+
this.loadFailures.add(failure);
|
|
238
|
+
throw failure;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Replaces the current session failure while preserving source errors and superseding pending loads.
|
|
244
|
+
* Ignores aggregate failures already published by this catalog's load operation.
|
|
245
|
+
*/
|
|
246
|
+
reportError(cause: unknown): void {
|
|
247
|
+
if (cause instanceof Error && this.loadFailures.has(cause)) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
this.revision++;
|
|
252
|
+
const errors = this.snapshot.errors.filter((entry) => entry !== this.sessionError);
|
|
253
|
+
this.sessionError = { source: "Storybook", error: normalizeError(cause) };
|
|
254
|
+
this.publish({
|
|
255
|
+
...this.snapshot,
|
|
256
|
+
isLoading: false,
|
|
257
|
+
errors: [...errors, this.sessionError],
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export { StoryCatalog };
|
|
263
|
+
export type { StoryCatalogSnapshot, StoryEntry, StoryLoadError, StorySource };
|
package/src/compose.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createElement } from "react";
|
|
2
|
+
import type {
|
|
3
|
+
Args,
|
|
4
|
+
ComponentMeta,
|
|
5
|
+
ComposedStories,
|
|
6
|
+
ComposedStory,
|
|
7
|
+
Preview,
|
|
8
|
+
StoryAnnotations,
|
|
9
|
+
StoryModule,
|
|
10
|
+
} from "./types.js";
|
|
11
|
+
import { composeStoryAnnotations, isExportStory } from "./upstream.js";
|
|
12
|
+
|
|
13
|
+
const requireObject = (value: unknown): void => {
|
|
14
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
15
|
+
throw new TypeError("Expected a CSF3 annotation object");
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Composes a CSF3 story into a native React component with resolved defaults and decorators.
|
|
21
|
+
* Compose outside render to preserve component identity. Rendering props override the composed args.
|
|
22
|
+
* This function does not create an application, window, or Storybook preview lifecycle.
|
|
23
|
+
*
|
|
24
|
+
* @param story The named story's annotations.
|
|
25
|
+
* @param meta The module's default component metadata.
|
|
26
|
+
* @param preview Shared project annotations, scoped to this composition.
|
|
27
|
+
* @param exportName Export name used for the story identifier and default display name.
|
|
28
|
+
* @returns A renderable component exposing its composed annotations.
|
|
29
|
+
* @throws If an annotation is not an object or no component or render function is available.
|
|
30
|
+
*/
|
|
31
|
+
const composeStory = <TArgs extends object>(
|
|
32
|
+
story: StoryAnnotations<NoInfer<TArgs>>,
|
|
33
|
+
meta: ComponentMeta<TArgs>,
|
|
34
|
+
preview: Preview = {},
|
|
35
|
+
exportName?: string,
|
|
36
|
+
): ComposedStory<TArgs> => {
|
|
37
|
+
requireObject(story);
|
|
38
|
+
requireObject(meta);
|
|
39
|
+
requireObject(preview);
|
|
40
|
+
|
|
41
|
+
if (!story.render && !meta.render && !preview.render && !meta.component) {
|
|
42
|
+
throw new TypeError("A story needs a component or render function");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return composeStoryAnnotations(story, { ...meta }, preview, {
|
|
46
|
+
render: (args) => {
|
|
47
|
+
if (!meta.component) {
|
|
48
|
+
throw new TypeError("A story needs a component or render function");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return createElement(meta.component, args);
|
|
52
|
+
},
|
|
53
|
+
}, exportName);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Composes the selected CSF3 exports of a module into native React components.
|
|
58
|
+
* The default export supplies metadata; its includeStories and excludeStories select named exports.
|
|
59
|
+
* Returned keys retain the original export names.
|
|
60
|
+
*
|
|
61
|
+
* @param stories A story module containing default metadata and named story objects.
|
|
62
|
+
* @param preview Shared project annotations, scoped to the returned compositions.
|
|
63
|
+
* @returns Composed components keyed by the selected export names.
|
|
64
|
+
* @throws If metadata or a selected export is invalid, or a selected story has no renderer.
|
|
65
|
+
*/
|
|
66
|
+
const composeStories = <TModule extends StoryModule>(
|
|
67
|
+
stories: TModule,
|
|
68
|
+
preview: Preview = {},
|
|
69
|
+
): ComposedStories<TModule> => {
|
|
70
|
+
requireObject(stories);
|
|
71
|
+
requireObject(stories.default);
|
|
72
|
+
requireObject(preview);
|
|
73
|
+
|
|
74
|
+
const meta = stories.default as ComponentMeta<Args>;
|
|
75
|
+
const composed: Partial<ComposedStories<TModule>> = {};
|
|
76
|
+
|
|
77
|
+
for (const [exportName, story] of Object.entries(stories)) {
|
|
78
|
+
if (exportName === "default" || exportName === "__namedExportsOrder" || !isExportStory(exportName, meta)) {
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
requireObject(story);
|
|
83
|
+
Object.defineProperty(composed, exportName, {
|
|
84
|
+
value: composeStory(story as StoryAnnotations<Args>, meta, preview, exportName),
|
|
85
|
+
enumerable: true,
|
|
86
|
+
configurable: true,
|
|
87
|
+
writable: true,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return composed as ComposedStories<TModule>;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export { composeStory, composeStories };
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Story discovery and preview configuration for the native explorer. */
|
|
2
|
+
type StorybookConfig = {
|
|
3
|
+
/** Project-relative globs; defaults to CSF story files under src. */
|
|
4
|
+
stories?: string[];
|
|
5
|
+
/** Additional project-relative globs excluded from discovery. */
|
|
6
|
+
exclude?: string[];
|
|
7
|
+
/** Project-relative preview module; defaults to a discovered .storybook/preview file. */
|
|
8
|
+
preview?: string;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** Returns a typed explorer configuration without changing it or resolving its paths. */
|
|
12
|
+
const defineConfig = (config: StorybookConfig): StorybookConfig => config;
|
|
13
|
+
|
|
14
|
+
export { defineConfig, type StorybookConfig };
|
package/src/controls.tsx
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import { ComboRow } from "@gtkx/components";
|
|
3
|
+
import { markupEscapeText } from "@gtkx/gi/glib";
|
|
4
|
+
import { AdwActionRow, AdwEntryRow, AdwPreferencesGroup, AdwSpinRow, AdwSwitchRow } from "@gtkx/jsx/adw";
|
|
5
|
+
import { GtkAdjustment } from "@gtkx/jsx/gtk";
|
|
6
|
+
import type { Args, ArgTypes } from "./types.js";
|
|
7
|
+
|
|
8
|
+
type ControlsProps = { argTypes: ArgTypes; args: Args; onChange: (update: Args) => void };
|
|
9
|
+
|
|
10
|
+
type ControlProps = {
|
|
11
|
+
argument: string;
|
|
12
|
+
title: string;
|
|
13
|
+
value: unknown;
|
|
14
|
+
type: string;
|
|
15
|
+
settings: Args;
|
|
16
|
+
options: unknown;
|
|
17
|
+
isDisabled: boolean;
|
|
18
|
+
onChange: (update: Args) => void;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const isObject = (value: unknown): value is Args =>
|
|
22
|
+
value !== null && typeof value === "object" && !Array.isArray(value);
|
|
23
|
+
|
|
24
|
+
const isWithinBoundsOrAbsent = (value: unknown, min: number, max: number): boolean =>
|
|
25
|
+
value === undefined || (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max);
|
|
26
|
+
|
|
27
|
+
const controlTitle = (name: unknown, argument: string): string => typeof name === "string" ? name : argument;
|
|
28
|
+
|
|
29
|
+
const numberDigits = (step: number): number => {
|
|
30
|
+
const [coefficient = "", exponent = "0"] = String(step).split("e", 2);
|
|
31
|
+
const fraction = coefficient.split(".", 2)[1]?.length ?? 0;
|
|
32
|
+
const digits = Math.max(0, fraction - Number(exponent));
|
|
33
|
+
|
|
34
|
+
return Math.min(20, digits);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const UnsupportedControl = ({ title, description }: { title: string; description: string }): ReactNode => (
|
|
38
|
+
<AdwActionRow title={markupEscapeText(title, -1)} subtitle={markupEscapeText(description, -1)} sensitive={false} />
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
const NumberControl = ({
|
|
42
|
+
argument,
|
|
43
|
+
title,
|
|
44
|
+
value,
|
|
45
|
+
settings,
|
|
46
|
+
isDisabled,
|
|
47
|
+
onChange,
|
|
48
|
+
}: Omit<ControlProps, "type" | "options">): ReactNode => {
|
|
49
|
+
const min = settings.min ?? -Number.MAX_SAFE_INTEGER;
|
|
50
|
+
const max = settings.max ?? Number.MAX_SAFE_INTEGER;
|
|
51
|
+
const step = settings.step ?? 1;
|
|
52
|
+
|
|
53
|
+
if (
|
|
54
|
+
typeof min !== "number" || typeof max !== "number" || typeof step !== "number" ||
|
|
55
|
+
!Number.isFinite(min) || !Number.isFinite(max) || !Number.isFinite(step) ||
|
|
56
|
+
step <= 0 || min > max || !isWithinBoundsOrAbsent(value, min, max)
|
|
57
|
+
) {
|
|
58
|
+
return <UnsupportedControl title={title} description="Provide a finite number and valid bounds." />;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const currentValue = typeof value === "number" ? value : Math.max(min, Math.min(0, max));
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<AdwSpinRow
|
|
65
|
+
name={`storybook-control-${argument}`}
|
|
66
|
+
title={markupEscapeText(title, -1)}
|
|
67
|
+
sensitive={!isDisabled}
|
|
68
|
+
value={currentValue}
|
|
69
|
+
digits={numberDigits(step)}
|
|
70
|
+
numeric
|
|
71
|
+
widthChars={8}
|
|
72
|
+
adjustment={(
|
|
73
|
+
<GtkAdjustment
|
|
74
|
+
lower={min}
|
|
75
|
+
upper={max}
|
|
76
|
+
stepIncrement={step}
|
|
77
|
+
pageIncrement={Math.min(Number.MAX_VALUE, step * 10)}
|
|
78
|
+
value={currentValue}
|
|
79
|
+
/>
|
|
80
|
+
)}
|
|
81
|
+
onNotifyValue={(next) => {
|
|
82
|
+
if (
|
|
83
|
+
typeof next === "number" && Number.isFinite(next) &&
|
|
84
|
+
next >= min && next <= max && !Object.is(next, value)
|
|
85
|
+
) {
|
|
86
|
+
onChange({ [argument]: next });
|
|
87
|
+
}
|
|
88
|
+
}}
|
|
89
|
+
/>
|
|
90
|
+
);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const SelectControl = (props: Omit<ControlProps, "type">): ReactNode => {
|
|
94
|
+
const { argument, title, value, options, settings, isDisabled, onChange } = props;
|
|
95
|
+
if (!Array.isArray(options) || options.length === 0 || options.some((option: unknown) =>
|
|
96
|
+
option !== null && typeof option !== "string" && typeof option !== "number" && typeof option !== "boolean")) {
|
|
97
|
+
return <UnsupportedControl title={title} description="Provide a list of text, number, or boolean options." />;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const values: unknown[] = options;
|
|
101
|
+
const selected = values.findIndex((option) => Object.is(option, value));
|
|
102
|
+
const labels = isObject(settings.labels) ? settings.labels : {};
|
|
103
|
+
const items = values.map((option, index) => {
|
|
104
|
+
const label = labels[String(option)];
|
|
105
|
+
|
|
106
|
+
return { id: String(index), value: typeof label === "string" ? label : String(option) };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
return (
|
|
110
|
+
<ComboRow
|
|
111
|
+
name={`storybook-control-${argument}`}
|
|
112
|
+
title={markupEscapeText(title, -1)}
|
|
113
|
+
sensitive={!isDisabled}
|
|
114
|
+
items={items}
|
|
115
|
+
selectedId={selected === -1 ? null : String(selected)}
|
|
116
|
+
onSelectionChanged={(id) => {
|
|
117
|
+
const index = Number(id);
|
|
118
|
+
|
|
119
|
+
if (Number.isSafeInteger(index) && index >= 0 && index < values.length) {
|
|
120
|
+
onChange({ [argument]: values[index] });
|
|
121
|
+
}
|
|
122
|
+
}}
|
|
123
|
+
/>
|
|
124
|
+
);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const Control = (props: ControlProps): ReactNode => {
|
|
128
|
+
const { argument, title, value, type, isDisabled, onChange } = props;
|
|
129
|
+
|
|
130
|
+
switch (type) {
|
|
131
|
+
case "boolean": {
|
|
132
|
+
return (
|
|
133
|
+
<AdwSwitchRow
|
|
134
|
+
name={`storybook-control-${argument}`}
|
|
135
|
+
title={markupEscapeText(title, -1)}
|
|
136
|
+
sensitive={!isDisabled}
|
|
137
|
+
active={value === true}
|
|
138
|
+
onNotifyActive={(active) => {
|
|
139
|
+
if (typeof active === "boolean" && !Object.is(active, value)) {
|
|
140
|
+
onChange({ [argument]: active });
|
|
141
|
+
}
|
|
142
|
+
}}
|
|
143
|
+
/>
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
case "text": {
|
|
147
|
+
return (
|
|
148
|
+
<AdwEntryRow
|
|
149
|
+
name={`storybook-control-${argument}`}
|
|
150
|
+
title={markupEscapeText(title, -1)}
|
|
151
|
+
sensitive={!isDisabled}
|
|
152
|
+
text={typeof value === "string" ? value : ""}
|
|
153
|
+
onNotifyText={(text) => {
|
|
154
|
+
if (typeof text === "string" && !Object.is(text, value)) {
|
|
155
|
+
onChange({ [argument]: text });
|
|
156
|
+
}
|
|
157
|
+
}}
|
|
158
|
+
/>
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
case "number":
|
|
162
|
+
case "range": {
|
|
163
|
+
return <NumberControl {...props} />;
|
|
164
|
+
}
|
|
165
|
+
case "select":
|
|
166
|
+
case "radio":
|
|
167
|
+
case "inline-radio": {
|
|
168
|
+
return <SelectControl {...props} />;
|
|
169
|
+
}
|
|
170
|
+
default: {
|
|
171
|
+
return <UnsupportedControl title={title} description={`Unsupported control: ${type}`} />;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const Controls = ({ argTypes, args, onChange }: ControlsProps): ReactNode => (
|
|
177
|
+
<AdwPreferencesGroup title="Controls">
|
|
178
|
+
{Object.entries(argTypes).map(([argument, annotation]) => {
|
|
179
|
+
const control: unknown = annotation?.control;
|
|
180
|
+
const table: unknown = annotation?.table;
|
|
181
|
+
|
|
182
|
+
if (control === undefined || control === false || (isObject(table) && table.disable === true)) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const settings = isObject(control) ? control : {};
|
|
187
|
+
const type = typeof control === "string" ? control : settings.type;
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<Control
|
|
191
|
+
key={argument}
|
|
192
|
+
argument={argument}
|
|
193
|
+
title={controlTitle(annotation?.name, argument)}
|
|
194
|
+
value={args[argument]}
|
|
195
|
+
type={typeof type === "string" ? type : "unknown"}
|
|
196
|
+
settings={settings}
|
|
197
|
+
options={annotation?.options}
|
|
198
|
+
isDisabled={settings.disable === true}
|
|
199
|
+
onChange={onChange}
|
|
200
|
+
/>
|
|
201
|
+
);
|
|
202
|
+
})}
|
|
203
|
+
</AdwPreferencesGroup>
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
export { Controls };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import { markupEscapeText } from "@gtkx/gi/glib";
|
|
3
|
+
import * as Gtk from "@gtkx/gi/gtk";
|
|
4
|
+
import { AdwActionRow, AdwStatusPage } from "@gtkx/jsx/adw";
|
|
5
|
+
import { GtkBox, GtkLabel, GtkListBox, GtkScrolledWindow, GtkSearchEntry } from "@gtkx/jsx/gtk";
|
|
6
|
+
import { useState } from "react";
|
|
7
|
+
import type { StoryEntry, StoryLoadError } from "./catalog.js";
|
|
8
|
+
|
|
9
|
+
type NavigatorProps = {
|
|
10
|
+
stories: StoryEntry[];
|
|
11
|
+
errors: StoryLoadError[];
|
|
12
|
+
selectedId: string | undefined;
|
|
13
|
+
onSelect: (id: string) => void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
type GroupProps = Pick<NavigatorProps, "selectedId" | "onSelect"> & {
|
|
17
|
+
title: string;
|
|
18
|
+
entries: StoryEntry[];
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const StoryGroup = ({ title, entries, selectedId, onSelect }: GroupProps): ReactNode => (
|
|
22
|
+
<GtkBox orientation={Gtk.Orientation.VERTICAL} spacing={6}>
|
|
23
|
+
<GtkLabel
|
|
24
|
+
label={title}
|
|
25
|
+
xalign={0}
|
|
26
|
+
marginStart={18}
|
|
27
|
+
marginEnd={18}
|
|
28
|
+
cssClasses={["heading"]}
|
|
29
|
+
wrap
|
|
30
|
+
/>
|
|
31
|
+
<GtkListBox
|
|
32
|
+
cssClasses={["navigation-sidebar"]}
|
|
33
|
+
selectedIndex={entries.findIndex((entry) => entry.id === selectedId)}
|
|
34
|
+
onRowSelected={(row) => {
|
|
35
|
+
const entry = row === null ? undefined : entries[row.getIndex()];
|
|
36
|
+
|
|
37
|
+
if (entry) {
|
|
38
|
+
onSelect(entry.id);
|
|
39
|
+
}
|
|
40
|
+
}}
|
|
41
|
+
>
|
|
42
|
+
{entries.map((entry) => (
|
|
43
|
+
<AdwActionRow
|
|
44
|
+
key={entry.id}
|
|
45
|
+
name={`storybook-story-${entry.id}`}
|
|
46
|
+
title={markupEscapeText(entry.name, -1)}
|
|
47
|
+
activatable
|
|
48
|
+
onActivated={() => {
|
|
49
|
+
onSelect(entry.id);
|
|
50
|
+
}}
|
|
51
|
+
/>
|
|
52
|
+
))}
|
|
53
|
+
</GtkListBox>
|
|
54
|
+
</GtkBox>
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
const LoadErrors = ({ errors }: Pick<NavigatorProps, "errors">): ReactNode => errors.length > 0 && (
|
|
58
|
+
<GtkBox name="storybook-load-errors" orientation={Gtk.Orientation.VERTICAL} spacing={6}>
|
|
59
|
+
{errors.map(({ source, error }, index) => (
|
|
60
|
+
<GtkLabel
|
|
61
|
+
key={`${source}-${String(index)}`}
|
|
62
|
+
label={`${source}\n${error.message.slice(0, 500)}`}
|
|
63
|
+
cssClasses={["error"]}
|
|
64
|
+
marginStart={18}
|
|
65
|
+
marginEnd={18}
|
|
66
|
+
wrap
|
|
67
|
+
selectable
|
|
68
|
+
xalign={0}
|
|
69
|
+
/>
|
|
70
|
+
))}
|
|
71
|
+
</GtkBox>
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
const StoryNavigator = ({ stories, errors, selectedId, onSelect }: NavigatorProps): ReactNode => {
|
|
75
|
+
const [search, setSearch] = useState("");
|
|
76
|
+
const query = search.trim().toLocaleLowerCase();
|
|
77
|
+
const groups = Map.groupBy(
|
|
78
|
+
stories.filter((entry) => `${entry.title} ${entry.name}`.toLocaleLowerCase().includes(query)),
|
|
79
|
+
(entry) => entry.title,
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
<GtkBox orientation={Gtk.Orientation.VERTICAL} spacing={12}>
|
|
84
|
+
<GtkSearchEntry
|
|
85
|
+
name="storybook-search"
|
|
86
|
+
placeholderText="Search stories"
|
|
87
|
+
text={search}
|
|
88
|
+
marginStart={12}
|
|
89
|
+
marginEnd={12}
|
|
90
|
+
onChanged={(entry) => {
|
|
91
|
+
setSearch(entry.getText());
|
|
92
|
+
}}
|
|
93
|
+
/>
|
|
94
|
+
<GtkScrolledWindow hscrollbarPolicy={Gtk.PolicyType.NEVER} vexpand>
|
|
95
|
+
<GtkBox orientation={Gtk.Orientation.VERTICAL} spacing={18} marginBottom={18}>
|
|
96
|
+
{[...groups].map(([title, entries]) => (
|
|
97
|
+
<StoryGroup
|
|
98
|
+
key={title}
|
|
99
|
+
title={title}
|
|
100
|
+
entries={entries}
|
|
101
|
+
selectedId={selectedId}
|
|
102
|
+
onSelect={onSelect}
|
|
103
|
+
/>
|
|
104
|
+
))}
|
|
105
|
+
{groups.size === 0 && (
|
|
106
|
+
<AdwStatusPage
|
|
107
|
+
name="storybook-no-matches"
|
|
108
|
+
title={query ? "No matching stories" : "No stories"}
|
|
109
|
+
iconName="system-search-symbolic"
|
|
110
|
+
cssClasses={["compact"]}
|
|
111
|
+
/>
|
|
112
|
+
)}
|
|
113
|
+
<LoadErrors errors={errors} />
|
|
114
|
+
</GtkBox>
|
|
115
|
+
</GtkScrolledWindow>
|
|
116
|
+
</GtkBox>
|
|
117
|
+
);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
export { StoryNavigator };
|