Best JavaScript code snippet using storybook-root
ComputesTemplateFromComponent.ts
Source:ComputesTemplateFromComponent.ts
1import type { Type } from '@angular/core';2import type { ArgType, ArgTypes } from '@storybook/api';3import type { ICollection } from '../types';4import {5 ComponentInputsOutputs,6 getComponentDecoratorMetadata,7 getComponentInputsOutputs,8} from './utils/NgComponentAnalyzer';9const separateInputsOutputsAttributes = (10 ngComponentInputsOutputs: ComponentInputsOutputs,11 props: ICollection = {}12) => {13 const inputs = ngComponentInputsOutputs.inputs14 .filter((i) => i.templateName in props)15 .map((i) => i.templateName);16 const outputs = ngComponentInputsOutputs.outputs17 .filter((o) => o.templateName in props)18 .map((o) => o.templateName);19 return {20 inputs,21 outputs,22 otherProps: Object.keys(props).filter((k) => ![...inputs, ...outputs].includes(k)),23 };24};25/**26 * Converts a component into a template with inputs/outputs present in initial props27 * @param component28 * @param initialProps29 * @param innerTemplate30 */31export const computesTemplateFromComponent = (32 component: Type<unknown>,33 initialProps?: ICollection,34 innerTemplate = ''35) => {36 const ngComponentMetadata = getComponentDecoratorMetadata(component);37 const ngComponentInputsOutputs = getComponentInputsOutputs(component);38 if (!ngComponentMetadata.selector) {39 // Allow to add renderer component when NgComponent selector is undefined40 return `<ng-container *ngComponentOutlet="storyComponent"></ng-container>`;41 }42 const { inputs: initialInputs, outputs: initialOutputs } = separateInputsOutputsAttributes(43 ngComponentInputsOutputs,44 initialProps45 );46 const templateInputs =47 initialInputs.length > 0 ? ` ${initialInputs.map((i) => `[${i}]="${i}"`).join(' ')}` : '';48 const templateOutputs =49 initialOutputs.length > 050 ? ` ${initialOutputs.map((i) => `(${i})="${i}($event)"`).join(' ')}`51 : '';52 return buildTemplate(53 ngComponentMetadata.selector,54 innerTemplate,55 templateInputs,56 templateOutputs57 );58};59const createAngularInputProperty = ({60 propertyName,61 value,62 argType,63}: {64 propertyName: string;65 value: any;66 argType?: ArgType;67}) => {68 const { name: type = null, summary = null } = argType?.type || {};69 let templateValue = type === 'enum' && !!summary ? `${summary}.${value}` : value;70 const actualType = type === 'enum' && summary ? 'enum' : typeof value;71 const requiresBrackets = ['object', 'any', 'boolean', 'enum', 'number'].includes(actualType);72 if (typeof value === 'object') {73 templateValue = propertyName;74 }75 return `${requiresBrackets ? '[' : ''}${propertyName}${76 requiresBrackets ? ']' : ''77 }="${templateValue}"`;78};79/**80 * Converts a component into a template with inputs/outputs present in initial props81 * @param component82 * @param initialProps83 * @param innerTemplate84 */85export const computesTemplateSourceFromComponent = (86 component: Type<unknown>,87 initialProps?: ICollection,88 argTypes?: ArgTypes89) => {90 const ngComponentMetadata = getComponentDecoratorMetadata(component);91 if (!ngComponentMetadata) {92 return null;93 }94 if (!ngComponentMetadata.selector) {95 // Allow to add renderer component when NgComponent selector is undefined96 return `<ng-container *ngComponentOutlet="${component.name}"></ng-container>`;97 }98 const ngComponentInputsOutputs = getComponentInputsOutputs(component);99 const { inputs: initialInputs, outputs: initialOutputs } = separateInputsOutputsAttributes(100 ngComponentInputsOutputs,101 initialProps102 );103 const templateInputs =104 initialInputs.length > 0105 ? ` ${initialInputs106 .map((propertyName) =>107 createAngularInputProperty({108 propertyName,109 value: initialProps[propertyName],110 argType: argTypes?.[propertyName],111 })112 )113 .join(' ')}`114 : '';115 const templateOutputs =116 initialOutputs.length > 0117 ? ` ${initialOutputs.map((i) => `(${i})="${i}($event)"`).join(' ')}`118 : '';119 return buildTemplate(ngComponentMetadata.selector, '', templateInputs, templateOutputs);120};121const buildTemplate = (122 selector: string,123 innerTemplate: string,124 inputs: string,125 outputs: string126) => {127 // https://www.w3.org/TR/2011/WD-html-markup-20110113/syntax.html#syntax-elements128 const voidElements = [129 'area',130 'base',131 'br',132 'col',133 'command',134 'embed',135 'hr',136 'img',137 'input',138 'keygen',139 'link',140 'meta',141 'param',142 'source',143 'track',144 'wbr',145 ];146 const firstSelector = selector.split(',')[0];147 const templateReplacers: [148 string | RegExp,149 string | ((substring: string, ...args: any[]) => string)150 ][] = [151 [/(^.*?)(?=[,])/, '$1'],152 [/(^\..+)/, 'div$1'],153 [/(^\[.+?])/, 'div$1'],154 [/([\w[\]]+)(\s*,[\w\s-[\],]+)+/, `$1`],155 [/#([\w-]+)/, ` id="$1"`],156 [/((\.[\w-]+)+)/, (_, c) => ` class="${c.split`.`.join` `.trim()}"`],157 [/(\[.+?])/g, (_, a) => ` ${a.slice(1, -1)}`],158 [159 /([\S]+)(.*)/,160 (template, elementSelector) => {161 return voidElements.some((element) => elementSelector === element)162 ? template.replace(/([\S]+)(.*)/, `<$1$2${inputs}${outputs} />`)163 : template.replace(/([\S]+)(.*)/, `<$1$2${inputs}${outputs}>${innerTemplate}</$1>`);164 },165 ],166 ];167 return templateReplacers.reduce(168 (prevSelector, [searchValue, replacer]) => prevSelector.replace(searchValue, replacer as any),169 firstSelector170 );...
Using AI Code Generation
1import { ngComponentMetadata } from 'storybook-root';2import { ngModule } from 'storybook-root';3import { ngStorybookModule } from 'storybook-root';4import { ngStorybookStory } from 'storybook-root';5import { ngStorybookStories } from 'storybook-root';6import { ngComponentMetadata } from 'storybook-root';7import { ngModule } from 'storybook-root';8import { ngStorybookModule } from 'storybook-root';9import { ngStorybookStory } from 'storybook-root';10import { ngStorybookStories } from 'storybook-root';11import { ngComponentMetadata } from 'storybook-root';12import { ngModule } from 'storybook-root';13import { ngStorybookModule } from 'storybook-root';14import { ngStorybookStory } from 'storybook-root';15import { ngStorybookStories } from 'storybook-root';16import { ngComponentMetadata } from 'storybook-root';17import { ngModule } from 'storybook-root';18import { ngStorybookModule } from 'storybook-root';19import { ngStorybookStory } from 'storybook-root';20import { ngStorybookStories } from 'storybook-root';21import { ng
Using AI Code Generation
1import { ngComponentMetadata } from 'storybook-root';2import { AppComponent } from './app.component';3export default ngComponentMetadata({4})5 .add('default', {6 });7import { Component } from '@angular/core';8@Component({9})10export class AppComponent {11 title = 'app';12}13 {{title}}14div {15 color: red;16}17import { BrowserModule } from '@angular/platform-browser';18import { NgModule } from '@angular/core';19import { AppComponent } from './app.component';20@NgModule({21 imports: [22})23export class AppModule { }24import { configure } from '@storybook/angular';25configure(require.context('../src', true, /\.stories\.ts$/), module);26{27 "compilerOptions": {28 },29}30{31 "compilerOptions": {32 }33}34{35 "scripts": {36 },37 "dependencies": {
Using AI Code Generation
1import { ngComponentMetadata } from 'storybook-root';2import { MyComponent } from './my-component';3export default ngComponentMetadata({4 props: {5 }6});7import { addDecorator } from '@storybook/angular';8import { withKnobs } from '@storybook/addon-knobs';9import { withA11y } from '@storybook/addon-a11y';10addDecorator(withKnobs);11addDecorator(withA11y);12import { addDecorator } from '@storybook/angular';13import { withKnobs } from '@storybook/addon-knobs';14import { withA11y } from '@storybook/addon-a11y';15addDecorator(withKnobs);16addDecorator(withA11y);17import { addDecorator } from '@storybook/angular';18import { withKnobs } from '@storybook/addon-knobs';19import { withA11y } from '@storybook/addon-a11y';20addDecorator(withKnobs);21addDecorator(withA11y);22import { addDecorator } from '@storybook/angular';23import { withKnobs } from '@storybook/addon-knobs';24import { withA11y } from '@storybook/addon-a11y';25addDecorator(withKnobs);26addDecorator(withA11y);27import { addDecorator } from '@storybook/angular';28import { withKnobs } from '@storybook/addon-knobs';29import { withA11y } from '@storybook/addon-a11y';30addDecorator(withKnobs);31addDecorator(withA11y);32import { addDecorator } from '@storybook/angular';33import { withKnobs } from '@storybook/addon-knobs';34import { withA11y } from '@storybook/addon-a11y';35addDecorator(withKnobs);36addDecorator(withA11y);37import { addDecorator
Using AI Code Generation
1import { Component } from '@angular/core';2import { storiesOf, moduleMetadata } from '@storybook/angular';3import { StorybookRoot } from './storybook-root.component';4import { withNotes } from '@storybook/addon-notes';5import { withKnobs } from '@storybook/addon-knobs';6import { action } from '@storybook/addon-actions';7@Component({8 <button (click)="onClick()">Click</button>9})10class StorybookRootComponent {}11storiesOf('Test', module)12 .addDecorator(13 moduleMetadata({14 })15 .addDecorator(withKnobs)16 .addDecorator(withNotes)17 .add('with a note', () => ({18 props: {19 onClick: action('clicked'),20 },21 }));22import { Component } from '@angular/core';23@Component({24 <button (click)="onClick()">Click</button>25})26export class StorybookRootComponent {27 onClick() {28 console.log('clicked');29 }30}
Using AI Code Generation
1import {ngComponentMetadata} from 'storybook-root';2import {MyComponent} from './my-component';3ngComponentMetadata(MyComponent, {4 <h1>{{title}}</h1>5 <p>{{description}}</p>6});7import {Component, Input} from '@angular/core';8@Component({9 <h1>{{title}}</h1>10 <p>{{description}}</p>11})12export class MyComponent {13 @Input() title: string;14 @Input() description: string;15}16import {storiesOf} from '@storybook/angular';17storiesOf('MyComponent', module)18 .add('default', () => ({19 props: {20 }21 }));22import {ComponentFixture, TestBed} from '@angular/core/testing';23import {MyComponent} from './my-component';24describe('MyComponent', () => {25 let fixture: ComponentFixture<MyComponent>;26 let component: MyComponent;27 beforeEach(() => {28 fixture = TestBed.createComponent(MyComponent);29 component = fixture.componentInstance;30 });31 it('should create the component', () => {32 expect(component).toBeTruthy();33 });34});
Using AI Code Generation
1import { ngComponentMetadata } from 'storybook-root';2ngComponentMetadata({3 inputs: {4 },5 outputs: {6 },7});8export default {9 inputs: {10 },11 outputs: {12 },13};14import { Component, EventEmitter, Input, Output } from '@angular/core';15@Component({16 (click)="onClick.emit($event)"17 {{ label }}18})19export class ButtonComponent {20 @Input() label = 'Button';21 @Input() disabled = false;22 @Input() classes = '';23 @Output() onClick = new EventEmitter<Event>();24 constructor() {}25}26:host {27 display: block;28}29button {30 background-color: #1ea7fd;31 border-radius: 3px;32 border: 0;33 color: white;34 cursor: pointer;35 font-size: 11px;36 font-weight: bold;37 line-height: 1;38 padding: 10px 20px;39 text-transform: uppercase;40 text-align: center;41 width: 100%;42}43button:disabled {44 opacity: 0.5;45 cursor: not-allowed;46}47import { storiesOf } from '@storybook/angular';48import { ButtonComponent } from './button.component';49export default {50 inputs: {51 },52 outputs: {53 },54};55storiesOf('Button', module)56 .add('with text', () => ({57 props: {58 },59 }))60 .add('with emoji', () => ({61 props: {
Using AI Code Generation
1import {ngComponentMetadata} from 'storybook-root';2export default ngComponentMetadata({3 inputs: {4 }5});6import {ngComponentMetadata} from 'storybook-root';7export default ngComponentMetadata({8 inputs: {9 }10});
Using AI Code Generation
1import {ngComponentMetadata} from 'storybook-root';2import {MyComponent} from 'my-component';3ngComponentMetadata(MyComponent, {4})5import {Component, Input, Output, EventEmitter} from '@angular/core';6@Component({7 <div (click)="onClick($event)">8})9export class MyComponent {10 @Input() foo;11 @Output() fooChange = new EventEmitter();12 onClick($event) {13 this.foo = 'bar';14 this.fooChange.emit(this.foo);15 }16}17import {MyComponent} from 'my-component';18import {TestBed, ComponentFixture} from '@angular/core/testing';19describe('MyComponent', () => {20 let component: MyComponent;21 let fixture: ComponentFixture<MyComponent>;22 beforeEach(() => {23 TestBed.configureTestingModule({24 });25 fixture = TestBed.createComponent(MyComponent);26 component = fixture.componentInstance;27 });28 it('should emit fooChange event when div is clicked', () => {29 spyOn(component.fooChange, 'emit');30 fixture.nativeElement.querySelector('div').click();31 expect(component.fooChange.emit).toHaveBeenCalledWith('bar');32 });33});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!