@storybook/angular 10.1.0-alpha.8 → 10.1.0-beta.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.
@@ -1,939 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
- var __export = (target, all) => {
5
- for (var name in all)
6
- __defProp(target, name, { get: all[name], enumerable: true });
7
- };
8
- var __decorateClass = (decorators, target, key, kind) => {
9
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
11
- if (decorator = decorators[i])
12
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
13
- if (kind && result) __defProp(target, key, result);
14
- return result;
15
- };
16
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
17
-
18
- // src/client/render.ts
19
- var render_exports = {};
20
- __export(render_exports, {
21
- render: () => render,
22
- renderToCanvas: () => renderToCanvas,
23
- rendererFactory: () => rendererFactory
24
- });
25
- import "@angular/compiler";
26
-
27
- // src/client/angular-beta/AbstractRenderer.ts
28
- import { bootstrapApplication } from "@angular/platform-browser";
29
- import { BehaviorSubject } from "rxjs";
30
- import { stringify } from "telejson";
31
-
32
- // src/client/angular-beta/utils/NgComponentAnalyzer.ts
33
- import {
34
- Component,
35
- Directive,
36
- Input,
37
- Output,
38
- Pipe,
39
- \u0275ReflectionCapabilities as ReflectionCapabilities
40
- } from "@angular/core";
41
- var reflectionCapabilities = new ReflectionCapabilities();
42
- var getComponentInputsOutputs = /* @__PURE__ */ __name((component) => {
43
- const componentMetadata = getComponentDecoratorMetadata(component);
44
- const componentPropsMetadata = getComponentPropsDecoratorMetadata(component);
45
- const initialValue = {
46
- inputs: [],
47
- outputs: []
48
- };
49
- if (componentMetadata && componentMetadata.inputs) {
50
- initialValue.inputs.push(
51
- ...componentMetadata.inputs.map((i) => ({
52
- propName: typeof i === "string" ? i : i.name,
53
- templateName: typeof i === "string" ? i : i.alias
54
- }))
55
- );
56
- }
57
- if (componentMetadata && componentMetadata.outputs) {
58
- initialValue.outputs.push(
59
- ...componentMetadata.outputs.map((i) => ({ propName: i, templateName: i }))
60
- );
61
- }
62
- if (!componentPropsMetadata) {
63
- return initialValue;
64
- }
65
- return Object.entries(componentPropsMetadata).reduce((previousValue, [propertyName, values]) => {
66
- const value = values.find((v) => v instanceof Input || v instanceof Output);
67
- if (value instanceof Input) {
68
- const inputToAdd = {
69
- propName: propertyName,
70
- templateName: value.bindingPropertyName ?? value.alias ?? propertyName
71
- };
72
- const previousInputsFiltered = previousValue.inputs.filter(
73
- (i) => i.templateName !== propertyName
74
- );
75
- return {
76
- ...previousValue,
77
- inputs: [...previousInputsFiltered, inputToAdd]
78
- };
79
- }
80
- if (value instanceof Output) {
81
- const outputToAdd = {
82
- propName: propertyName,
83
- templateName: value.bindingPropertyName ?? value.alias ?? propertyName
84
- };
85
- const previousOutputsFiltered = previousValue.outputs.filter(
86
- (i) => i.templateName !== propertyName
87
- );
88
- return {
89
- ...previousValue,
90
- outputs: [...previousOutputsFiltered, outputToAdd]
91
- };
92
- }
93
- return previousValue;
94
- }, initialValue);
95
- }, "getComponentInputsOutputs");
96
- var isComponent = /* @__PURE__ */ __name((component) => {
97
- if (!component) {
98
- return false;
99
- }
100
- const decorators = reflectionCapabilities.annotations(component);
101
- return (decorators || []).some((d) => d instanceof Component);
102
- }, "isComponent");
103
- var getComponentPropsDecoratorMetadata = /* @__PURE__ */ __name((component) => {
104
- return reflectionCapabilities.propMetadata(component);
105
- }, "getComponentPropsDecoratorMetadata");
106
- var getComponentDecoratorMetadata = /* @__PURE__ */ __name((component) => {
107
- const decorators = reflectionCapabilities.annotations(component);
108
- return decorators.reverse().find((d) => d instanceof Component);
109
- }, "getComponentDecoratorMetadata");
110
-
111
- // src/client/angular-beta/ComputesTemplateFromComponent.ts
112
- var isValidIdentifier = /* @__PURE__ */ __name((name) => /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name), "isValidIdentifier");
113
- var formatPropInTemplate = /* @__PURE__ */ __name((propertyName) => isValidIdentifier(propertyName) ? propertyName : `this['${propertyName}']`, "formatPropInTemplate");
114
- var separateInputsOutputsAttributes = /* @__PURE__ */ __name((ngComponentInputsOutputs, props = {}) => {
115
- const inputs = ngComponentInputsOutputs.inputs.filter((i) => i.templateName in props).map((i) => i.templateName);
116
- const outputs = ngComponentInputsOutputs.outputs.filter((o) => o.templateName in props).map((o) => o.templateName);
117
- return {
118
- inputs,
119
- outputs,
120
- otherProps: Object.keys(props).filter((k) => ![...inputs, ...outputs].includes(k))
121
- };
122
- }, "separateInputsOutputsAttributes");
123
- var computesTemplateFromComponent = /* @__PURE__ */ __name((component, initialProps, innerTemplate = "") => {
124
- const ngComponentMetadata = getComponentDecoratorMetadata(component);
125
- const ngComponentInputsOutputs = getComponentInputsOutputs(component);
126
- if (!ngComponentMetadata.selector) {
127
- return `<ng-container *ngComponentOutlet="storyComponent"></ng-container>`;
128
- }
129
- const { inputs: initialInputs, outputs: initialOutputs } = separateInputsOutputsAttributes(
130
- ngComponentInputsOutputs,
131
- initialProps
132
- );
133
- const templateInputs = initialInputs.length > 0 ? ` ${initialInputs.map((i) => `[${i}]="${formatPropInTemplate(i)}"`).join(" ")}` : "";
134
- const templateOutputs = initialOutputs.length > 0 ? ` ${initialOutputs.map((i) => `(${i})="${formatPropInTemplate(i)}($event)"`).join(" ")}` : "";
135
- return buildTemplate(
136
- ngComponentMetadata.selector,
137
- innerTemplate,
138
- templateInputs,
139
- templateOutputs
140
- );
141
- }, "computesTemplateFromComponent");
142
- function stringifyCircular(obj) {
143
- const seen = /* @__PURE__ */ new Set();
144
- return JSON.stringify(obj, (key, value) => {
145
- if (typeof value === "object" && value !== null) {
146
- if (seen.has(value)) {
147
- return "[Circular]";
148
- }
149
- seen.add(value);
150
- }
151
- return value;
152
- });
153
- }
154
- __name(stringifyCircular, "stringifyCircular");
155
- var createAngularInputProperty = /* @__PURE__ */ __name(({
156
- propertyName,
157
- value,
158
- argType
159
- }) => {
160
- let templateValue;
161
- switch (typeof value) {
162
- case "string":
163
- templateValue = `'${value}'`;
164
- break;
165
- case "object":
166
- templateValue = stringifyCircular(value).replace(/'/g, "\u2019").replace(/\\"/g, "\u201D").replace(/"([^-"]+)":/g, "$1: ").replace(/"/g, "'").replace(/\u2019/g, "\\'").replace(/\u201D/g, "\\'").split(",").join(", ");
167
- break;
168
- default:
169
- templateValue = value;
170
- }
171
- return `[${propertyName}]="${templateValue}"`;
172
- }, "createAngularInputProperty");
173
- var computesTemplateSourceFromComponent = /* @__PURE__ */ __name((component, initialProps, argTypes) => {
174
- const ngComponentMetadata = getComponentDecoratorMetadata(component);
175
- if (!ngComponentMetadata) {
176
- return null;
177
- }
178
- if (!ngComponentMetadata.selector) {
179
- return `<ng-container *ngComponentOutlet="${component.name}"></ng-container>`;
180
- }
181
- const ngComponentInputsOutputs = getComponentInputsOutputs(component);
182
- const { inputs: initialInputs, outputs: initialOutputs } = separateInputsOutputsAttributes(
183
- ngComponentInputsOutputs,
184
- initialProps
185
- );
186
- const templateInputs = initialInputs.length > 0 ? ` ${initialInputs.map(
187
- (propertyName) => createAngularInputProperty({
188
- propertyName,
189
- value: initialProps[propertyName],
190
- argType: argTypes?.[propertyName]
191
- })
192
- ).join(" ")}` : "";
193
- const templateOutputs = initialOutputs.length > 0 ? ` ${initialOutputs.map((i) => `(${i})="${formatPropInTemplate(i)}($event)"`).join(" ")}` : "";
194
- return buildTemplate(ngComponentMetadata.selector, "", templateInputs, templateOutputs);
195
- }, "computesTemplateSourceFromComponent");
196
- var buildTemplate = /* @__PURE__ */ __name((selector, innerTemplate, inputs, outputs) => {
197
- const voidElements = [
198
- "area",
199
- "base",
200
- "br",
201
- "col",
202
- "command",
203
- "embed",
204
- "hr",
205
- "img",
206
- "input",
207
- "keygen",
208
- "link",
209
- "meta",
210
- "param",
211
- "source",
212
- "track",
213
- "wbr"
214
- ];
215
- const firstSelector = selector.split(",")[0];
216
- const templateReplacers = [
217
- [/(^.*?)(?=[,])/, "$1"],
218
- [/(^\..+)/, "div$1"],
219
- [/(^\[.+?])/, "div$1"],
220
- [/([\w[\]]+)(\s*,[\w\s-[\],]+)+/, `$1`],
221
- [/#([\w-]+)/, ` id="$1"`],
222
- [/((\.[\w-]+)+)/, (_, c) => ` class="${c.split`.`.join` `.trim()}"`],
223
- [/(\[.+?])/g, (_, a) => ` ${a.slice(1, -1)}`],
224
- [
225
- /([\S]+)(.*)/,
226
- (template, elementSelector) => {
227
- return voidElements.some((element) => elementSelector === element) ? template.replace(/([\S]+)(.*)/, `<$1$2${inputs}${outputs} />`) : template.replace(/([\S]+)(.*)/, `<$1$2${inputs}${outputs}>${innerTemplate}</$1>`);
228
- }
229
- ]
230
- ];
231
- return templateReplacers.reduce(
232
- (prevSelector, [searchValue, replacer]) => prevSelector.replace(searchValue, replacer),
233
- firstSelector
234
- );
235
- }, "buildTemplate");
236
-
237
- // src/client/angular-beta/StorybookWrapperComponent.ts
238
- import {
239
- ChangeDetectorRef,
240
- Component as Component3,
241
- Inject,
242
- NgModule as NgModule2,
243
- ViewChild,
244
- ViewContainerRef
245
- } from "@angular/core";
246
- import { map, skip } from "rxjs/operators";
247
-
248
- // src/client/angular-beta/StorybookProvider.ts
249
- import { InjectionToken, NgZone } from "@angular/core";
250
- import { Observable } from "rxjs";
251
- var STORY_PROPS = new InjectionToken("STORY_PROPS");
252
- var storyPropsProvider = /* @__PURE__ */ __name((storyProps$) => ({
253
- provide: STORY_PROPS,
254
- useFactory: storyDataFactory(storyProps$.asObservable()),
255
- deps: [NgZone]
256
- }), "storyPropsProvider");
257
- function storyDataFactory(data) {
258
- return (ngZone) => new Observable((subscriber) => {
259
- const sub = data.subscribe(
260
- (v) => {
261
- ngZone.run(() => subscriber.next(v));
262
- },
263
- (err) => {
264
- ngZone.run(() => subscriber.error(err));
265
- },
266
- () => {
267
- ngZone.run(() => subscriber.complete());
268
- }
269
- );
270
- return () => {
271
- sub.unsubscribe();
272
- };
273
- });
274
- }
275
- __name(storyDataFactory, "storyDataFactory");
276
-
277
- // src/client/angular-beta/utils/PropertyExtractor.ts
278
- import { CommonModule } from "@angular/common";
279
- import {
280
- Component as Component2,
281
- Directive as Directive2,
282
- Injectable,
283
- InjectionToken as InjectionToken2,
284
- Input as Input2,
285
- Output as Output2,
286
- Pipe as Pipe2,
287
- \u0275ReflectionCapabilities as ReflectionCapabilities3,
288
- VERSION
289
- } from "@angular/core";
290
- import { BrowserModule } from "@angular/platform-browser";
291
- import { dedent } from "ts-dedent";
292
-
293
- // src/client/angular-beta/utils/NgModulesAnalyzer.ts
294
- import { NgModule, \u0275ReflectionCapabilities as ReflectionCapabilities2 } from "@angular/core";
295
- var reflectionCapabilities2 = new ReflectionCapabilities2();
296
- var isComponentAlreadyDeclared = /* @__PURE__ */ __name((componentToFind, moduleDeclarations, moduleImports) => {
297
- if (moduleDeclarations && moduleDeclarations.flat().some((declaration) => declaration === componentToFind)) {
298
- return true;
299
- }
300
- if (!moduleImports) {
301
- return false;
302
- }
303
- return moduleImports.flat().some((importItem) => {
304
- const extractedNgModuleMetadata = extractNgModuleMetadata(importItem);
305
- if (!extractedNgModuleMetadata) {
306
- return false;
307
- }
308
- return isComponentAlreadyDeclared(
309
- componentToFind,
310
- extractedNgModuleMetadata.declarations,
311
- extractedNgModuleMetadata.imports
312
- );
313
- });
314
- }, "isComponentAlreadyDeclared");
315
- var extractNgModuleMetadata = /* @__PURE__ */ __name((importItem) => {
316
- const target = importItem && importItem.ngModule ? importItem.ngModule : importItem;
317
- const decorators = reflectionCapabilities2.annotations(target);
318
- if (!decorators || decorators.length === 0) {
319
- return null;
320
- }
321
- const ngModuleDecorator = decorators.find(
322
- (decorator) => decorator instanceof NgModule
323
- );
324
- if (!ngModuleDecorator) {
325
- return null;
326
- }
327
- return ngModuleDecorator;
328
- }, "extractNgModuleMetadata");
329
-
330
- // src/client/angular-beta/utils/PropertyExtractor.ts
331
- var reflectionCapabilities3 = new ReflectionCapabilities3();
332
- var REMOVED_MODULES = new InjectionToken2("REMOVED_MODULES");
333
- var uniqueArray = /* @__PURE__ */ __name((arr) => {
334
- return arr.flat(Number.MAX_VALUE).filter(Boolean).filter((value, index, self) => self.indexOf(value) === index);
335
- }, "uniqueArray");
336
- var _PropertyExtractor = class _PropertyExtractor {
337
- constructor(metadata, component) {
338
- this.metadata = metadata;
339
- this.component = component;
340
- this.declarations = [];
341
- /**
342
- * Analyze NgModule Metadata
343
- *
344
- * - Removes Restricted Imports
345
- * - Extracts providers from ModuleWithProviders
346
- * - Returns a new NgModuleMetadata object
347
- */
348
- this.analyzeMetadata = /* @__PURE__ */ __name(async (metadata) => {
349
- const declarations = [...metadata?.declarations || []];
350
- const providers = [...metadata?.providers || []];
351
- const applicationProviders = [];
352
- const imports = await Promise.all(
353
- [...metadata?.imports || []].map(async (imported) => {
354
- const [isRestricted, restrictedProviders] = await _PropertyExtractor.analyzeRestricted(imported);
355
- if (isRestricted) {
356
- applicationProviders.unshift(restrictedProviders || []);
357
- return null;
358
- }
359
- return imported;
360
- })
361
- ).then((results) => results.filter(Boolean));
362
- return { ...metadata, imports, providers, applicationProviders, declarations };
363
- }, "analyzeMetadata");
364
- }
365
- // With the new way of mounting standalone components to the DOM via bootstrapApplication API,
366
- // we should now pass ModuleWithProviders to the providers array of the bootstrapApplication function.
367
- static warnImportsModuleWithProviders(propertyExtractor) {
368
- const hasModuleWithProvidersImport = propertyExtractor.imports.some(
369
- (importedModule) => "ngModule" in importedModule
370
- );
371
- if (hasModuleWithProvidersImport) {
372
- console.warn(
373
- dedent(
374
- `
375
- Storybook Warning:
376
- moduleMetadata property 'imports' contains one or more ModuleWithProviders, likely the result of a 'Module.forRoot()'-style call.
377
- In Storybook 7.0 we use Angular's new 'bootstrapApplication' API to mount the component to the DOM, which accepts a list of providers to set up application-wide providers.
378
- Use the 'applicationConfig' decorator from '@storybook/angular' to pass your ModuleWithProviders to the 'providers' property in combination with the importProvidersFrom helper function from '@angular/core' to extract all the necessary providers.
379
- Visit https://angular.io/guide/standalone-components#configuring-dependency-injection for more information
380
- `
381
- )
382
- );
383
- }
384
- }
385
- async init() {
386
- const analyzed = await this.analyzeMetadata(this.metadata);
387
- this.imports = uniqueArray([CommonModule, analyzed.imports]);
388
- this.providers = uniqueArray(analyzed.providers);
389
- this.applicationProviders = uniqueArray(analyzed.applicationProviders);
390
- this.declarations = uniqueArray(analyzed.declarations);
391
- if (this.component) {
392
- const { isDeclarable, isStandalone } = _PropertyExtractor.analyzeDecorators(this.component);
393
- const isDeclared = isComponentAlreadyDeclared(
394
- this.component,
395
- analyzed.declarations,
396
- this.imports
397
- );
398
- if (isStandalone) {
399
- this.imports.push(this.component);
400
- } else if (isDeclarable && !isDeclared) {
401
- this.declarations.push(this.component);
402
- }
403
- }
404
- }
405
- };
406
- __name(_PropertyExtractor, "PropertyExtractor");
407
- _PropertyExtractor.analyzeRestricted = /* @__PURE__ */ __name(async (ngModule) => {
408
- if (ngModule === BrowserModule) {
409
- console.warn(
410
- dedent`
411
- Storybook Warning:
412
- You have imported the "BrowserModule", which is not necessary anymore.
413
- In Storybook v7.0 we are using Angular's new bootstrapApplication API to mount an Angular application to the DOM.
414
- Note that the BrowserModule providers are automatically included when starting an application with bootstrapApplication()
415
- Please remove the "BrowserModule" from the list of imports in your moduleMetadata definition to remove this warning.
416
- `
417
- );
418
- return [true];
419
- }
420
- try {
421
- const animations = await import("@angular/platform-browser/animations");
422
- if (ngModule === animations.BrowserAnimationsModule) {
423
- console.warn(
424
- dedent`
425
- Storybook Warning:
426
- You have added the "BrowserAnimationsModule" to the list of "imports" in your moduleMetadata definition of your Story.
427
- In Storybook 7.0 we use Angular's new 'bootstrapApplication' API to mount the component to the DOM, which accepts a list of providers to set up application-wide providers.
428
- Use the 'applicationConfig' decorator from '@storybook/angular' and add the "provideAnimations" function to the list of "providers".
429
- If your Angular version does not support "provide-like" functions, use the helper function importProvidersFrom instead to set up animations. For this case, please add "importProvidersFrom(BrowserAnimationsModule)" to the list of providers of your applicationConfig definition.
430
- Please visit https://angular.io/guide/standalone-components#configuring-dependency-injection for more information.
431
- `
432
- );
433
- return [true, animations.provideAnimations()];
434
- }
435
- if (ngModule === animations.NoopAnimationsModule) {
436
- console.warn(
437
- dedent`
438
- Storybook Warning:
439
- You have added the "NoopAnimationsModule" to the list of "imports" in your moduleMetadata definition of your Story.
440
- In Storybook v7.0 we are using Angular's new bootstrapApplication API to mount an Angular application to the DOM, which accepts a list of providers to set up application-wide providers.
441
- Use the 'applicationConfig' decorator from '@storybook/angular' and add the "provideNoopAnimations" function to the list of "providers".
442
- If your Angular version does not support "provide-like" functions, use the helper function importProvidersFrom instead to set up noop animations and to extract all necessary providers from NoopAnimationsModule. For this case, please add "importProvidersFrom(NoopAnimationsModule)" to the list of providers of your applicationConfig definition.
443
- Please visit https://angular.io/guide/standalone-components#configuring-dependency-injection for more information.
444
- `
445
- );
446
- return [true, animations.provideNoopAnimations()];
447
- }
448
- } catch (e) {
449
- return [false];
450
- }
451
- return [false];
452
- }, "analyzeRestricted");
453
- _PropertyExtractor.analyzeDecorators = /* @__PURE__ */ __name((component) => {
454
- const decorators = reflectionCapabilities3.annotations(component);
455
- const isComponent2 = decorators.some((d) => _PropertyExtractor.isDecoratorInstanceOf(d, "Component"));
456
- const isDirective = decorators.some((d) => _PropertyExtractor.isDecoratorInstanceOf(d, "Directive"));
457
- const isPipe = decorators.some((d) => _PropertyExtractor.isDecoratorInstanceOf(d, "Pipe"));
458
- const isDeclarable = isComponent2 || isDirective || isPipe;
459
- let isStandalone = (isComponent2 || isDirective) && [...decorators].reverse().find(
460
- (d) => _PropertyExtractor.isDecoratorInstanceOf(d, "Component") || _PropertyExtractor.isDecoratorInstanceOf(d, "Directive")
461
- )?.standalone;
462
- if (isStandalone === void 0) {
463
- isStandalone = !!(VERSION.major && Number(VERSION.major) >= 19);
464
- }
465
- return { isDeclarable, isStandalone };
466
- }, "analyzeDecorators");
467
- _PropertyExtractor.isDecoratorInstanceOf = /* @__PURE__ */ __name((decorator, name) => {
468
- let factory;
469
- switch (name) {
470
- case "Component":
471
- factory = Component2;
472
- break;
473
- case "Directive":
474
- factory = Directive2;
475
- break;
476
- case "Pipe":
477
- factory = Pipe2;
478
- break;
479
- case "Injectable":
480
- factory = Injectable;
481
- break;
482
- case "Input":
483
- factory = Input2;
484
- break;
485
- case "Output":
486
- factory = Output2;
487
- break;
488
- default:
489
- throw new Error(`Unknown decorator type: ${name}`);
490
- }
491
- return decorator instanceof factory || decorator.ngMetadataName === name;
492
- }, "isDecoratorInstanceOf");
493
- var PropertyExtractor = _PropertyExtractor;
494
-
495
- // src/client/angular-beta/StorybookWrapperComponent.ts
496
- var getNonInputsOutputsProps = /* @__PURE__ */ __name((ngComponentInputsOutputs, props = {}) => {
497
- const inputs = ngComponentInputsOutputs.inputs.filter((i) => i.templateName in props).map((i) => i.templateName);
498
- const outputs = ngComponentInputsOutputs.outputs.filter((o) => o.templateName in props).map((o) => o.templateName);
499
- return Object.keys(props).filter((k) => ![...inputs, ...outputs].includes(k));
500
- }, "getNonInputsOutputsProps");
501
- var createStorybookWrapperComponent = /* @__PURE__ */ __name(({
502
- selector,
503
- template,
504
- storyComponent,
505
- styles,
506
- moduleMetadata,
507
- initialProps,
508
- analyzedMetadata
509
- }) => {
510
- const viewChildSelector = storyComponent ?? "__storybook-noop";
511
- const { imports, declarations, providers } = analyzedMetadata;
512
- let StorybookComponentModule = class {
513
- };
514
- __name(StorybookComponentModule, "StorybookComponentModule");
515
- StorybookComponentModule = __decorateClass([
516
- NgModule2({
517
- declarations,
518
- imports,
519
- exports: [...declarations, ...imports]
520
- })
521
- ], StorybookComponentModule);
522
- PropertyExtractor.warnImportsModuleWithProviders(analyzedMetadata);
523
- let StorybookWrapperComponent = class {
524
- constructor(storyProps$, changeDetectorRef) {
525
- this.storyProps$ = storyProps$;
526
- this.changeDetectorRef = changeDetectorRef;
527
- // Used in case of a component without selector
528
- this.storyComponent = storyComponent ?? "";
529
- }
530
- ngOnInit() {
531
- this.storyWrapperPropsSubscription = this.storyProps$.subscribe((storyProps = {}) => {
532
- Object.assign(this, storyProps);
533
- this.changeDetectorRef.detectChanges();
534
- this.changeDetectorRef.markForCheck();
535
- });
536
- }
537
- ngAfterViewInit() {
538
- if (this.storyComponentElementRef) {
539
- const ngComponentInputsOutputs = getComponentInputsOutputs(storyComponent);
540
- const initialOtherProps = getNonInputsOutputsProps(ngComponentInputsOutputs, initialProps);
541
- initialOtherProps.forEach((p) => {
542
- this.storyComponentElementRef[p] = initialProps[p];
543
- });
544
- this.storyComponentViewContainerRef.injector.get(ChangeDetectorRef).markForCheck();
545
- this.changeDetectorRef.detectChanges();
546
- this.storyComponentPropsSubscription = this.storyProps$.pipe(
547
- skip(1),
548
- map((props) => {
549
- const propsKeyToKeep = getNonInputsOutputsProps(ngComponentInputsOutputs, props);
550
- return propsKeyToKeep.reduce((acc, p) => ({ ...acc, [p]: props[p] }), {});
551
- })
552
- ).subscribe((props) => {
553
- Object.assign(this.storyComponentElementRef, props);
554
- this.storyComponentViewContainerRef.injector.get(ChangeDetectorRef).markForCheck();
555
- this.changeDetectorRef.detectChanges();
556
- });
557
- }
558
- }
559
- ngOnDestroy() {
560
- if (this.storyComponentPropsSubscription != null) {
561
- this.storyComponentPropsSubscription.unsubscribe();
562
- }
563
- if (this.storyWrapperPropsSubscription != null) {
564
- this.storyWrapperPropsSubscription.unsubscribe();
565
- }
566
- }
567
- };
568
- __name(StorybookWrapperComponent, "StorybookWrapperComponent");
569
- __decorateClass([
570
- ViewChild(viewChildSelector, { static: true })
571
- ], StorybookWrapperComponent.prototype, "storyComponentElementRef", 2);
572
- __decorateClass([
573
- ViewChild(viewChildSelector, { read: ViewContainerRef, static: true })
574
- ], StorybookWrapperComponent.prototype, "storyComponentViewContainerRef", 2);
575
- StorybookWrapperComponent = __decorateClass([
576
- Component3({
577
- selector,
578
- template,
579
- standalone: true,
580
- imports: [StorybookComponentModule],
581
- providers,
582
- styles,
583
- schemas: moduleMetadata.schemas
584
- }),
585
- __decorateParam(0, Inject(STORY_PROPS)),
586
- __decorateParam(1, Inject(ChangeDetectorRef))
587
- ], StorybookWrapperComponent);
588
- return StorybookWrapperComponent;
589
- }, "createStorybookWrapperComponent");
590
-
591
- // src/client/angular-beta/StorybookModule.ts
592
- var getApplication = /* @__PURE__ */ __name(({
593
- storyFnAngular,
594
- component,
595
- targetSelector,
596
- analyzedMetadata
597
- }) => {
598
- const { props, styles, moduleMetadata = {} } = storyFnAngular;
599
- let { template } = storyFnAngular;
600
- const hasTemplate = !hasNoTemplate(template);
601
- if (!hasTemplate && component) {
602
- template = computesTemplateFromComponent(component, props, "");
603
- }
604
- return createStorybookWrapperComponent({
605
- moduleMetadata,
606
- selector: targetSelector,
607
- template,
608
- storyComponent: component,
609
- styles,
610
- initialProps: props,
611
- analyzedMetadata
612
- });
613
- }, "getApplication");
614
- function hasNoTemplate(template) {
615
- return template === null || template === void 0;
616
- }
617
- __name(hasNoTemplate, "hasNoTemplate");
618
-
619
- // src/client/angular-beta/utils/BootstrapQueue.ts
620
- var queue = [];
621
- var isProcessing = false;
622
- var resetCompiledComponents = /* @__PURE__ */ __name(async () => {
623
- try {
624
- const { \u0275resetCompiledComponents } = await import("@angular/core");
625
- \u0275resetCompiledComponents();
626
- } catch (e) {
627
- }
628
- }, "resetCompiledComponents");
629
- var queueBootstrapping = /* @__PURE__ */ __name((fn) => {
630
- return new Promise((resolve, reject) => {
631
- queue.push(() => fn().then(resolve).catch(reject));
632
- if (!isProcessing) {
633
- processQueue();
634
- }
635
- });
636
- }, "queueBootstrapping");
637
- var processQueue = /* @__PURE__ */ __name(async () => {
638
- isProcessing = true;
639
- while (queue.length > 0) {
640
- const bootstrappingFn = queue.shift();
641
- if (bootstrappingFn) {
642
- await bootstrappingFn();
643
- await resetCompiledComponents();
644
- }
645
- }
646
- isProcessing = false;
647
- }, "processQueue");
648
-
649
- // src/client/angular-beta/utils/Zoneless.ts
650
- var getProvideZonelessChangeDetectionFn = /* @__PURE__ */ __name(async () => {
651
- const angularCore = await import("@angular/core");
652
- return "provideExperimentalZonelessChangeDetection" in angularCore ? angularCore.provideExperimentalZonelessChangeDetection : "provideZonelessChangeDetection" in angularCore ? angularCore.provideZonelessChangeDetection : null;
653
- }, "getProvideZonelessChangeDetectionFn");
654
-
655
- // src/client/angular-beta/AbstractRenderer.ts
656
- var applicationRefs = /* @__PURE__ */ new Map();
657
- var STORY_UID_ATTRIBUTE = "data-sb-story-uid";
658
- var _AbstractRenderer = class _AbstractRenderer {
659
- constructor() {
660
- this.previousStoryRenderInfo = /* @__PURE__ */ new Map();
661
- }
662
- /** Wait and destroy the platform */
663
- static resetApplications(domNode) {
664
- applicationRefs.forEach((appRef, appDOMNode) => {
665
- if (!appRef.destroyed && (!domNode || appDOMNode === domNode)) {
666
- appRef.destroy();
667
- }
668
- });
669
- }
670
- /**
671
- * Bootstrap main angular module with main component or send only new `props` with storyProps$
672
- *
673
- * @param storyFnAngular {StoryFnAngularReturnType}
674
- * @param forced {boolean} If :
675
- *
676
- * - True render will only use the StoryFn `props' in storyProps observable that will update sotry's
677
- * component/template properties. Improves performance without reloading the whole
678
- * module&component if props changes
679
- * - False fully recharges or initializes angular module & component
680
- *
681
- * @param component {Component}
682
- */
683
- async render({
684
- storyFnAngular,
685
- forced,
686
- component,
687
- targetDOMNode
688
- }) {
689
- const targetSelector = this.generateTargetSelectorFromStoryId(targetDOMNode.id);
690
- const newStoryProps$ = new BehaviorSubject(storyFnAngular.props);
691
- if (!this.fullRendererRequired({
692
- targetDOMNode,
693
- storyFnAngular,
694
- moduleMetadata: {
695
- ...storyFnAngular.moduleMetadata
696
- },
697
- forced
698
- })) {
699
- this.storyProps$.next(storyFnAngular.props);
700
- return;
701
- }
702
- await this.beforeFullRender(targetDOMNode);
703
- if (this.storyProps$) {
704
- this.storyProps$.complete();
705
- }
706
- this.storyProps$ = newStoryProps$;
707
- this.initAngularRootElement(targetDOMNode, targetSelector);
708
- const analyzedMetadata = new PropertyExtractor(storyFnAngular.moduleMetadata, component);
709
- await analyzedMetadata.init();
710
- const storyUid = this.generateStoryUIdFromRawStoryUid(
711
- targetDOMNode.getAttribute(STORY_UID_ATTRIBUTE)
712
- );
713
- const componentSelector = storyUid !== null ? `${targetSelector}[${storyUid}]` : targetSelector;
714
- if (storyUid !== null) {
715
- const element = targetDOMNode.querySelector(targetSelector);
716
- element.toggleAttribute(storyUid, true);
717
- }
718
- const application = getApplication({
719
- storyFnAngular,
720
- component,
721
- targetSelector: componentSelector,
722
- analyzedMetadata
723
- });
724
- const providers = [
725
- storyPropsProvider(newStoryProps$),
726
- ...analyzedMetadata.applicationProviders,
727
- ...storyFnAngular.applicationConfig?.providers ?? []
728
- ];
729
- if (STORYBOOK_ANGULAR_OPTIONS?.experimentalZoneless) {
730
- const provideZonelessChangeDetectionFn = await getProvideZonelessChangeDetectionFn();
731
- if (!provideZonelessChangeDetectionFn) {
732
- throw new Error("Zoneless change detection requires Angular 18 or higher");
733
- } else {
734
- providers.unshift(provideZonelessChangeDetectionFn());
735
- }
736
- }
737
- const applicationRef = await queueBootstrapping(() => {
738
- return bootstrapApplication(application, {
739
- ...storyFnAngular.applicationConfig,
740
- providers
741
- });
742
- });
743
- applicationRefs.set(targetDOMNode, applicationRef);
744
- }
745
- /**
746
- * Only ASCII alphanumerics can be used as HTML tag name. https://html.spec.whatwg.org/#elements-2
747
- *
748
- * Therefore, stories break when non-ASCII alphanumerics are included in target selector.
749
- * https://github.com/storybookjs/storybook/issues/15147
750
- *
751
- * This method returns storyId when it doesn't contain any non-ASCII alphanumerics. Otherwise, it
752
- * generates a valid HTML tag name from storyId by removing non-ASCII alphanumerics from storyId,
753
- * prefixing "sb-", and suffixing "-component"
754
- *
755
- * @memberof AbstractRenderer
756
- * @protected
757
- */
758
- generateTargetSelectorFromStoryId(id) {
759
- const invalidHtmlTag = /[^A-Za-z0-9-]/g;
760
- const storyIdIsInvalidHtmlTagName = invalidHtmlTag.test(id);
761
- return storyIdIsInvalidHtmlTagName ? `sb-${id.replace(invalidHtmlTag, "")}-component` : id;
762
- }
763
- /**
764
- * Angular is unable to handle components that have selectors with accented attributes.
765
- *
766
- * Therefore, stories break when meta's title contains accents.
767
- * https://github.com/storybookjs/storybook/issues/29132
768
- *
769
- * This method filters accents from a given raw id. For example, this method converts
770
- * 'Example/Button with an "é" accent' into 'Example/Button with an "e" accent'.
771
- *
772
- * @memberof AbstractRenderer
773
- * @protected
774
- */
775
- generateStoryUIdFromRawStoryUid(rawStoryUid) {
776
- if (rawStoryUid === null) {
777
- return rawStoryUid;
778
- }
779
- const accentCharacters = /[\u0300-\u036f]/g;
780
- return rawStoryUid.normalize("NFD").replace(accentCharacters, "");
781
- }
782
- /** Adds DOM element that angular will use as bootstrap component. */
783
- initAngularRootElement(targetDOMNode, targetSelector) {
784
- targetDOMNode.innerHTML = "";
785
- targetDOMNode.appendChild(document.createElement(targetSelector));
786
- }
787
- fullRendererRequired({
788
- targetDOMNode,
789
- storyFnAngular,
790
- moduleMetadata,
791
- forced
792
- }) {
793
- const previousStoryRenderInfo = this.previousStoryRenderInfo.get(targetDOMNode);
794
- const currentStoryRender = {
795
- storyFnAngular,
796
- moduleMetadataSnapshot: stringify(moduleMetadata, { maxDepth: 50 })
797
- };
798
- this.previousStoryRenderInfo.set(targetDOMNode, currentStoryRender);
799
- if (
800
- // check `forceRender` of story RenderContext
801
- !forced || // if it's the first rendering and storyProps$ is not init
802
- !this.storyProps$
803
- ) {
804
- return true;
805
- }
806
- const hasChangedTemplate = !!storyFnAngular?.template && previousStoryRenderInfo?.storyFnAngular?.template !== storyFnAngular.template;
807
- if (hasChangedTemplate) {
808
- return true;
809
- }
810
- const hasChangedModuleMetadata = currentStoryRender.moduleMetadataSnapshot !== previousStoryRenderInfo?.moduleMetadataSnapshot;
811
- return hasChangedModuleMetadata;
812
- }
813
- };
814
- __name(_AbstractRenderer, "AbstractRenderer");
815
- var AbstractRenderer = _AbstractRenderer;
816
-
817
- // src/client/angular-beta/CanvasRenderer.ts
818
- var _CanvasRenderer = class _CanvasRenderer extends AbstractRenderer {
819
- async render(options) {
820
- await super.render(options);
821
- }
822
- async beforeFullRender() {
823
- _CanvasRenderer.resetApplications();
824
- }
825
- };
826
- __name(_CanvasRenderer, "CanvasRenderer");
827
- var CanvasRenderer = _CanvasRenderer;
828
-
829
- // src/client/angular-beta/DocsRenderer.ts
830
- import { DOCS_RENDERED, STORY_CHANGED } from "storybook/internal/core-events";
831
- import { addons } from "storybook/preview-api";
832
-
833
- // src/client/angular-beta/utils/StoryUID.ts
834
- var storyCounts = /* @__PURE__ */ new Map();
835
- var getNextStoryUID = /* @__PURE__ */ __name((storyId) => {
836
- if (!storyCounts.has(storyId)) {
837
- storyCounts.set(storyId, -1);
838
- }
839
- const count = storyCounts.get(storyId) + 1;
840
- storyCounts.set(storyId, count);
841
- return `${storyId}-${count}`;
842
- }, "getNextStoryUID");
843
-
844
- // src/client/angular-beta/DocsRenderer.ts
845
- var _DocsRenderer = class _DocsRenderer extends AbstractRenderer {
846
- async render(options) {
847
- const channel = addons.getChannel();
848
- channel.once(STORY_CHANGED, async () => {
849
- await _DocsRenderer.resetApplications();
850
- });
851
- channel.once(DOCS_RENDERED, async () => {
852
- await _DocsRenderer.resetApplications();
853
- });
854
- await super.render({ ...options, forced: false });
855
- }
856
- async beforeFullRender(domNode) {
857
- _DocsRenderer.resetApplications(domNode);
858
- }
859
- initAngularRootElement(targetDOMNode, targetSelector) {
860
- super.initAngularRootElement(targetDOMNode, targetSelector);
861
- targetDOMNode.setAttribute(STORY_UID_ATTRIBUTE, getNextStoryUID(targetDOMNode.id));
862
- }
863
- };
864
- __name(_DocsRenderer, "DocsRenderer");
865
- var DocsRenderer = _DocsRenderer;
866
-
867
- // src/client/angular-beta/RendererFactory.ts
868
- var _RendererFactory = class _RendererFactory {
869
- constructor() {
870
- this.rendererMap = /* @__PURE__ */ new Map();
871
- }
872
- async getRendererInstance(targetDOMNode) {
873
- const targetId = targetDOMNode.id;
874
- if (targetDOMNode === null) {
875
- return null;
876
- }
877
- const renderType = getRenderType(targetDOMNode);
878
- if (this.lastRenderType && this.lastRenderType !== renderType) {
879
- await AbstractRenderer.resetApplications();
880
- clearRootHTMLElement(renderType);
881
- this.rendererMap.clear();
882
- }
883
- if (!this.rendererMap.has(targetId)) {
884
- this.rendererMap.set(targetId, this.buildRenderer(renderType));
885
- }
886
- this.lastRenderType = renderType;
887
- return this.rendererMap.get(targetId);
888
- }
889
- buildRenderer(renderType) {
890
- if (renderType === "docs") {
891
- return new DocsRenderer();
892
- }
893
- return new CanvasRenderer();
894
- }
895
- };
896
- __name(_RendererFactory, "RendererFactory");
897
- var RendererFactory = _RendererFactory;
898
- var getRenderType = /* @__PURE__ */ __name((targetDOMNode) => {
899
- return targetDOMNode.id === "storybook-root" ? "canvas" : "docs";
900
- }, "getRenderType");
901
- function clearRootHTMLElement(renderType) {
902
- switch (renderType) {
903
- case "canvas":
904
- global.document.getElementById("storybook-docs").innerHTML = "";
905
- break;
906
- case "docs":
907
- global.document.getElementById("storybook-root").innerHTML = "";
908
- break;
909
- default:
910
- break;
911
- }
912
- }
913
- __name(clearRootHTMLElement, "clearRootHTMLElement");
914
-
915
- // src/client/render.ts
916
- var rendererFactory = new RendererFactory();
917
- var render = /* @__PURE__ */ __name((props) => ({ props }), "render");
918
- async function renderToCanvas({ storyFn, showMain, forceRemount, storyContext: { component } }, element) {
919
- showMain();
920
- const renderer = await rendererFactory.getRendererInstance(element);
921
- await renderer.render({
922
- storyFnAngular: storyFn(),
923
- component,
924
- forced: !forceRemount,
925
- targetDOMNode: element
926
- });
927
- }
928
- __name(renderToCanvas, "renderToCanvas");
929
-
930
- export {
931
- __name,
932
- isComponent,
933
- formatPropInTemplate,
934
- computesTemplateFromComponent,
935
- computesTemplateSourceFromComponent,
936
- render,
937
- renderToCanvas,
938
- render_exports
939
- };