Best JavaScript code snippet using storybook-root
index.ts
Source:index.ts
1import fs from 'fs-extra';2import os from 'os';3import path from 'path';4import findCacheDir from 'find-cache-dir';5import { getOptions } from 'loader-utils';6import { withDefaultConfig } from 'react-docgen-typescript';7import { createHash } from 'crypto';8import { IOptions } from './types';9import { computeComponentName } from './defaults';10module.exports.default = async function(source) {11 const options: IOptions = getOptions(this) || {};12 const {13 forceRegenerate,14 fileNameResolver,15 transformProps = tables => tables[0],16 propFilter,17 componentNameResolver = computeComponentName,18 shouldExtractLiteralValuesFromEnum,19 savePropValueAsString,20 } = options;21 const parserOptions = { propFilter, componentNameResolver, shouldExtractLiteralValuesFromEnum, savePropValueAsString };22 const parser = withDefaultConfig(parserOptions);23 const cacheFolder = findCacheDir({ name: 'webpack-react-docgen-typescript' }) || os.tmpdir();24 //create cache folder if it doesnt exist25 if (!fs.existsSync(cacheFolder)) {26 fs.mkdirSync(cacheFolder, { recursive: true });27 } 28 const cachedFileName = fileNameResolver ? fileNameResolver({ ...this, cacheFolder }) :29 path.join(cacheFolder, createHash('md5').update(this.resourcePath).digest('hex'));30 if (!cachedFileName) {31 return source;32 }33 const parseTypes = async () => {34 let parsed;35 try {36 parsed = parser.parse(this.resourcePath);37 } catch (e) {38 console.warn(`\nTS: issue parsing ${this.resourcePath}`)39 } 40 const result = parsed && Array.isArray(parsed) && parsed.length > 0 ? parsed : {};41 fs.writeFileSync(cachedFileName, JSON.stringify(result));42 return result;43 }44 let docgenInfo = null;45 if (forceRegenerate) {46 //force remove the cached file47 if (fs.existsSync(cachedFileName)) {48 fs.unlink(cachedFileName);49 } 50 }51 52 //check if the options have changed53 const optionsHash = createHash('md5').update(JSON.stringify(parserOptions)).digest('hex').substr(0, 6);54 const optionsFileName = path.join(cacheFolder, '--options--.cache');55 if (fs.existsSync(optionsFileName)) {56 const lastOptions = fs.readFileSync(optionsFileName, 'utf8');57 if (lastOptions !== optionsHash) {58 //empty the cache folder files59 fs.emptyDirSync(cacheFolder);60 //last options are different from current options61 fs.writeFileSync(optionsFileName, optionsHash);62 }63 } else {64 fs.writeFileSync(optionsFileName, optionsHash);65 }66 67 if (fs.existsSync(cachedFileName)) {68 const cacheStats = fs.statSync(cachedFileName);69 const fileStats = fs.statSync(this.resourcePath);70 if (cacheStats.mtime.getTime() >= fileStats.mtime.getTime()) {71 const fileData = fs.readFileSync(cachedFileName);72 docgenInfo = JSON.parse(fileData);73 } else {74 docgenInfo = await parseTypes();75 }76 } else {77 //does not exist in cache, re-generate78 docgenInfo = await parseTypes();79 }80 if (Array.isArray(docgenInfo) && docgenInfo.length > 0) {81 docgenInfo = transformProps(docgenInfo);82 if (docgenInfo) {83 const doc = Array.isArray(docgenInfo) && docgenInfo.length > 0 ? docgenInfo[0] : docgenInfo;84 return source + `85 try {86 //@ts-ignore87 ${doc.displayName}.__docgenInfo = ${JSON.stringify(doc)};88 } catch (e) {89 }90 `;91 } 92 }93 return source;...
index.js
Source:index.js
1import PropTypes from 'prop-types';2const PropTypesMap = new Map();3Object.keys(PropTypes).forEach((typeName) => {4 const type = PropTypes[typeName];5 PropTypesMap.set(type, typeName);6 PropTypesMap.set(type.isRequired, typeName);7});8const isNotEmpty = obj => obj && obj.props && Object.keys(obj.props).length > 0;9const hasDocgen = type => isNotEmpty(type.__docgenInfo);10const propsFromDocgen = (type) => {11 const props = {};12 const docgenInfoProps = type.__docgenInfo.props;13 Object.keys(docgenInfoProps).forEach((property) => {14 const docgenInfoProp = docgenInfoProps[property];15 const defaultValueDesc = docgenInfoProp.defaultValue || {};16 const propType = docgenInfoProp.flowType || docgenInfoProp.type || 'other';17 props[property] = {18 property,19 propType,20 required: docgenInfoProp.required,21 description: docgenInfoProp.description,22 defaultValue: defaultValueDesc.value23 };24 });25 return props;26};27const propsFromPropTypes = (type) => {28 const props = {};29 if (type.propTypes) {30 Object.keys(type.propTypes).forEach((property) => {31 const typeInfo = type.propTypes[property];32 const required = typeInfo.isRequired === undefined;33 const docgenInfo =34 type.__docgenInfo && type.__docgenInfo.props && type.__docgenInfo.props[property];35 const description = docgenInfo ? docgenInfo.description : null;36 let propType = PropTypesMap.get(typeInfo) || 'other';37 if (propType === 'other') {38 if (docgenInfo && docgenInfo.type) {39 propType = docgenInfo.type.name;40 }41 }42 props[property] = { property, propType, required, description };43 });44 }45 if (type.defaultProps) {46 Object.keys(type.defaultProps).forEach((property) => {47 const value = type.defaultProps[property];48 if (value === undefined) {49 return;50 }51 if (!props[property]) {52 props[property] = { property };53 }54 props[property].defaultValue = value;55 });56 }57 return props;58};59const getPropDefinitions = (type) => {60 if (!type) {61 return null;62 }63 const propDefinitionsMap = hasDocgen(type)64 ? propsFromDocgen(type)65 : propsFromPropTypes(type);66 const propDefinitions = Object.values(propDefinitionsMap);67 return propDefinitions;68};...
filterDocgenInfoProps.js
Source:filterDocgenInfoProps.js
1/**2 * @license3 *4 * Copyright IBM Corp. 20215 *6 * This source code is licensed under the Apache-2.0 license found in the7 * LICENSE file in the root directory of this source tree.8 */9/**10 * Filteres out internal properties from React Docgen info.11 *12 * @param {React.Component} Component The component.13 * @returns {React.Component} The given component.14 */15function filterDocgenInfoProps(Component) {16 const { __docgenInfo: docgenInfo } = Component;17 docgenInfo.props = Object.keys(docgenInfo.props).reduce(18 (acc, key) =>19 /@internal/i.test(docgenInfo.props[key].description)20 ? acc21 : {22 ...acc,23 [key]: docgenInfo.props[key],24 },25 {}26 );27 return Component;28}...
Using AI Code Generation
1import { docgenInfo } from 'storybook-root';2export default {3 parameters: {4 docs: {5 page: () => docgenInfo(MyComponent)6 }7 }8};9import { addDecorator } from '@storybook/react';10import { withDocs } from 'storybook-addon-docgen';11addDecorator(withDocs);12module.exports = async ({ config }) => {13 config.resolve.alias['storybook-root'] = path.resolve(__dirname, '../');14 return config;15};
Using AI Code Generation
1import { docgenInfo } from 'storybook-addon-docgen-info/dist/docgenInfo';2import { Button } from '@storybook/react/demo';3export default {4 parameters: {5 info: {6 propTables: docgenInfo(Button)7 }8 }9};
Using AI Code Generation
1const fs = require('fs');2const path = require('path');3const { docgenInfo } = require('./node_modules/@storybook/react/dist/server/docgen');4const storybookDir = path.resolve(__dirname, './node_modules/@storybook/react/dist/client/preview');5const storybookRequire = require.context(storybookDir, true, /stories\.js$/);6 .keys()7 .reduce((acc, key) => {8 const { default: component } = storybookRequire(key);9 const docgen = docgenInfo(component);10 acc[key] = docgen;11 return acc;12 }, {});13fs.writeFileSync('docgenMap.json', JSON.stringify(docgenMap, null, 2));14{15 "./stories/Alert.stories.js": {16 "props": {17 "children": {18 "type": {19 }20 },21 "className": {22 "type": {23 }24 },25 "color": {26 "defaultValue": {27 },28 "type": {29 {30 },31 {32 },33 {34 },
Using AI Code Generation
1import {docgenInfo} from 'storybook-root';2const {info} = docgenInfo(__dirname, 'MyComponent');3console.log(info);4import React from 'react';5import {storiesOf} from '@storybook/react';6import MyComponent from './MyComponent';7storiesOf('MyComponent', module)8 .add('with text', () => (9 ));
Using AI Code Generation
1import { docgenInfo } from 'storybook-root';2console.log(docgenInfo('component-name'));3import { docgenInfo } from 'storybook-addon-docgen';4export { docgenInfo };5import { setAddon } from '@storybook/react';6import docgenInfoAddon from 'storybook-addon-docgen';7setAddon(docgenInfoAddon);8module.exports = (storybookBaseConfig, configType) => {9 storybookBaseConfig.module.rules.push({10 });11 return storybookBaseConfig;12};13import 'storybook-addon-docgen/register';14import { setAddon } from '@storybook/react';15import docgenInfoAddon, { setDefaults } from 'storybook-addon-docgen';16setDefaults({17});18setAddon(docgenInfoAddon);19#### `setDefaults(options)`20Default: `{}`21The `propFilter` option to pass to [react-docgen](
Using AI Code Generation
1import { docgenInfo } from 'storybook-root';2import { getDocgenSection } from 'storybook-readme';3import { writeFileSync } from 'fs';4import { join } from 'path';5const component = 'Button';6const docgen = docgenInfo(component);7const markdown = getDocgenSection(docgen);8writeFileSync(join(__dirname, `../docs/${component}.md`), markdown);
Using AI Code Generation
1const Button = ({ children, onClick }) => (2 <button onClick={onClick}>{children}</button>3);4Button.propTypes = {5};6export default Button;7import React from 'react';8import { shallow } from 'enzyme';9import Button from './Button';10describe('Button', () => {11 it('should render without crashing', () => {12 shallow(<Button />);13 });14});15shallow(<Button>{''}</Button>);16import React from 'react';17import { render, fireEvent, act, waitForElement } from '@testing-library/react';18import { flushAllPromises } from 'utils/test-utils';19import { withTheme } from 'utils/test-utils';20import { Button } from 'components';21import { useAuth } from 'hooks';22import { useAuth as useAuthMock } from
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!!