How to use ngComponentInputsOutputs method in storybook-root

Best JavaScript code snippet using storybook-root

StorybookWrapperComponent.ts

Source:StorybookWrapperComponent.ts Github

copy

Full Screen

1import {2 AfterViewInit,3 ChangeDetectorRef,4 Component,5 ElementRef,6 Inject,7 OnDestroy,8 Type,9 ViewChild,10 ViewContainerRef,11} from '@angular/core';12import { Subscription, Subject } from 'rxjs';13import { map, skip } from 'rxjs/operators';14import { ICollection } from '../types';15import { STORY_PROPS } from './StorybookProvider';16import { ComponentInputsOutputs, getComponentInputsOutputs } from './utils/NgComponentAnalyzer';17const getNonInputsOutputsProps = (18 ngComponentInputsOutputs: ComponentInputsOutputs,19 props: ICollection = {}20) => {21 const inputs = ngComponentInputsOutputs.inputs22 .filter((i) => i.templateName in props)23 .map((i) => i.templateName);24 const outputs = ngComponentInputsOutputs.outputs25 .filter((o) => o.templateName in props)26 .map((o) => o.templateName);27 return Object.keys(props).filter((k) => ![...inputs, ...outputs].includes(k));28};29/**30 * Wraps the story template into a component31 *32 * @param storyComponent33 * @param initialProps34 */35export const createStorybookWrapperComponent = (36 selector: string,37 template: string,38 storyComponent: Type<unknown> | undefined,39 styles: string[],40 initialProps?: ICollection41): Type<any> => {42 // In ivy, a '' selector is not allowed, therefore we need to just set it to anything if43 // storyComponent was not provided.44 const viewChildSelector = storyComponent ?? '__storybook-noop';45 @Component({46 selector,47 template,48 styles,49 })50 class StorybookWrapperComponent implements AfterViewInit, OnDestroy {51 private storyComponentPropsSubscription: Subscription;52 private storyWrapperPropsSubscription: Subscription;53 @ViewChild(viewChildSelector, { static: true }) storyComponentElementRef: ElementRef;54 @ViewChild(viewChildSelector, { read: ViewContainerRef, static: true })55 storyComponentViewContainerRef: ViewContainerRef;56 // Used in case of a component without selector57 storyComponent = storyComponent ?? '';58 // eslint-disable-next-line no-useless-constructor59 constructor(60 @Inject(STORY_PROPS) private storyProps$: Subject<ICollection | undefined>,61 private changeDetectorRef: ChangeDetectorRef62 ) {}63 ngOnInit(): void {64 // Subscribes to the observable storyProps$ to keep these properties up to date65 this.storyWrapperPropsSubscription = this.storyProps$.subscribe((storyProps = {}) => {66 // All props are added as component properties67 Object.assign(this, storyProps);68 this.changeDetectorRef.detectChanges();69 this.changeDetectorRef.markForCheck();70 });71 }72 ngAfterViewInit(): void {73 // Bind properties to component, if the story have component74 if (this.storyComponentElementRef) {75 const ngComponentInputsOutputs = getComponentInputsOutputs(storyComponent);76 const initialOtherProps = getNonInputsOutputsProps(ngComponentInputsOutputs, initialProps);77 // Initializes properties that are not Inputs | Outputs78 // Allows story props to override local component properties79 initialOtherProps.forEach((p) => {80 (this.storyComponentElementRef as any)[p] = initialProps[p];81 });82 // `markForCheck` the component in case this uses changeDetection: OnPush83 // And then forces the `detectChanges`84 this.storyComponentViewContainerRef.injector.get(ChangeDetectorRef).markForCheck();85 this.changeDetectorRef.detectChanges();86 // Once target component has been initialized, the storyProps$ observable keeps target component inputs up to date87 this.storyComponentPropsSubscription = this.storyProps$88 .pipe(89 skip(1),90 map((props) => {91 // removes component output in props92 const outputsKeyToRemove = ngComponentInputsOutputs.outputs.map(93 (o) => o.templateName94 );95 return Object.entries(props).reduce(96 (prev, [key, value]) => ({97 ...prev,98 ...(!outputsKeyToRemove.includes(key) && {99 [key]: value,100 }),101 }),102 {} as ICollection103 );104 }),105 map((props) => {106 // In case a component uses an input with `bindingPropertyName` (ex: @Input('name'))107 // find the value of the local propName in the component Inputs108 // otherwise use the input key109 return Object.entries(props).reduce((prev, [propKey, value]) => {110 const input = ngComponentInputsOutputs.inputs.find(111 (o) => o.templateName === propKey112 );113 return {114 ...prev,115 ...(input ? { [input.propName]: value } : { [propKey]: value }),116 };117 }, {} as ICollection);118 })119 )120 .subscribe((props) => {121 // Replace inputs with new ones from props122 Object.assign(this.storyComponentElementRef, props);123 // `markForCheck` the component in case this uses changeDetection: OnPush124 // And then forces the `detectChanges`125 this.storyComponentViewContainerRef.injector.get(ChangeDetectorRef).markForCheck();126 this.changeDetectorRef.detectChanges();127 });128 }129 }130 ngOnDestroy(): void {131 if (this.storyComponentPropsSubscription != null) {132 this.storyComponentPropsSubscription.unsubscribe();133 }134 if (this.storyWrapperPropsSubscription != null) {135 this.storyWrapperPropsSubscription.unsubscribe();136 }137 }138 }139 return StorybookWrapperComponent;...

Full Screen

Full Screen

ComputesTemplateFromComponent.ts

Source:ComputesTemplateFromComponent.ts Github

copy

Full Screen

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 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root';2import { storiesOf } from 'storybook-root';3import { moduleMetadata } from 'storybook-root';4import { withKnobs } from 'storybook-root';5import { withA11y } from 'storybook-root';6import { withCssResources } from 'storybook-root';7import { withNotes } from 'storybook-root';8import { withOptions } from 'storybook-root';9import { withViewport } from 'storybook-root';10import { withBackgrounds } from 'storybook-root';11import { withTests } from 'storybook-root';12import { withConsole } from 'storybook-root';13import { withLinks } from 'storybook-root';14import { withInfo } from 'storybook-root';15import { withPaddings } from 'storybook-root';16import { withPerformance } from 'storybook-root';17import { withContexts } from 'storybook-root';18import { withActions } from 'storybook-root';19import { withPropsTable } from 'storybook-root';20import { withViewport } from 'storybook-root';21import { withState } from 'storybook-root';22import { withOptions } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root';2import { ButtonComponent } from './button.component';3export default {4}5export const primary = () => ({6 moduleMetadata: {7 },8 props: ngComponentInputsOutputs({9 })10});11import { Component, Input, Output, EventEmitter } from '@angular/core';12@Component({13})14export class ButtonComponent {15 @Input() text: string;16 @Output() clicked = new EventEmitter();17 onClick() {18 this.clicked.emit();19 }20}21<button (click)="onClick()">{{text}}</button>22button {23 padding: 10px;24 background-color: blue;25 color: white;26}27import { async, ComponentFixture, TestBed } from '@angular/core/testing';28import { ButtonComponent } from './button.component';29describe('ButtonComponent', () => {30 let component: ButtonComponent;31 let fixture: ComponentFixture<ButtonComponent>;32 beforeEach(async(() => {33 TestBed.configureTestingModule({34 })35 .compileComponents();36 }));37 beforeEach(() => {38 fixture = TestBed.createComponent(ButtonComponent);39 component = fixture.componentInstance;40 fixture.detectChanges();41 });42 it('should create', () => {43 expect(component).toBeTruthy();44 });45});46import { ButtonComponent } from './button.component';47export default {48}49export const primary = () => ({50 moduleMetadata: {51 },52 props: {53 }54});55import { ButtonComponent } from './button.component';56export default {57}58export const primary = () => ({59 moduleMetadata: {60 },61 props: {62 }63});64import { ButtonComponent } from './button.component';65export default {66}67export const primary = () => ({68 moduleMetadata: {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root';2import { MyComponent } from 'my-component';3export default {4};5export const inputsAndOutputs = () => ({6 props: ngComponentInputsOutputs(MyComponent),7});8import { Component, Input, Output, EventEmitter } from '@angular/core';9@Component({10 <button (click)="onClick()">Click me</button>11})12export class MyComponent {13 @Input() input1: string;14 @Input() input2: string;15 @Output() output1 = new EventEmitter<string>();16 @Output() output2 = new EventEmitter<string>();17 onClick() {18 this.output1.emit('Hello world');19 }20}21import { MyComponent } from './my-component.component';22export default {23};24export const inputsAndOutputs = () => ({25 props: {26 output1: (value: string) => console.log(value),27 output2: (value: string) => console.log(value),28 },29});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root-module';2import { ngComponentInputsOutputs } from 'storybook-root-module';3import { ngComponentInputsOutputs } from 'storybook-root-module';4import { ngComponentInputsOutputs } from 'storybook-root-module';5import { ngComponentInputsOutputs } from 'storybook-root-module';6import { ngComponentInputsOutputs } from 'storybook-root-module';7import { ngComponentInputsOutputs } from 'storybook-root-module';8import { ngComponentInputsOutputs } from 'storybook-root-module';9import { ngComponentInputsOutputs } from 'storybook-root-module';10import { ngComponentInputsOutputs } from 'storybook-root-module';11import { ngComponentInputsOutputs } from

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root';2const inputs = ngComponentInputsOutputs('my-component', 'inputs');3const outputs = ngComponentInputsOutputs('my-component', 'outputs');4export default {5 parameters: {6 },7};8const Template = (args: MyComponent) => ({9 moduleMetadata: {10 },11});12export const Primary = Template.bind({});13Primary.args = {14};15export const Secondary = Template.bind({});16Secondary.args = {17};18export const Large = Template.bind({});19Large.args = {20};21export const Small = Template.bind({});22Small.args = {23};24export const PrimaryWithEmoji = Template.bind({});25PrimaryWithEmoji.args = {26};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root'2ngComponentInputsOutputs({3 inputs: {4 },5 outputs: {6 click: () => console.log('click'),7 },8})9import { configure } from '@storybook/angular'10import { setConsoleOptions } from '@storybook/addon-console'11import { withA11y } from '@storybook/addon-a11y'12import { withKnobs } from '@storybook/addon-knobs'13import { withNotes } from '@storybook/addon-notes'14import { withCssResources } from '@storybook/addon-cssresources'15import { withContexts } from '@storybook/addon-contexts/angular'16import { addDecorator } from '@storybook/angular'17import { withConsole } from '@storybook/addon-console'18import { contexts } from './contexts'19addDecorator(withContexts(contexts))20addDecorator(withKnobs)21addDecorator(withA11y)22addDecorator(withNotes)23addDecorator(withCssResources)24addDecorator((storyFn, context) => withConsole()(storyFn)(context))25setConsoleOptions({26})27configure(require.context('../src', true, /\.stories\.ts$/), module)28import { addParameters } from '@storybook/angular'29import { themes } from '@storybook/theming'30import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport'31addParameters({32 options: {33 },34 viewport: {35 },36})37import { contexts } from '@storybook/addon-contexts'38 {39 {40 props: {41 },42 },43 {44 props: {45 },

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngComponentInputsOutputs } from 'storybook-root';2import { MyComponent } from './my.component';3import { MyComponentInputsOutputs } from './my.component.inputs-outputs';4describe('MyComponent', () => {5 it('should render', () => {6 const { inputs, outputs } = ngComponentInputsOutputs(MyComponent, MyComponentInputsOutputs);7 const component = new MyComponent(inputs, outputs);8 expect(component).toBeTruthy();9 });10});11export const MyComponentInputsOutputs = {12 inputs: {13 },14 outputs: {15 },16};17import { Component, Input, Output, EventEmitter } from '@angular/core';18@Component({19})20export class MyComponent {21 @Input() input1: string;22 @Input() input2: string;23 @Output() output1 = new EventEmitter();24 @Output() output2 = new EventEmitter();25 constructor(inputs: any, outputs: any) {26 this.input1 = inputs.input1;27 this.input2 = inputs.input2;28 this.output1 = outputs.output1;29 this.output2 = outputs.output2;30 }31}32import { async, ComponentFixture, TestBed } from '@angular/core/testing';33import { MyComponent } from './my.component';34import { MyComponentInputsOutputs } from './my.component.inputs-outputs';35describe('MyComponent', () => {36 let component: MyComponent;37 let fixture: ComponentFixture<MyComponent>;38 beforeEach(async(() => {39 TestBed.configureTestingModule({40 }).compileComponents();41 }));42 beforeEach(() => {43 const { inputs, outputs } = ngComponentInputsOutputs(MyComponent, MyComponentInputsOutputs);44 fixture = TestBed.createComponent(MyComponent);45 component = fixture.componentInstance;46 component.input1 = inputs.input1;47 component.input2 = inputs.input2;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful