Best JavaScript code snippet using storybook-root
compodoc.ts
Source:compodoc.ts
1/* eslint-disable no-underscore-dangle */2/* global window */3import type { ArgType, ArgTypes } from '@storybook/api';4import { logger } from '@storybook/client-logger';5import type {6 Argument,7 Class,8 CompodocJson,9 Component,10 Injectable,11 Method,12 Pipe,13 Property,14 Directive,15 JsDocTag,16} from './types';17export const isMethod = (methodOrProp: Method | Property): methodOrProp is Method => {18 return (methodOrProp as Method).args !== undefined;19};20export const setCompodocJson = (compodocJson: CompodocJson) => {21 // @ts-ignore22 window.__STORYBOOK_COMPODOC_JSON__ = compodocJson;23};24// @ts-ignore25export const getCompodocJson = (): CompodocJson => window.__STORYBOOK_COMPODOC_JSON__;26export const checkValidComponentOrDirective = (component: Component | Directive) => {27 if (!component.name) {28 throw new Error(`Invalid component ${JSON.stringify(component)}`);29 }30};31export const checkValidCompodocJson = (compodocJson: CompodocJson) => {32 if (!compodocJson || !compodocJson.components) {33 throw new Error('Invalid compodoc JSON');34 }35};36const hasDecorator = (item: Property, decoratorName: string) =>37 item.decorators && item.decorators.find((x: any) => x.name === decoratorName);38const mapPropertyToSection = (item: Property) => {39 if (hasDecorator(item, 'ViewChild')) {40 return 'view child';41 }42 if (hasDecorator(item, 'ViewChildren')) {43 return 'view children';44 }45 if (hasDecorator(item, 'ContentChild')) {46 return 'content child';47 }48 if (hasDecorator(item, 'ContentChildren')) {49 return 'content children';50 }51 return 'properties';52};53const mapItemToSection = (key: string, item: Method | Property): string => {54 switch (key) {55 case 'methods':56 case 'methodsClass':57 return 'methods';58 case 'inputsClass':59 return 'inputs';60 case 'outputsClass':61 return 'outputs';62 case 'properties':63 case 'propertiesClass':64 if (isMethod(item)) {65 throw new Error("Cannot be of type Method if key === 'propertiesClass'");66 }67 return mapPropertyToSection(item);68 default:69 throw new Error(`Unknown key: ${key}`);70 }71};72export const findComponentByName = (name: string, compodocJson: CompodocJson) =>73 compodocJson.components.find((c: Component) => c.name === name) ||74 compodocJson.directives.find((c: Directive) => c.name === name) ||75 compodocJson.pipes.find((c: Pipe) => c.name === name) ||76 compodocJson.injectables.find((c: Injectable) => c.name === name) ||77 compodocJson.classes.find((c: Class) => c.name === name);78const getComponentData = (component: Component | Directive) => {79 if (!component) {80 return null;81 }82 checkValidComponentOrDirective(component);83 const compodocJson = getCompodocJson();84 if (!compodocJson) {85 return null;86 }87 checkValidCompodocJson(compodocJson);88 const { name } = component;89 const metadata = findComponentByName(name, compodocJson);90 if (!metadata) {91 logger.warn(`Component not found in compodoc JSON: '${name}'`);92 }93 return metadata;94};95const displaySignature = (item: Method): string => {96 const args = item.args.map(97 (arg: Argument) => `${arg.name}${arg.optional ? '?' : ''}: ${arg.type}`98 );99 return `(${args.join(', ')}) => ${item.returnType}`;100};101const extractTypeFromValue = (defaultValue: any) => {102 const valueType = typeof defaultValue;103 return defaultValue || valueType === 'number' || valueType === 'boolean' || valueType === 'string'104 ? valueType105 : null;106};107const extractEnumValues = (compodocType: any) => {108 const compodocJson = getCompodocJson();109 const enumType = compodocJson?.miscellaneous?.enumerations?.find((x) => x.name === compodocType);110 if (enumType?.childs.every((x) => x.value)) {111 return enumType.childs.map((x) => x.value);112 }113 if (typeof compodocType !== 'string' || compodocType.indexOf('|') === -1) {114 return null;115 }116 try {117 return compodocType.split('|').map((value) => JSON.parse(value));118 } catch (e) {119 return null;120 }121};122export const extractType = (property: Property, defaultValue: any) => {123 const compodocType = property.type || extractTypeFromValue(defaultValue);124 switch (compodocType) {125 case 'string':126 case 'boolean':127 case 'number':128 return { name: compodocType };129 case undefined:130 case null:131 return { name: 'void' };132 default: {133 const resolvedType = resolveTypealias(compodocType);134 const enumValues = extractEnumValues(resolvedType);135 return enumValues ? { name: 'enum', value: enumValues } : { name: 'object' };136 }137 }138};139const castDefaultValue = (property: Property, defaultValue: any) => {140 const compodocType = property.type;141 // All these checks are necessary as compodoc does not always set the type ie. @HostBinding have empty types.142 // null and undefined also have 'any' type143 if (['boolean', 'number', 'string', 'EventEmitter'].includes(compodocType)) {144 switch (compodocType) {145 case 'boolean':146 return defaultValue === 'true';147 case 'number':148 return Number(defaultValue);149 case 'EventEmitter':150 return undefined;151 default:152 return defaultValue;153 }154 } else {155 switch (defaultValue) {156 case 'true':157 return true;158 case 'false':159 return false;160 case 'null':161 return null;162 case 'undefined':163 return undefined;164 default:165 return defaultValue;166 }167 }168};169const extractDefaultValueFromComments = (property: Property, value: any) => {170 let commentValue = value;171 property.jsdoctags.forEach((tag: JsDocTag) => {172 if (['default', 'defaultvalue'].includes(tag.tagName.escapedText)) {173 // @ts-ignore174 const dom = new window.DOMParser().parseFromString(tag.comment, 'text/html');175 commentValue = dom.body.textContent;176 }177 });178 return commentValue;179};180const extractDefaultValue = (property: Property) => {181 try {182 let value: string | boolean = property.defaultValue?.replace(/^'(.*)'$/, '$1');183 value = castDefaultValue(property, value);184 if (value == null && property.jsdoctags?.length > 0) {185 value = extractDefaultValueFromComments(property, value);186 }187 return value;188 } catch (err) {189 logger.debug(`Error extracting ${property.name}: ${property.defaultValue}`);190 return undefined;191 }192};193const resolveTypealias = (compodocType: string): string => {194 const compodocJson = getCompodocJson();195 const typeAlias = compodocJson?.miscellaneous?.typealiases?.find((x) => x.name === compodocType);196 return typeAlias ? resolveTypealias(typeAlias.rawtype) : compodocType;197};198export const extractArgTypesFromData = (componentData: Class | Directive | Injectable | Pipe) => {199 const sectionToItems: Record<string, ArgType[]> = {};200 const compodocClasses = ['component', 'directive'].includes(componentData.type)201 ? ['propertiesClass', 'methodsClass', 'inputsClass', 'outputsClass']202 : ['properties', 'methods'];203 type COMPODOC_CLASS =204 | 'properties'205 | 'methods'206 | 'propertiesClass'207 | 'methodsClass'208 | 'inputsClass'209 | 'outputsClass';210 compodocClasses.forEach((key: COMPODOC_CLASS) => {211 const data = (componentData as any)[key] || [];212 data.forEach((item: Method | Property) => {213 const section = mapItemToSection(key, item);214 const defaultValue = isMethod(item) ? undefined : extractDefaultValue(item as Property);215 const type =216 isMethod(item) || (section !== 'inputs' && section !== 'properties')217 ? { name: 'void' }218 : extractType(item as Property, defaultValue);219 const action = section === 'outputs' ? { action: item.name } : {};220 const argType = {221 name: item.name,222 description: item.rawdescription || item.description,223 defaultValue,224 type,225 ...action,226 table: {227 category: section,228 type: {229 summary: isMethod(item) ? displaySignature(item) : item.type,230 required: isMethod(item) ? false : !item.optional,231 },232 defaultValue: { summary: defaultValue },233 },234 };235 if (!sectionToItems[section]) {236 sectionToItems[section] = [];237 }238 sectionToItems[section].push(argType);239 });240 });241 const SECTIONS = [242 'properties',243 'inputs',244 'outputs',245 'methods',246 'view child',247 'view children',248 'content child',249 'content children',250 ];251 const argTypes: ArgTypes = {};252 SECTIONS.forEach((section) => {253 const items = sectionToItems[section];254 if (items) {255 items.forEach((argType) => {256 argTypes[argType.name] = argType;257 });258 }259 });260 return argTypes;261};262export const extractArgTypes = (component: Component | Directive) => {263 const componentData = getComponentData(component);264 return componentData && extractArgTypesFromData(componentData);265};266export const extractComponentDescription = (component: Component | Directive) => {267 const componentData = getComponentData(component);268 return componentData && (componentData.rawdescription || componentData.description);...
Using AI Code Generation
1import { compodocType } from 'storybook-root';2import { compodocType } from 'storybook-root';3import { compodocType } from 'storybook-root';4import { compodocType } from 'storybook-root';5import { compodocType } from 'storybook-root';6import { compodocType } from 'storybook-root';7import { compodocType } from 'storybook-root';8import { compodocType } from 'storybook-root';9import { compodocType } from 'storybook-root';10import { compodocType } from 'storybook-root';11import { compodocType } from 'storybook-root';12import { compodocType } from 'storybook-root';13import { compodocType } from 'storybook-root';14import { compodocType } from 'storybook-root';15import { compodocType } from 'storybook-root';16import { compodocType } from 'storybook-root';17import { compodocType } from 'storybook-root';18import { compodocType } from '
Using AI Code Generation
1import {compodocType} from 'storybook-root-module';2import {compodocType} from 'storybook-root-module';3import {compodocType} from 'storybook-root-module';4import {compodocType} from 'storybook-root-module';5import {compodocType} from 'storybook-root-module';6import {compodocType} from 'storybook-root-module';7import {compodocType} from 'storybook-root-module';8import {compodocType} from 'storybook-root-module';9import {compodocType} from 'storybook-root-module';10import {compodocType} from 'storybook-root-module';
Using AI Code Generation
1import { compodocType } from 'storybook-root';2export const CompodocType = compodocType;3import { CompodocType } from './test.js';4storiesOf('test', module)5 .add('CompodocType', () => {6 return {7 components: {8 }9 };10 });
Using AI Code Generation
1import { compodocType } from 'storybook-root';2export function compodocType(type) {3 return type;4}5import { compodocType } from 'storybook-root';6export function compodocType(type) {7 return type;8}9import { compodocType } from 'storybook-root';10export function compodocType(type) {11 return type;12}13import { compodocType } from 'storybook-root';14export function compodocType(type) {15 return type;16}17import { compodocType } from 'storybook-root';18export function compodocType(type) {19 return type;20}21import { compodocType } from 'storybook-root';22export function compodocType(type) {23 return type;24}25import { compodocType } from 'storybook-root';26export function compodocType(type) {27 return type;28}29import { compodocType } from 'storybook-root';30export function compodocType(type) {31 return type;32}33import { compodocType } from 'storybook-root';34export function compodocType(type) {35 return type;36}37import { compodocType } from 'storybook-root';
Using AI Code Generation
1import { compodocType } from 'storybook-root';2export default {3};4export const test = () => ({5});6@Component({7})8export class TestComponent {}9div {10 background: red;11}12import { compodocType } from 'storybook-root';13export default {14};15export const test = () => ({16});17import { async, ComponentFixture, TestBed } from '@angular/core/testing';18import { TestComponent } from './test.component';19describe('TestComponent', () => {20 let component: TestComponent;21 let fixture: ComponentFixture<TestComponent>;22 beforeEach(async(() => {23 TestBed.configureTestingModule({24 }).compileComponents();25 }));26 beforeEach(() => {27 fixture = TestBed.createComponent(TestComponent);28 component = fixture.componentInstance;29 fixture.detectChanges();30 });31 it('should create', () => {32 expect(component).toBeTruthy();33 });34});35import { OnInit } from '@angular/core';36export declare class TestComponent implements OnInit {37 constructor();38 ngOnInit(): void;39}40{41 "metadata": {42 "TestComponent": {43 {44 "expression": {45 },46 {47 "div {\n background: red;\n}"48 }
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!!