Best JavaScript code snippet using storybook-root
generate.handler.ts
Source:generate.handler.ts
1import { GenerateConfigType, isGeneratableType, isModuleType, isControllerType, isMiddlewareType, GenerateType, isProviderType } from './../types/generate-config.type';2import { Handler } from './handler';3import { red, blue, green } from 'kleur';4import fs from 'fs';5import { resolve } from 'path';6import { ErrorCodeType } from '../types/error-code.type';7import { templates } from '../config.json';8export class GenerateHandler extends Handler {9 insertPath: string = '';10 fileName: string = '';11 className: string = '';12 folderName: string = '';13 generateType: GenerateType = GenerateType.module;14 constructor(private config: GenerateConfigType) {15 super();16 }17 init(): void {18 this.validateTypes();19 this.validateAndSetPaths();20 this.setSimpleName();21 }22 setSimpleName(): void {23 let name = this.config.name.trim();24 if (name == '') {25 console.error(red('Empty Name Error: Name Cannot be empty'));26 process.exit(0)27 }28 if (!name.match(/^[A-Za-z._]+$/)) {29 console.error(red('Name Format Error: Name Can only consist of Letters'));30 process.exit(0)31 }32 name = name.replace(/([A-Z])/g, '_$1').trim()33 if (name[0] == '_') name = name.substring(1);34 name = name.toLowerCase();35 name = name.split('.')[0];36 if (name.match(/module$/i)) {37 name = name.substring(0, name.length - 6);38 }39 if (name.match(/controller$/i)) {40 name = name.substring(0, name.length - 10);41 }42 if (name.match(/middleware$/i)) {43 name = name.substring(0, name.length - 10);44 }45 if (name.match(/provider$/i)) {46 name = name.substring(0, name.length - 10);47 }48 if (name[name.length - 1] == '_') name = name.substring(0, name.length - 1);49 this.fileName = name;50 switch (this.generateType) {51 case GenerateType.module:52 this.fileName += '.module.ts';53 break;54 case GenerateType.controller:55 this.fileName += '.controller.ts';56 break;57 case GenerateType.middleware:58 this.fileName += '.middleware.ts';59 break;60 case GenerateType.provider:61 this.fileName += '.provider.ts';62 break;63 }64 this.folderName = name;65 name = name.replace('_', ' ');66 name = titleCase(name).replace(' ', '');67 this.className = name;68 switch (this.generateType) {69 case GenerateType.module:70 this.className += 'Module';71 break;72 case GenerateType.controller:73 this.className += 'Controller';74 break;75 case GenerateType.middleware:76 this.className += 'Middleware';77 break;78 case GenerateType.provider:79 this.className += 'Provider';80 break;81 }82 }83 validateAndSetPaths() {84 const currentPath: string = process.cwd() + this.getNamePath();85 this.updateBasePath(currentPath);86 this.insertPath = currentPath;87 }88 getNamePath(): string {89 let path: string = '';90 let name: string | undefined;91 let namePaths = this.config.name.split('\\');92 name = namePaths.pop();93 if (namePaths.length > 0) {94 if (name) this.config.name = name;95 return '\\' + namePaths.join('\\');96 }97 namePaths = this.config.name.split('/');98 name = namePaths.pop();99 if (namePaths.length > 0) {100 if (name) this.config.name = name;101 return '\\' + namePaths.join('\\');102 }103 return path;104 }105 validateTypes() {106 if (!isGeneratableType(this.config.type)) {107 console.error(red('Generatable Type entered is Invalid'));108 console.info();109 console.info(blue('Try one of the following commands'));110 console.info(blue(' - To Generate a Module `m` or `module`'));111 console.info(blue(' - To Generate a Controller `c` or `controller`'));112 console.info(blue(' - To Generate a Provider `p` or `provider`'));113 console.info(blue(' - To Generate a Middleware `middleware`'));114 process.exit(0);115 }116 this.generateType = getGenerateType(this.config.type) || GenerateType.module;117 }118 get template(): string {119 let tempName: string = '';120 switch (this.generateType) {121 case GenerateType.module:122 tempName += templates.module;123 break;124 case GenerateType.controller:125 tempName += templates.controller;126 break;127 case GenerateType.middleware:128 tempName += templates.middleware;129 break;130 case GenerateType.provider:131 tempName += templates.provider;132 }133 return tempName;134 }135 process(): void {136 let file: string = this.template;137 file = file.replace(/\$name/g, this.className);138 file = file.replace(/\$route/g, this.folderName);139 const path = this.generateType == GenerateType.module ? (this.folderName + '/' + this.fileName) : this.fileName;140 writeFileSyncRecursive(path, file);141 this.updateModule(path);142 console.info(green('File Generated Successfully'))143 }144 updateModule(path: string) {145 const assetPath: string = resolve(path);146 let aPath = assetPath;147 if (this.generateType === GenerateType.module) {148 const tempPath = assetPath.split('\\');149 tempPath.pop();150 aPath = tempPath.join('\\');151 }152 let modulePath: string = this.findModulePath(aPath);153 let type: "imports" | "controllers" | "middlewares" | "providers" = 154 this.generateType === GenerateType.module ? 'imports' : 155 this.generateType === GenerateType.controller ? 'controllers' : 156 this.generateType === GenerateType.provider ? 'providers' : 157 'middlewares';158 159 insertAssetToModule(type, modulePath, assetPath, this.className);160 }161 findModulePath(path: string): string {162 const pathArr: string[] = path.split('\\');163 pathArr.pop();164 const assetPath: string = pathArr.join('\\');165 const fileNames = fs.readdirSync(assetPath)166 for (const filename of fileNames) {167 if (filename.match(/\.module\.ts$/)) {168 return assetPath + '\\' + filename;169 }170 }171 if (assetPath == this.basePath) {172 console.error(red(`( ${ErrorCodeType.NoModuleError} ) Error: No Parent Module Found`));173 process.exit(1)174 }175 return this.findModulePath(assetPath);176 }177}178function titleCase(str: string) {179 const splitStr = str.toLowerCase().split(' ');180 for (let i = 0; i < splitStr.length; i++) {181 // You do not need to check if i is larger than splitStr length, as your for does that for you182 // Assign it back to the array183 splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);184 }185 // Directly return the joined string186 return splitStr.join(' ');187}188function getGenerateType(type: any): GenerateType | null {189 if (isControllerType(type)) return GenerateType.controller;190 if (isMiddlewareType(type)) return GenerateType.middleware;191 if (isModuleType(type)) return GenerateType.module;192 if (isProviderType(type)) return GenerateType.provider;193 return null;194}195function writeFileSyncRecursive(filename: string, content: string) {196 // -- normalize path separator to '/' instead of path.sep, 197 // -- as / works in node for Windows as well, and mixed \\ and / can appear in the path198 let filepath = filename.replace(/\\/g, '/');199 // -- preparation to allow absolute paths as well200 let root = '';201 if (filepath[0] === '/') {202 root = '/';203 filepath = filepath.slice(1);204 }205 else if (filepath[1] === ':') {206 root = filepath.slice(0, 3); // c:\207 filepath = filepath.slice(3);208 }209 // -- create folders all the way down210 const folders = filepath.split('/').slice(0, -1); // remove last item, file211 folders.reduce(212 (acc, folder) => {213 const folderPath = acc + folder + '/';214 if (!fs.existsSync(folderPath)) {215 fs.mkdirSync(folderPath);216 }217 return folderPath218 },219 root // first 'acc', important220 );221 // -- write file222 fs.writeFileSync(root + filepath, content);223}224function insertAssetToModule(type: 'controllers' | 'middlewares' | 'imports' | 'providers', modulePath: string, assetPath: string, ClassName: string) {225 const path = require('path');226 var relModulePath = '.\\' + path.relative('./', modulePath);227 var file = fs.readFileSync(relModulePath, 'utf-8');228 let moduleObj: string | undefined;229 const tempModule = /@Module\(({[^]+})\)/g.exec(file);230 if (tempModule != null) {231 moduleObj = tempModule[1];232 }233 else {234 console.error(red(`( ${ErrorCodeType.ModuleDecoratorNotFoundError} ) Error: Module Decorator Not Found in ` + relModulePath));235 process.exit(1);236 }237 const typeMatch = new RegExp(`${type}[^:]*:[^\\[]*\\[[^\\]]*\\]`, 'g');238 if (moduleObj.match(typeMatch)) {239 const assetMatch = new RegExp(`(${type}[^:]*:[^\\[]*\\[)`);240 file = file.replace(assetMatch, `$1\r\n\t\t${ClassName},`);241 } else {242 const assetMatch = new RegExp(/(@Module\({)/g);243 file = file.replace(assetMatch, `$1\r\n\t${type}: [\r\n\t\t${ClassName},\r\n\t],`);244 }245 const mPath = modulePath.split('\\');246 mPath.pop();247 file = `import { ${ClassName} } from './${path.relative(mPath.join('\\') + '\\', assetPath).replace('\\', '/').replace('.ts', '')}';\r\n${file}`;248 fs.writeFileSync(relModulePath, file);...
tokenizer.js
Source:tokenizer.js
1function generateType(type, string, index) {2 return {3 type: type,4 value: string,5 index,6 }7}8function tokenizer(input) {9 let current = 0;10 let token = [];11 while (current < input.length) {12 let char = input[current]13 console.log(char,current);14 // ç¬¦å· 15 // []16 if (char === '[' || char === ']') {17 token.push(generateType('paren', char, current))18 current++;19 continue;20 }21 // ()22 if (char === '(' || char === ')') {23 token.push(generateType('paren', char, current))24 current++;25 continue;26 }27 // = ==28 if (char === '=') {29 if (input[current + 1] === '=') {30 token.push(generateType('paren', '==', current))31 current++;32 } else {33 token.push(generateType('paren', char, current))34 }35 current++;36 continue;37 }38 // + - /39 if (/[\+|\-|\/]/.test(char)) {40 token.push(generateType('paren', char, current))41 current++;42 continue;43 }44 // > >=45 if (char === '>') {46 if (input[current + 1] === '=') {47 token.push(generateType('paren', '>=', current))48 current++;49 } else {50 token.push(generateType('paren', char, current))51 }52 current++;53 continue;54 }55 // < <=56 if (char === '<') {57 if (input[current + 1] === '=') {58 token.push(generateType('paren', '<=', current))59 current++;60 } else {61 token.push(generateType('paren', char, current))62 }63 current++;64 continue;65 }66 if (/[\?|\:]/.test(char)) {67 token.push(generateType('paren', char, current))68 current++;69 continue;70 }71 if (/[\.]/.test(char)) {72 token.push(generateType('Call', char, current))73 current++;74 continue;75 }76 if (/[\,]/.test(char)) {77 token.push(generateType('paren', char, current))78 current++;79 continue;80 }81 if (/[\s]/.test(char)) {82 current++;83 continue;84 }85 // ç¬¦å· end86 // åé å符87 if (char === "\"") {88 let value = '';89 let start = current90 char = input[++current];91 while (char !== "\"" && current < input.length) {92 value += char;93 char = input[++current];94 }95 char = input[++current];96 token.push(generateType('string', value, start))97 continue;98 }99 let NUMBERS = /[0-9]/;100 if (NUMBERS.test(char)) {101 let start = current102 let value = '';103 while (NUMBERS.test(char)) {104 value += char;105 char = input[++current];106 }107 token.push(generateType('number', value, start))108 continue;109 }110 let LETTERS_STRET = /[a-z|A-Z|\@|\_]/i;111 if (LETTERS_STRET.test(char)) {112 let value = char;113 let start = ++current114 let LETTERS = /[a-z|A-Z|\_|\s|0-9]/i;115 char = input[current];116 console.log();117 while (LETTERS.test(char) && typeof char !== 'undefined') {118 value += char;119 char = input[++current];120 console.log(char,current);121 }122 token.push(generateType('name', value, start))123 continue;124 }125 throw new TypeError('I dont know what this character is: ' + char);126 }127 return token128}129let array = ['[_FCI10]+"å§å:"+([LastName]=="-"?([Mobile Phone].substring(0,2)=="88"?"è¾
å¡":"æ°ä¼å"):[LastName])+[_FCI8]','2','TURE','[@ad taa 12]']130for (let index = 0; index < array.length; index++) {131 console.log(tokenizer(array[index]));132 ...
generate-type.spec.js
Source:generate-type.spec.js
1const generateType = require('./generate-type');2describe('transforms types for custom use case', () => {3 it('should return Int for integer type', () => {4 const property = { type: 'integer' };5 expect(generateType(property)).toBe('Int');6 });7 it('should return Float for number type', () => {8 const property = { type: 'number' };9 expect(generateType(property)).toBe('Float');10 });11 it('should return Date for date-only type', () => {12 const property = { type: 'date-only' };13 expect(generateType(property)).toBe('Date');14 });15 it('should return Time for time-only type', () => {16 const property = { type: 'time-only' };17 expect(generateType(property)).toBe('Time');18 });19 it('should return DateTimeOnly for datetime-only type', () => {20 const property = { type: 'datetime-only' };21 expect(generateType(property)).toBe('DateTimeOnly');22 });23 it('should return DateTime for datetime', () => {24 const property = { type: 'datetime' };25 expect(generateType(property)).toBe('DateTime');26 });27 it('should return DateTime for datetime with format that is NOT rfc2616', () => {28 const property = { type: 'datetime', format: 'rfc3339' };29 expect(generateType(property)).toBe('DateTime');30 });31 it('should return DateTimeRfc2616 for datetime with format rfc2616', () => {32 const property = { type: 'datetime', format: 'rfc2616' };33 expect(generateType(property)).toBe('DateTimeRfc2616');34 });...
Using AI Code Generation
1import { generateType } from 'storybook-root-decorator';2storiesOf('Button', module)3 .add(4 withInfo(`5${generateType('Button')}6`)(() => <Button />),7 );8import { generateType } from 'storybook-root-decorator';9Button.propTypes = {10 theme: PropTypes.oneOf(['primary', 'secondary']),11 size: PropTypes.oneOf(['small', 'medium', 'large']),12};13Button.defaultProps = {14 onClick: () => {},15};16export default Button;17import { generateType } from 'storybook-root-decorator';18storiesOf('Button', module)19 .add(20 withInfo(`21${generateType('Button')}22`)(() => <Button />),23 );24import { generateType } from 'storybook-root-decorator';25${generateType('Button')}26import { generateType } from 'storybook-root-decorator';27storiesOf('Button', module)28 .add(29 withInfo(`30${generateType('Button')}31`)(() => <Button />),32 );33import { generateType } from 'storybook-root-decorator';34Button.propTypes = {35 theme: PropTypes.oneOf(['primary', 'secondary']),
Using AI Code Generation
1import { generateType } from 'storybook-root-decorator';2const type = generateType('Button');3export default type;4import React from 'react';5import Button from './Button';6import type from './test';7export default {8};9import React from 'react';10import PropTypes from 'prop-types';11import type from './test';12const Button = ({ label }) => {13 return <button>{label}</button>;14};15Button.propTypes = {16};17export default Button;18import React from 'react';19import { shallow } from 'enzyme';20import Button from './Button';21import type from './test';22describe(type, () => {23 it('should render properly', () => {24 const wrapper = shallow(<Button label="Click Me" />);25 expect(wrapper).toMatchSnapshot();26 });27});28import React from 'react';29import { storiesOf } from '@storybook/react';30import { withInfo } from '@storybook/addon-info';31import Button from './Button';32import type from './test';33storiesOf(type, module)34 .addDecorator(withInfo)35 .add('with default props', () => <Button label="Click Me" />, {36 info: {37 },38 });39import React from 'react';40import { storiesOf } from '@storybook/react';41import { withInfo } from '@storybook/addon-info';42import Button from './Button';43import type from './test';44storiesOf(type, module)45 .addDecorator(withInfo)46 .add('with default props', () => <Button label="Click Me" />, {47 info: {48 },49 });50import React from 'react';51import { storiesOf } from '@storybook/react';52import { withInfo } from '@storybook/addon-info';53import Button from './Button';54import type from './test';55storiesOf(type, module)56 .addDecorator(withInfo)57 .add('with default props', () => <Button label="Click Me" />, {58 info: {59 },60 });61import React from 'react';62import { storiesOf } from
Using AI Code Generation
1import { generateType } from 'storybook-root-decorator';2const type = generateType('h1');3const story = () => <div>{type('My Heading')}</div>;4export default story;5import MyHeading from '../test.js';6storiesOf('MyHeading', module).add('default', MyHeading);7import { addDecorator } from '@storybook/react';8import { withRootDecorator } from 'storybook-root-decorator';9addDecorator(withRootDecorator);10import { configure } from '@storybook/react';11import '../storybook/config';12configure(require.context('../storybook', true, /\.stories\.js$/), module);13{14 "scripts": {15 },16 "devDependencies": {17 }18}
Using AI Code Generation
1import { generateType } from 'storybook-root-decorator';2const type = generateType('test', 'test', 'test', 'test', 'test');3console.log(type);4import { generateType } from 'storybook-root-decorator';5const type = generateType('test', 'test', 'test', 'test', 'test');6console.log(type);7import { generateType } from 'storybook-root-decorator';8const type = generateType('test', 'test', 'test', 'test', 'test');9console.log(type);10import { generateType } from 'storybook-root-decorator';11const type = generateType('test', 'test', 'test', 'test', 'test');12console.log(type);13import { generateType } from 'storybook-root-decorator';14const type = generateType('test', 'test', 'test', 'test', 'test');15console.log(type);16import { generateType } from 'storybook-root-decorator';17const type = generateType('test', 'test', 'test', 'test', 'test');18console.log(type);19import { generateType } from 'storybook-root-decorator';20const type = generateType('test', 'test', 'test', 'test', 'test');21console.log(type);22import { generateType } from 'storybook-root-decorator';23const type = generateType('test', 'test', 'test', 'test', 'test');24console.log(type);25import { generateType } from 'storybook-root-decorator';26const type = generateType('test', 'test', 'test', 'test', 'test');27console.log(type);28import { generateType } from 'storybook-root-decorator';29const type = generateType('test', 'test', 'test', '
Using AI Code Generation
1import { generateType } from 'storybook-root-types';2const path = require('path');3const rootPath = path.join(__dirname, '../src');4generateType({ rootPath, outputDir: path.join(__dirname, '../types') });5"scripts": {6}7declare module 'storybook-root-types' {8 export function generateType(options: {9 rootPath: string;10 outputDir: string;11 }): void;12}13import { generateType } from 'storybook-root-types';14generateType({15 rootPath: path.resolve(__dirname, '../src'),16 outputDir: path.resolve(__dirname, '../types'),17});18"paths": {19}20import { generateType } from 'storybook-root-types';21generateType({22 rootPath: path.resolve(__dirname, '../src'),23 outputDir: path.resolve(__dirname, '../types'),24});25"paths": {26}27import { generateType } from 'storybook-root-types';28generateType({29 rootPath: path.resolve(__dirname, '../src'),30 outputDir: path.resolve(__dirname, '../types'),31});32"paths": {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!!