Best JavaScript code snippet using storybook-root
typeExtractor.ts
Source:typeExtractor.ts  
1import ts from "byots";2import { symbolHasFlag, symbolFlagsToString, typeFlagsToString, getSymbolUsageName, getFullTypeName, isDefaultType, parseBoolean } from "./helpers";3export type JSDocProps = {4    [prop: string]: string;5};6export type Types = {7    [name: string]: TypeSchema;8};9export type RootTypes = {10    [name: string]: {11        type: ts.ObjectType;12        schema: TypeSchema;13    };14};15export type NumberTypeSchema = {16    type: "number";17    min?: number;18    max?: number;19    minMessage?: string;20    maxMessage?: string;21    integer?: boolean;22    integerMessage?: string;23    typeMessage?: string;24};25export type StringTypeSchema = {26    type: "string";27    min?: number;28    max?: number;29    regex?: string;30    minMessage?: string;31    maxMessage?: string;32    regexMessage?: string;33    typeMessage?: string;34};35export type ArrayTypeSchema = { type: "array"; itemType: TypeSchema; min?: number; max?: number; minMessage?: string; maxMessage?: string };36export type TypeTypeSchema =37    | { type: "boolean" | "object" | "never" | "date" | "unknown" | "any" | "null" | "undefined"; typeMessage?: string }38    | StringTypeSchema39    | NumberTypeSchema;40export type TypeRefSchema = { type: "ref"; name: string };41export type TypeSchema =42    | { type: "or"; schemas: readonly TypeSchema[] }43    | TypeRefSchema44    | { type: "objectLiteral"; fields: Types }45    | ArrayTypeSchema46    | { type: "tuple"; itemTypes: readonly TypeSchema[] }47    | TypeTypeSchema48    | { type: "numberLiteral"; value: number; message?: string }49    | { type: "stringLiteral"; value: string; message?: string }50    | { type: "booleanLiteral"; value: boolean; message?: string };51export interface TypeSchemaGeneratorSettings {52    checker: ts.TypeChecker;53    otherTypes: RootTypes;54    obfuscateRootTypes?: boolean;55}56let obfuscationMap: {57    [name: string]: string;58} = {};59let obfuscationIndex = 0;60function obfuscate(name: string) {61    if (name in obfuscationMap) {62        return obfuscationMap[name];63    } else {64        let n = obfuscationIndex++ + "";65        obfuscationMap[name] = n;66        return n;67    }68}69function createSchemaForObjectType(type: ts.ObjectType, settings: TypeSchemaGeneratorSettings): TypeSchema {70    let fullName = getFullTypeName(type, settings.checker);71    let serializeName = settings.obfuscateRootTypes ? obfuscate(fullName) : fullName;72    let sym = type.aliasSymbol ?? type.symbol;73    let isInline = sym.name === "__type";74    let schema: TypeSchema = { type: "objectLiteral", fields: {} };75    if (!isInline) {76        if (isDefaultType(sym)) {77            if (fullName === "Date") {78                return { type: "date" };79            }80            console.warn(`Including builtin type \`${fullName}\``);81        }82        if (serializeName in settings.otherTypes) return { type: "ref", name: serializeName };83        settings.otherTypes[serializeName] = { type, schema };84    }85    let properties = settings.checker.getAugmentedPropertiesOfType(type);86    for (let i = 0; i < properties.length; i++) {87        let property = properties[i];88        if (symbolHasFlag(property, ts.SymbolFlags.Method)) {89            console.warn(`Ignoring function \`${property.name}\``);90            continue;91        }92        let jsDocProps: JSDocProps = {};93        property.getJsDocTags().forEach((e) => e.name.startsWith("v-") && (jsDocProps[e.name.substring(2)] = e.text ?? ""));94        // Thx! https://stackoverflow.com/questions/61933695/typescript-compiler-api-get-get-type-of-mapped-property95        let propType = settings.checker.getTypeOfSymbolAtLocation(property, property.declarations?.[0] ?? type.symbol.declarations![0]);96        let sch = createSchemaForType(propType, jsDocProps, settings);97        schema.fields[property.name] = sch;98    }99    return !isInline ? { type: "ref", name: serializeName } : schema;100}101export function createSchemaForType(type: ts.Type, customProps: JSDocProps = {}, settings: TypeSchemaGeneratorSettings): TypeSchema {102    switch (type.flags) {103        case ts.TypeFlags.Object: {104            if (settings.checker.isTupleType(type)) {105                let tupleType = type as ts.TupleType;106                return {107                    type: "tuple",108                    itemTypes: tupleType.resolvedTypeArguments!.map((e) => createSchemaForType(e, customProps, settings)),109                };110            } else if (settings.checker.isArrayType(type)) {111                let arrType = settings.checker.getElementTypeOfArrayType(type)!;112                return createArraySchema(customProps, createSchemaForType(arrType, customProps, settings));113            } else if (114                symbolHasFlag(type.symbol, ts.SymbolFlags.Interface) ||115                symbolHasFlag(type.symbol, ts.SymbolFlags.TypeLiteral) ||116                symbolHasFlag(type.symbol, ts.SymbolFlags.Class)117            ) {118                return createSchemaForObjectType(type as ts.ObjectType, settings);119            } else {120                throw new Error(`Unsupported object type \`${symbolFlagsToString(type.symbol.flags)}\``);121            }122        }123        case ts.TypeFlags.Union:124            return { type: "or", schemas: (type as ts.UnionType).types.map((e) => createSchemaForType(e, customProps, settings)) };125        case ts.TypeFlags.String:126            return createTypeTypeSchema(customProps, createStringSchema(customProps));127        case ts.TypeFlags.Number:128            return createTypeTypeSchema(customProps, createNumberSchema(customProps));129        case ts.TypeFlags.Union | ts.TypeFlags.Boolean:130        case ts.TypeFlags.Boolean:131            return createTypeTypeSchema(customProps, { type: "boolean" });132        case ts.TypeFlags.Never:133            console.warn(`A never type was found, this will always validate to false. \`${settings.checker.typeToString(type)}\``);134            return createTypeTypeSchema(customProps, { type: "never" });135        case ts.TypeFlags.Any:136            console.warn(`An any type was found, this will always validate to true. \`${settings.checker.typeToString(type)}\``);137            return createTypeTypeSchema(customProps, { type: "any" });138        case ts.TypeFlags.NumberLiteral:139            return { type: "numberLiteral", value: (type as ts.NumberLiteralType).value };140        case ts.TypeFlags.StringLiteral:141            return { type: "stringLiteral", value: (type as ts.StringLiteralType).value };142        case ts.TypeFlags.BooleanLiteral:143            return { type: "booleanLiteral", value: type.id === 17 }; // Better way?144        case ts.TypeFlags.Undefined:145            return createTypeTypeSchema(customProps, { type: "undefined" });146        case ts.TypeFlags.Null:147            return createTypeTypeSchema(customProps, { type: "null" });148        case ts.TypeFlags.Unknown:149            return createTypeTypeSchema(customProps, { type: "unknown" });150        case ts.TypeFlags.NonPrimitive:151            return createTypeTypeSchema(customProps, { type: "object" });152        case ts.TypeFlags.TypeParameter:153            throw new Error(`The type of generic \`${(type as ts.TypeParameter).symbol.name}\` must be known at build time.`);154        default:155            // & (ts.TypeFlags.Intersection) will be flattened when using getAugmentedPropertiesOfType, so when it remains it means something is not right156            throw new Error(`Unsupported type \`${typeFlagsToString(type.flags)}\``);157    }158}159export function createSchemaForTypeDeclaration(e: ts.InterfaceDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration, settings: TypeSchemaGeneratorSettings): TypeRefSchema {160    if ((ts.isInterfaceDeclaration(e) || ts.isClassDeclaration(e) || ts.isTypeAliasDeclaration(e)) && e.name) {161        return createSchemaForType(settings.checker.getTypeAtLocation(e), undefined, settings) as TypeRefSchema;162    } else {163        throw new Error(`Unsupported declaration type \`${ts.NodeFlags[e.flags]}\``);164    }165}166function createStringSchema(customProps: JSDocProps): StringTypeSchema {167    let schema: StringTypeSchema = { type: "string" };168    Object.keys(customProps).forEach((prop) => {169        let args = customProps[prop].split(" ");170        switch (prop) {171            case "min":172                schema.min = parseInt(args[0]);173                schema.minMessage = args.slice(1).join(" ") || undefined;174                break;175            case "max":176                schema.max = parseInt(args[0]);177                schema.maxMessage = args.slice(1).join(" ") || undefined;178                break;179            case "regex":180                let arg = args[0];181                schema.regex = arg.startsWith("/") && arg.endsWith("/") ? arg.substring(1, arg.length - 2) : arg;182                schema.regexMessage = args.slice(1).join(" ") || undefined;183                break;184            default:185                console.warn(`String does not support validator \`@v-${prop}\`, ignoring...`);186                break;187        }188    });189    return schema;190}191function createNumberSchema(customProps: JSDocProps): NumberTypeSchema {192    let schema: NumberTypeSchema = { type: "number" };193    Object.keys(customProps).forEach((prop) => {194        let args = customProps[prop].split(" ");195        switch (prop) {196            case "min":197                schema.min = parseInt(args[0]);198                schema.minMessage = args.slice(1).join(" ") || undefined;199                break;200            case "max":201                schema.max = parseInt(args[0]);202                schema.maxMessage = args.slice(1).join(" ") || undefined;203                break;204            case "int":205                schema.integer = parseBoolean(args[0]);206                schema.integerMessage = args.slice(1).join(" ") || undefined;207                break;208            default:209                console.warn(`Number does not support validator \`@v-${prop}\`, ignoring...`);210                break;211        }212    });213    return schema;214}215function createArraySchema(customProps: JSDocProps, itemType: TypeSchema): ArrayTypeSchema {216    let schema: ArrayTypeSchema = { type: "array", itemType };217    Object.keys(customProps).forEach((prop) => {218        let args = customProps[prop].split(" ");219        switch (prop) {220            case "array-min":221                schema.min = parseInt(args[0]);222                schema.minMessage = args.slice(1).join(" ") || undefined;223                break;224            case "array-max":225                schema.max = parseInt(args[0]);226                schema.maxMessage = args.slice(1).join(" ") || undefined;227                break;228            default:229                console.warn(`Array does not support validator \`@v-${prop}\`, ignoring...`);230                break;231        }232    });233    return schema;234}235function createTypeTypeSchema(customProps: JSDocProps, schema: TypeTypeSchema): TypeTypeSchema {236    Object.keys(customProps).forEach((prop) => {237        let args = customProps[prop].split(" ");238        switch (prop) {239            case "type":240                schema.typeMessage = args.join(" ") || undefined;241                break;242            default:243                console.warn(`Type constraint does not support validator \`@v-${prop}\`, ignoring...`);244                break;245        }246    });247    return schema;248}249export function rootTypesToTypes(rootTypes: RootTypes): Types {250    let obj: Types = {};251    Object.keys(rootTypes).forEach((e) => (obj[e] = rootTypes[e].schema));252    return obj;...jsdoc.js
Source:jsdoc.js  
1/* eslint-disable react/no-unused-prop-types */2/* eslint-disable react/require-default-props */3import React from 'react';4import PropTypes from 'prop-types';5export const JsDocProps = () => <div>JSDoc with PropTypes!</div>;6JsDocProps.propTypes = {7  /**8   * should not be visible since it's ignored.9   * @ignore10   */11  case0: PropTypes.string,12  /**13   * simple description.14   */15  case1: PropTypes.string,16  /**17   * multi18   * lines19   * description20   */21  case2: PropTypes.string,22  /**23   * *description* **with** `formatting`24   */25  case3: PropTypes.string,26  /**27   * simple description and dummy JSDoc tag.28   * @param event29   */30  case4: PropTypes.string,31  /**32   * @param event33   */34  case5: PropTypes.string,35  /**36   * simple description with a @.37   */38  case6: PropTypes.string,39  case7: PropTypes.func,40  /**41   * func with a simple description.42   */43  case8: PropTypes.func,44  /**45   * @param event46   */47  case9: PropTypes.func,48  /**49   * param with name50   * @param event51   */52  case10: PropTypes.func,53  /**54   * param with name & type55   * @param {SyntheticEvent} event56   */57  case11: PropTypes.func,58  /**59   * param with name, type & description60   * @param {SyntheticEvent} event - React's original event61   */62  case12: PropTypes.func,63  /**64   * param with type65   * @param {SyntheticEvent}66   */67  case13: PropTypes.func,68  /**69   * param with type & description70   * @param {SyntheticEvent} - React's original event71   */72  case14: PropTypes.func,73  /**74   * param with name & description75   * @param event - React's original event76   */77  case15: PropTypes.func,78  /**79   * autofix event-80   * @param event- React's original event81   */82  case16: PropTypes.func,83  /**84   * autofix event.85   * @param event.86   * @returns {string}87   */88  case17: PropTypes.func,89  /**90   * with an empty param.91   * @param92   */93  case18: PropTypes.func,94  /**95   * with multiple empty params.96   * @param97   * @param98   * @param99   */100  case19: PropTypes.func,101  /**102   * with arg alias.103   * @arg event104   */105  case20: PropTypes.func,106  /**107   * with argument alias.108   * @argument event109   */110  case21: PropTypes.func,111  /**112   * with multiple params.113   * @param {SyntheticEvent} event114   * @param {string} stringValue115   * @param {number} numberValue116   */117  case22: PropTypes.func,118  /**119   * with an empty returns120   * @returns121   */122  case23: PropTypes.func,123  /**124   * with a returns with a type125   * @returns {SyntheticEvent}126   */127  case24: PropTypes.func,128  /**129   * with a returns with a type & description130   * @returns {SyntheticEvent} - React's original event131   */132  case25: PropTypes.func,133  /**134   * single param and a returns135   * @param {string} stringValue136   * @returns {SyntheticEvent} - React's original event137   */138  case26: PropTypes.func,139  /**140   * multiple params and a returns141   * @param {string} stringValue142   * @param {number} numberValue143   * @returns {SyntheticEvent} - React's original event144   */145  case27: PropTypes.func,146  /**147   * multiple returns148   * @returns {SyntheticEvent} - React's original event149   * @returns {string} - Second returns150   */151  case28: PropTypes.func,152  /**153   * param with unsupported JSDoc tags154   * @param {SyntheticEvent} event - React's original event155   * @type {number}156   * @version 2157   */158  case29: PropTypes.func,159  /**160   * param record type161   * @param {{a: number, b: string}} myType162   */163  case30: PropTypes.func,164  /**165   * param array type166   * @param {string[]} myType167   */168  case31: PropTypes.func,169  /**170   * param union type171   * @param {(number|boolean)} myType172   */173  case32: PropTypes.func,174  /**175   * param any type176   * @param {*} myType177   */178  case33: PropTypes.func,179  /**180   * param repeatable type181   * @param {...number} myType182   */183  case34: PropTypes.func,184  /**185   * optional param186   * @param {number} [myType]187   */188  case35: PropTypes.func,189  /**190   * optional param191   * @param {number} [myType]192   */193  case36: PropTypes.func,194  /**195   * dot in param name196   * @param {number} my.type197   */198  case37: PropTypes.func,199  /**200   * returns record type201   * @returns {{a: number, b: string}}202   */203  case38: PropTypes.func,204  /**205   * returns array type206   * @returns {string[]}207   */208  case39: PropTypes.func,209  /**210   * returns union type211   * @returns {(number|boolean)}212   */213  case40: PropTypes.func,214  /**215   * returns any type216   * @returns {*}217   */218  case41: PropTypes.func,219  /**220   * returns primitive221   * @returns {string}222   */223  case42: PropTypes.func,224  /**225   * returns void226   * @returns {void}227   */228  case43: PropTypes.func,229};230export const FailingJsDocProps = () => <div>Failing JSDoc Props!</div>;231FailingJsDocProps.propTypes = {232  /**233   * autofix event.234   * @param event.235   */236  case: PropTypes.func,...index.ts
Source:index.ts  
1const interfaceNameRegex = /public class ([a-zA-Z0-9?]+) /g;2const propertyRegex = /public ([a-zA-Z?\<\>\[\]]+ [a-zA-Z0-9]+).*;/g;3interface JsDocProperty {4    property: string;5    type: string;6}7const typeMappings = {8    string: "string",9    int: "number",10    decimal: "number",11    float: "number",12    bool: "boolean",13    object: "*",14};15const jsdocType = (typeName: string, props: string) => {16    return `17/**18 * @typedef {Object} ${typeName}${props}19 **/20    `;21};22const jsdocProp = (propertyName: string, propertyType: string) => {23    const isList =24        propertyType.includes("IEnumerable") || propertyType.includes("List");25    const splitComponents = propertyType.split("<");26    propertyType =27        splitComponents.length > 128            ? splitComponents[1].replace(">", "")29            : splitComponents[0];30    let jsdocType = "any";31    if (Object.keys(typeMappings).includes(propertyType)) {32        jsdocType = typeMappings[propertyType];33    }34    if (isList) {35        jsdocType = `${jsdocType}[]`;36    }37    return `\n * @property {${jsdocType}} ${propertyName}`;38};39export const convertClassToJsdocType = (40    csharpClass: string,41    classPrefix: string,42    classSuffix: string43): string => {44    const interfaceName = `${classPrefix}${extractInterfaceName(45        csharpClass46    )}${classSuffix}`;47    const props = extractProperties(csharpClass);48    const jsdocProps = props49        .map((property) => {50            return jsdocProp(property.property, property.type);51        })52        .join("");53    return jsdocType(interfaceName, jsdocProps);54};55const extractInterfaceName = (tsInterface: string): string => {56    interfaceNameRegex.lastIndex = 0;57    let matches = interfaceNameRegex.exec(tsInterface);58    if (!matches || matches.length === 0) {59        return "";60    }61    return matches[matches.length - 1];62};63const extractProperties = (csharpClass: string): JsDocProperty[] => {64    propertyRegex.lastIndex = 0;65    let matches = csharpClass.match(propertyRegex);66    if (!matches) {67        return [];68    }69    let jsdocProps: JsDocProperty[] = matches.map((match) => {70        const components = match.split(" ");71        return {72            property: components[2].trim().replace(";", ""),73            type: components[1].trim(),74        };75    });76    return jsdocProps;...Using AI Code Generation
1import { JsDocProps } from 'storybook-root';2const Test = () => {3  return <div>{JsDocProps}</div>;4};5export default Test;6import { configure } from '@storybook/react';7import { addDecorator } from '@storybook/react';8import { withInfo } from '@storybook/addon-info';9import { withKnobs } from '@storybook/addon-knobs';10import { withOptions } from '@storybook/addon-options';11import { JsDocProps } from 'storybook-root';12addDecorator(13  withInfo({14  })15);16addDecorator(withKnobs);17addDecorator(18  withOptions({Using AI Code Generation
1var JsDocProps = require('storybook-root').JsDocProps;2var React = require('react');3var ReactDOM = require('react-dom');4var MyComponent = require('./myComponent');5var MyComponentDoc = require('./myComponentDoc');6var MyComponentDocProps = require('./myComponentDocProps');7var myComponentDoc = new MyComponentDoc();8var myComponentDocProps = new MyComponentDocProps();9ReactDOM.render(10  <MyComponent doc={myComponentDoc} docProps={myComponentDocProps} />,11  document.getElementById('root')12);13var JsDocProps = require('storybook-root').JsDocProps;14var MyComponentDocProps = function () {15  JsDocProps.call(this);16  this.prop1 = 'prop1';17  this.prop2 = 'prop2';18  this.prop3 = 'prop3';19  this.prop4 = 'prop4';20  this.prop5 = 'prop5';21};22MyComponentDocProps.prototype = Object.create(JsDocProps.prototype);23MyComponentDocProps.prototype.constructor = MyComponentDocProps;24module.exports = MyComponentDocProps;25var JsDoc = require('storybook-root').JsDoc;26var MyComponentDoc = function () {27  JsDoc.call(this);28  this.description = 'MyComponent description';29  this.displayName = 'MyComponent';30  this.methods = [];31  this.props = {};32  this.props.prop1 = {33    type: {34    },35  };36  this.props.prop2 = {37    type: {38    },39  };40  this.props.prop3 = {41    type: {42    },43  };44  this.props.prop4 = {45    type: {46    },47  };48  this.props.prop5 = {49    type: {50    },51  };52};53MyComponentDoc.prototype = Object.create(JsDocUsing AI Code Generation
1import { JsDocProps } from 'storybook-root'2const MyComponent = () => {3}4JsDocProps(MyComponent, 'MyComponent')5JsDocProps(MyComponent)6JsDocProps(MyComponent, 'MyComponent', {Using AI Code Generation
1import JsDocProps from 'storybook-root/JsDocProps';2import { storiesOf } from '@storybook/react';3import { withKnobs } from '@storybook/addon-knobs/react';4import { withInfo } from '@storybook/addon-info';5import Button from './Button';6storiesOf('Button', module)7  .addDecorator(withKnobs)8  .addDecorator(withInfo)9  .add('Button', () => <Button />, {10    info: {11      text: JsDocProps(Button)12    }13  });14import React from 'react';15import PropTypes from 'prop-types';16 * @param {string} label - The label of the button17 * @param {string} [type='button'] - The type of the button18 * @param {string} [className=''] - The class of the button19 * @param {function} [onClick=() => {}] - The onClick function of the button20 * @param {string} [style=''] - The style of the button21 * @param {string} [disabled=''] - The disabled state of the button22 * @returns {React.Component} - A button23const Button = ({24}) => (25    type={type}26    className={className}27    onClick={onClick}28    style={style}29    disabled={disabled}30    {label}31);32Button.propTypes = {33};34Button.defaultProps = {35  onClick: () => {},36  style: {},37};38export default Button;39import { addDecorator } from '@storybook/react';40import { withKnobs } from '@storybook/addon-knobs/react';41addDecorator(withKnobs);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!!
