How to use componentRef method in storybook-root

Best JavaScript code snippet using storybook-root

angular-view-factory.ts

Source:angular-view-factory.ts Github

copy

Full Screen

1import {2 Inject,3 ViewFactory,4 PostConstruct,5 ViewContainer,6 ViewFactoryArgs,7 VIEW_COMPONENT_CONFIG,8 ConfiguredItem,9 TagUtil,10 ViewConfig,11 VIEW_CONFIG_KEY12} from 'ug-layout';13import {14 Injector,15 ViewContainerRef,16 ComponentFactoryResolver,17 Type,18 ReflectiveInjector,19 ComponentFactory,20 ComponentRef,21 ElementRef,22 Provider,23 ViewRef24} from '@angular/core';25import { ɵDomSharedStylesHost } from '@angular/platform-browser';26import { Subject } from 'rxjs';27import { DetachHost } from 'ug-layout';28import * as angular from './angular';29import { AngularPlugin } from './angular-plugin';30import { Angular1ComponentFactory } from './angularjs-component-factory';31import {32 ANGULAR_TAG,33 ViewComponentConfig,34 COMPONENT_REF_KEY,35 ANGULAR_PLUGIN,36 ANGULAR_GLOBAL37} from './common';38export class AngularViewFactory extends ViewFactory {39 @Inject(ANGULAR_PLUGIN) protected _plugin: AngularPlugin;40 @Inject(ANGULAR_GLOBAL) protected _angularGlobal: any;41 @Inject(DetachHost) protected _detachHost: DetachHost;42 protected _componentFactoryResolver: ComponentFactoryResolver;43 protected _ng1Bootstrapped: Subject<void> = new Subject<void>();44 protected _isNg1Bootstrapped: boolean = false;45 protected _isCheckingForNg1: boolean = false;46 protected get _ng2Injector(): Injector {47 return this._plugin.injector;48 }49 protected get _viewContainerRef(): ViewContainerRef {50 return this._plugin.viewContainerRef;51 }52 @PostConstruct()53 init(): void {54 // This is technically private... BUT it is exported so... it's fair game.55 const styleHost = this._ng2Injector.get(ɵDomSharedStylesHost);56 this._componentFactoryResolver = this._ng2Injector.get(57 ComponentFactoryResolver58 );59 // On detach add the detach child as a style host to add60 // all styles to that child.61 if (this._plugin.detachComponentStyles) {62 this._detachHost.onDetach.subscribe(handler => {63 const childWindow = handler.getChild();64 if (childWindow) {65 const childHost = childWindow.document.head;66 styleHost.addHost(childHost);67 handler.onClose.subscribe(() => styleHost.removeHost(childHost));68 }69 });70 }71 }72 create<T>(args: ViewFactoryArgs): ViewContainer<T> {73 // Pass through for non angular components.74 if (!TagUtil.matchesTags(args.config, [ANGULAR_TAG])) {75 return super.create<T>(args);76 }77 let viewConfig = null;78 if (args.config.useClass) {79 viewConfig = ConfiguredItem.resolveConfig<any>(80 args.config.useClass,81 null82 );83 } else if (args.config.useFactory) {84 viewConfig = ConfiguredItem.resolveConfig<any>(85 args.config.useFactory,86 null87 );88 }89 const component = this.getTokenFrom(args.config);90 return super.create<T>({91 ...args,92 config: {93 ...args.config,94 token: component,95 useFactory: new ConfiguredItem(96 this.createFactory<T>(component, args.config),97 viewConfig98 ),99 deps: [ViewContainer, VIEW_COMPONENT_CONFIG]100 }101 });102 }103 protected createFactory<T>(104 component: Type<T>,105 config: ViewConfig106 ): (...args: any[]) => Promise<T> {107 return async (viewContainer: ViewContainer<T>, config: any): Promise<T> => {108 const metadata = Reflect.getMetadata(109 VIEW_CONFIG_KEY,110 component111 ) as ViewComponentConfig;112 if (metadata.upgrade) {113 return await this._ng1Factory(viewContainer, component, config);114 }115 return await this._ng2Factory(viewContainer, component, config);116 };117 }118 private async _ng1Factory<T>(119 viewContainer: ViewContainer<T>,120 component: Type<T>,121 config: any122 ): Promise<T> {123 if (!this._isNg1Bootstrapped) {124 if (!this._isCheckingForNg1) {125 this._checkForNg1Init();126 }127 await this._ng1Bootstrapped.toPromise();128 }129 const token = component;130 const metadata = Reflect.getOwnMetadata(131 VIEW_CONFIG_KEY,132 token133 ) as ViewComponentConfig;134 const ng1Injector = this._ng2Injector.get('$injector') as angular.Injector;135 const componentRef = ng1Injector.instantiate<Angular1ComponentFactory<T>>(136 Angular1ComponentFactory,137 {138 viewContainer,139 Component: token,140 config: metadata,141 $scope:142 this._plugin.scope || ng1Injector.get<angular.Scope>('$rootScope'),143 angularGlobal: this._angularGlobal,144 providers: this.getNg1Providers(145 {146 viewComponentConfig: config147 },148 viewContainer149 )150 }151 );152 viewContainer.destroyed.subscribe(() =>153 this._onNg1ComponentDestroyed(componentRef.scope, viewContainer)154 );155 return componentRef.create();156 }157 private async _ng2Factory<T>(158 viewContainer: ViewContainer<T>,159 component: Type<T>,160 config: any161 ): Promise<T> {162 const token = component;163 const componentFactory = this._componentFactoryResolver.resolveComponentFactory<164 T165 >(token);166 const injector = ReflectiveInjector.resolveAndCreate(167 this.getNg2Providers(168 [169 {170 provide: ElementRef,171 useValue: new ElementRef(viewContainer.element)172 },173 { provide: ViewContainer, useValue: viewContainer },174 { provide: VIEW_COMPONENT_CONFIG, useValue: config }175 ],176 viewContainer177 ),178 this._ng2Injector179 );180 const componentRef = this._viewContainerRef.createComponent(181 componentFactory,182 undefined,183 injector184 );185 const unbindInputs = this._setupInputs<T>(componentFactory, componentRef);186 componentRef.instance[COMPONENT_REF_KEY] = componentRef;187 viewContainer.mount(componentRef.location.nativeElement);188 viewContainer.destroyed.subscribe(() => {189 unbindInputs();190 this._onComponentDestroy(componentRef, componentFactory);191 });192 viewContainer.attached.subscribe(() =>193 this._onAttachChange(true, componentRef, viewContainer)194 );195 viewContainer.detached.subscribe(() =>196 this._onAttachChange(false, componentRef, viewContainer)197 );198 // This is needed for dynamic components...199 componentRef.changeDetectorRef.markForCheck();200 return componentRef.instance;201 }202 private _onAttachChange<T>(203 isAttached: boolean,204 componentRef: ComponentRef<T>,205 viewContainer: ViewContainer<T>206 ): void {207 const index = this._viewContainerRef.indexOf(componentRef.hostView);208 const hasViewRef = index !== -1;209 if (isAttached) {210 componentRef.hostView.reattach();211 // The view container ref could have changed, so if we reattach, attach to the correct container.212 if (!hasViewRef) {213 this._viewContainerRef.insert(componentRef.hostView);214 viewContainer.mount(componentRef.location.nativeElement);215 }216 } else {217 componentRef.hostView.detach();218 if (hasViewRef) {219 this._viewContainerRef.detach(index);220 }221 }222 }223 /**224 * This is very ugly, but NG2 doesn't let us know when NG1 is bootstrapped, so we need to225 * pull for when it's ready. In reality this only gets invoked 2 or 3 times so it's not that big of a deal.226 * @private227 */228 protected _checkForNg1Init(): void {229 this._isCheckingForNg1 = true;230 if (this._ng2Injector.get('$injector', null)) {231 this._isNg1Bootstrapped = true;232 this._ng1Bootstrapped.next();233 this._ng1Bootstrapped.complete();234 } else {235 setTimeout(() => this._checkForNg1Init());236 }237 }238 private _setupInputs<T>(239 factory: ComponentFactory<T>,240 componentRef: ComponentRef<T>241 ): () => void {242 let isBound: boolean = true;243 for (const input of factory.inputs) {244 const descriptor =245 Object.getOwnPropertyDescriptor(246 componentRef.instance,247 input.propName248 ) ||249 // Account for getter/setters250 Object.getOwnPropertyDescriptor(251 componentRef.componentType.prototype,252 input.propName253 );254 if (descriptor) {255 let { set, get, value } = descriptor;256 if (!set && !get) {257 set = v => (value = v);258 get = () => value;259 }260 Object.defineProperty(componentRef.instance, input.propName, {261 get,262 enumerable: descriptor.enumerable,263 configurable: true,264 set(value) {265 if (set) {266 set.call(this, value);267 }268 if (isBound && !(componentRef.changeDetectorRef as ViewRef).destroyed) {269 componentRef.changeDetectorRef.detectChanges();270 }271 }272 });273 }274 }275 return () => (isBound = false);276 }277 private _onDestroyNotify<T>(278 componentRef: ComponentRef<T>,279 viewContainer: ViewContainer<T>280 ): void {281 const index = this._viewContainerRef.indexOf(componentRef.hostView);282 if (viewContainer.isCacheable) {283 componentRef.hostView.detach();284 if (index !== -1) {285 this._viewContainerRef.detach(index);286 }287 }288 }289 private _onNg1ComponentDestroyed<T>(290 scope: angular.Scope,291 container: ViewContainer<T>292 ): void {293 if (294 container.component &&295 typeof container.component['$onDestroy'] === 'function'296 ) {297 container.component['$onDestroy']();298 }299 scope.$destroy();300 // Angular 1 emits a `$destroy` event when a node is removed from the DOM.301 // We need to simulate this event.302 if (this._angularGlobal) {303 this._angularGlobal.element(container.element).remove();304 }305 }306 private _onComponentDestroy<T>(307 componentRef: ComponentRef<T>,308 componentFactory: ComponentFactory<T>309 ): void {310 const index = this._viewContainerRef.indexOf(componentRef.hostView);311 if (index !== -1) {312 this._viewContainerRef.remove(index);313 }314 componentRef.destroy();315 for (const output of componentFactory.outputs) {316 if (317 typeof componentRef.instance === 'object' &&318 typeof componentRef.instance[output.propName] === 'object' &&319 typeof componentRef.instance[output.propName].complete === 'function'320 ) {321 componentRef.instance[output.propName].complete();322 }323 }324 }325 protected getNg1Providers(326 providers: { [key: string]: any },327 viewContainer: ViewContainer<any>328 ): { [key: string]: any } {329 return providers;330 }331 protected getNg2Providers(332 providers: Provider[],333 viewContainer: ViewContainer<any>334 ): Provider[] {335 return providers;336 }...

Full Screen

Full Screen

dom-portal-host.ts

Source:dom-portal-host.ts Github

copy

Full Screen

1import {2 ComponentFactoryResolver,3 ComponentRef,4 EmbeddedViewRef,5 ApplicationRef,6} from '@angular/core';7import { BasePortalHost, ComponentPortal } from './portal';8/**9 * A PortalHost for attaching portals to an arbitrary DOM element outside of the Angular10 * application context.11 *12 * This is the only part of the portal core that directly touches the DOM.13 */14export class DomPortalHost extends BasePortalHost {15 constructor(16 private _hostDomElement: Element,17 private _componentFactoryResolver: ComponentFactoryResolver,18 private _appRef: ApplicationRef19 ) {20 super();21 }22 /**23 * Attach the given ComponentPortal to DOM element using the ComponentFactoryResolver.24 * @param portal Portal to be attached25 */26 attachComponentPortal<T>(portal: ComponentPortal<T>, newestOnTop: boolean): ComponentRef<T> {27 const componentFactory = this._componentFactoryResolver.resolveComponentFactory(28 portal.component29 );30 let componentRef: ComponentRef<T>;31 // If the portal specifies a ViewContainerRef, we will use that as the attachment point32 // for the component (in terms of Angular's component tree, not rendering).33 // When the ViewContainerRef is missing, we use the factory to create the component directly34 // and then manually attach the ChangeDetector for that component to the application (which35 // happens automatically when using a ViewContainer).36 componentRef = componentFactory.create(portal.injector);37 // When creating a component outside of a ViewContainer, we need to manually register38 // its ChangeDetector with the application. This API is unfortunately not yet published39 // in Angular core. The change detector must also be deregistered when the component40 // is destroyed to prevent memory leaks.41 this._appRef.attachView(componentRef.hostView);42 this.setDisposeFn(() => {43 this._appRef.detachView(componentRef.hostView);44 componentRef.destroy();45 });46 // At this point the component has been instantiated, so we move it to the location in the DOM47 // where we want it to be rendered.48 if (newestOnTop) {49 this._hostDomElement.insertBefore(50 this._getComponentRootNode(componentRef),51 this._hostDomElement.firstChild52 );53 } else {54 this._hostDomElement.appendChild(this._getComponentRootNode(componentRef));55 }56 return componentRef;57 }58 /** Gets the root HTMLElement for an instantiated component. */59 private _getComponentRootNode(componentRef: ComponentRef<any>): HTMLElement {60 return (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;61 }...

Full Screen

Full Screen

base.service.ts

Source:base.service.ts Github

copy

Full Screen

1import {2 ComponentRef,3 ComponentFactoryResolver,4 ApplicationRef,5 Injector,6 Injectable,7 EmbeddedViewRef,8 Inject,9} from '@angular/core';10import {DOCUMENT} from '@angular/common';11@Injectable({providedIn: 'root'})12export abstract class BaseService {13 constructor(14 private resolver: ComponentFactoryResolver,15 private applicationRef: ApplicationRef,16 private injector: Injector,17 @Inject(DOCUMENT) private doc: any,18 ) {19 }20 protected list: ComponentRef<any>[] = [];21 /**22 * 销毁23 *24 * @param component 下标(从0开始或组件引用对象),或不指定时,销毁最新一个25 */26 destroy(component?: number | ComponentRef<any>) {27 if (typeof component === 'number') {28 component = this.list[<number>component];29 }30 if (!component) {31 component = this.list.pop();32 }33 if (component) {34 (<ComponentRef<any>>component).destroy();35 }36 }37 /**38 * 销毁所有39 */40 destroyAll() {41 for (const component of this.list) {42 this.destroy(component);43 }44 }45 /** 动态构建组件 */46 protected build<T>(component: { new(...args: any[]): T }): ComponentRef<T> {47 const componentFactory = this.resolver.resolveComponentFactory(component);48 const componentRef = componentFactory.create(this.injector);49 this.list.push(componentRef);50 const componentRootNode = (componentRef.hostView as EmbeddedViewRef<any>)51 .rootNodes[0] as HTMLElement;52 this.applicationRef.attachView(componentRef.hostView);53 componentRef.onDestroy(() => {54 this.applicationRef.detachView(componentRef.hostView);55 });56 this.doc.body.appendChild(componentRootNode);57 return componentRef;58 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root-decorator';2export default {3};4export const test = () => {5 const ref = componentRef();6 return (7 <div ref={ref}>8 );9};10import { addDecorator } from '@storybook/react';11import { withRootDecorator } from 'storybook-root-decorator';12addDecorator(withRootDecorator);13import { addons } from '@storybook/addons';14import { create } from '@storybook/theming';15addons.setConfig({16 theme: create({17 }),18});19const path = require('path');20module.exports = ({ config }) => {21 config.resolve.alias = {22 'storybook-root-decorator': path.resolve(__dirname, '../src/index.js'),23 };24 return config;25};26module.exports = {27 webpackFinal: require('./webpack.config'),28};29 #root {30 display: flex;31 flex-direction: column;32 align-items: center;33 justify-content: center;34 margin: 0;35 height: 100vh;36 width: 100vw;37 }38import { addDecorator } from '@storybook/react';39import { withRootDecorator } from 'storybook-root-decorator';40addDecorator(withRootDecorator);41import { addons } from '@storybook/addons';42import { create } from '@storybook/theming';43addons.setConfig({44 theme: create({45 }),46});47const path = require('path');48module.exports = ({ config }) => {49 config.resolve.alias = {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root-decorator';2componentRef('app-root');3componentRef('app-root').then((element) => {4});5componentRef('app-root').then((element) => {6});7componentRef('app-root').then((element) => {8});9componentRef('app-root').then((element) => {10});11componentRef('app-root').then((element) => {12});13componentRef('app-root').then

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root-decorator';2const MyComponent = () => {3 const ref = componentRef('my-component');4 return <div ref={ref} />;5};6export default MyComponent;7import { addDecorator } from '@storybook/react';8import { withRootDecorator } from 'storybook-root-decorator';9addDecorator(withRootDecorator);10import { addDecorator } from '@storybook/react';11import { withRootDecorator } from 'storybook-root-decorator';12addDecorator(withRootDecorator);13import { addDecorator } from '@storybook/react';14import { withRootDecorator } from 'storybook-root-decorator';15addDecorator(withRootDecorator);16module.exports = {17 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],18};19import { addDecorator } from '@storybook/react';20import { withRootDecorator } from 'storybook-root-decorator';21addDecorator(withRootDecorator);22 window.__STORYBOOK_ROOT_DECORATOR__ = {23 };24 window.__STORYBOOK_ROOT_DECORATOR__ = {25 };26 window.__STORYBOOK_ROOT_DECORATOR__ = {27 };28 window.__STORYBOOK_ROOT_DECORATOR__ = {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root-decorator';2import { MyComponent } from './MyComponent';3export default {4};5import React from 'react';6import { MyComponent } from './MyComponent';7export const Default = () => <MyComponent />;8import { render } from '@testing-library/react';9import { Default } from './MyComponent.stories';10describe('MyComponent', () => {11 it('should render', () => {12 const { container } = render(Default());13 expect(container).toBeInTheDocument();14 });15});16import { render } from '@testing-library/react';17import { Default } from './MyComponent.stories';18describe('MyComponent', () => {19 it('should render', () => {20 const { container } = render(Default());21 expect(container).toBeInTheDocument();22 });23});24import { render } from '@testing-library/react';25import { Default } from './MyComponent.stories';26describe('MyComponent', () => {27 it('should render', () => {28 const { container } = render(Default());29 expect(container).toBeInTheDocument();30 });31});32import { render } from '@testing-library/react';33import { Default } from './MyComponent.stories';34describe('MyComponent', () => {35 it('should render', () => {36 const { container } = render(Default());37 expect(container).toBeInTheDocument();38 });39});40import { render } from '@testing-library/react';41import { Default } from './MyComponent.stories';42describe('MyComponent', () => {43 it('should render', () => {44 const { container } = render(Default());45 expect(container).toBeInTheDocument();46 });47});48import { render } from '@testing-library/react';49import { Default } from './MyComponent.stories';50describe('MyComponent', () => {51 it('should render', () => {52 const { container } = render(Default());53 expect(container).toBeInTheDocument();54 });55});56import { render } from '@testing-library/react';57import { Default } from './MyComponent.st

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root-decorator';2const ref = componentRef();3ref.setComponent(<MyComponent />);4ref.setComponent(<MyOtherComponent />);5ref.setComponent(null);6ref.setComponent(<MyComponent />);7ref.setComponent(<MyOtherComponent />);8ref.setComponent(null);9import { componentRef } from 'storybook-root-decorator';10const ref = componentRef();11ref.setComponent(<MyComponent />);12ref.setComponent(<MyOtherComponent />);13ref.setComponent(null);14ref.setComponent(<MyComponent />);15ref.setComponent(<MyOtherComponent />);16ref.setComponent(null);17import { componentRef } from 'storybook-root-decorator';18const ref = componentRef();19ref.setComponent(<MyComponent />);20ref.setComponent(<MyOtherComponent />);21ref.setComponent(null);22ref.setComponent(<MyComponent />);23ref.setComponent(<MyOtherComponent />);24ref.setComponent(null);25import { componentRef } from 'storybook-root-decorator';26const ref = componentRef();27ref.setComponent(<MyComponent />);28ref.setComponent(<MyOtherComponent />);29ref.setComponent(null);30ref.setComponent(<MyComponent />);31ref.setComponent(<MyOtherComponent />);32ref.setComponent(null);33import { componentRef } from 'storybook-root-decorator';34const ref = componentRef();35ref.setComponent(<MyComponent />);36ref.setComponent(<MyOtherComponent />);37ref.setComponent(null);38ref.setComponent(<MyComponent />);39ref.setComponent(<MyOtherComponent />);40ref.setComponent(null);41import { componentRef } from 'storybook-root-decorator';42const ref = componentRef();43ref.setComponent(<MyComponent />);44ref.setComponent(<MyOtherComponent />);45ref.setComponent(null);46ref.setComponent(<MyComponent />);47ref.setComponent(<MyOtherComponent />);48ref.setComponent(null);49import { componentRef } from 'storybook-root-decorator';50const ref = componentRef();

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Component, Prop, State, Element, h } from '@stencil/core';2import { getStorybookUI } from '@storybook/ionic';3@Component({4})5export class StorybookRoot {6 @Element() element: HTMLElement;7 @State() storybookUI: any;8 @Prop() componentRef: any;9 async componentWillLoad() {10 this.storybookUI = await getStorybookUI({ port: 7007, onDeviceUI: true });11 }12 render() {13 return (14 {this.storybookUI}15 );16 }17}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { componentRef } from 'storybook-root'2const component = componentRef('button')3component.click()4"scripts": {5}6"scripts": {7}8See [CONTRIBUTING.md](

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