How to use unsortedExports method in storybook-root

Best JavaScript code snippet using storybook-root

CsfFile.ts

Source:CsfFile.ts Github

copy

Full Screen

1/* eslint-disable no-underscore-dangle */2import fs from 'fs-extra';3import dedent from 'ts-dedent';4import * as t from '@babel/types';5import generate from '@babel/generator';6import traverse from '@babel/traverse';7import { toId, isExportStory, storyNameFromExport } from '@storybook/csf';8import { babelParse } from './babelParse';9const logger = console;10interface Meta {11 id?: string;12 title?: string;13 component?: string;14 includeStories?: string[] | RegExp;15 excludeStories?: string[] | RegExp;16}17interface Story {18 id: string;19 name: string;20 parameters: Record<string, any>;21}22function parseIncludeExclude(prop: t.Node) {23 if (t.isArrayExpression(prop)) {24 return prop.elements.map((e) => {25 if (t.isStringLiteral(e)) return e.value;26 throw new Error(`Expected string literal: ${e}`);27 });28 }29 if (t.isStringLiteral(prop)) return new RegExp(prop.value);30 if (t.isRegExpLiteral(prop)) return new RegExp(prop.pattern, prop.flags);31 throw new Error(`Unknown include/exclude: ${prop}`);32}33const findVarInitialization = (identifier: string, program: t.Program) => {34 let init: t.Expression = null;35 let declarations: t.VariableDeclarator[] = null;36 program.body.find((node: t.Node) => {37 if (t.isVariableDeclaration(node)) {38 declarations = node.declarations;39 } else if (t.isExportNamedDeclaration(node) && t.isVariableDeclaration(node.declaration)) {40 declarations = node.declaration.declarations;41 }42 return (43 declarations &&44 declarations.find((decl: t.Node) => {45 if (46 t.isVariableDeclarator(decl) &&47 t.isIdentifier(decl.id) &&48 decl.id.name === identifier49 ) {50 init = decl.init;51 return true; // stop looking52 }53 return false;54 })55 );56 });57 return init;58};59const formatLocation = (node: t.Node, fileName?: string) => {60 const { line, column } = node.loc.start;61 return `${fileName || ''} (line ${line}, col ${column})`.trim();62};63const isArgsStory = (init: t.Node, parent: t.Node, csf: CsfFile) => {64 let storyFn: t.Node = init;65 // export const Foo = Bar.bind({})66 if (t.isCallExpression(init)) {67 const { callee, arguments: bindArguments } = init;68 if (69 t.isProgram(parent) &&70 t.isMemberExpression(callee) &&71 t.isIdentifier(callee.object) &&72 t.isIdentifier(callee.property) &&73 callee.property.name === 'bind' &&74 (bindArguments.length === 0 ||75 (bindArguments.length === 1 &&76 t.isObjectExpression(bindArguments[0]) &&77 bindArguments[0].properties.length === 0))78 ) {79 const boundIdentifier = callee.object.name;80 const template = findVarInitialization(boundIdentifier, parent);81 if (template) {82 // eslint-disable-next-line no-param-reassign83 csf._templates[boundIdentifier] = template;84 storyFn = template;85 }86 }87 }88 if (t.isArrowFunctionExpression(storyFn)) {89 return storyFn.params.length > 0;90 }91 if (t.isFunctionDeclaration(storyFn)) {92 return storyFn.params.length > 0;93 }94 return false;95};96const parseExportsOrder = (init: t.Expression) => {97 if (t.isArrayExpression(init)) {98 return init.elements.map((item: t.Expression) => {99 if (t.isStringLiteral(item)) {100 return item.value;101 }102 throw new Error(`Expected string literal named export: ${item}`);103 });104 }105 throw new Error(`Expected array of string literals: ${init}`);106};107const sortExports = (exportByName: Record<string, any>, order: string[]) => {108 return order.reduce((acc, name) => {109 const namedExport = exportByName[name];110 if (namedExport) acc[name] = namedExport;111 return acc;112 }, {} as Record<string, any>);113};114export interface CsfOptions {115 defaultTitle: string;116 fileName?: string;117}118export class NoMetaError extends Error {119 constructor(ast: t.Node, fileName?: string) {120 super(dedent`121 CSF: missing default export ${formatLocation(ast, fileName)}122 More info: https://storybook.js.org/docs/react/writing-stories/introduction#default-export123 `);124 this.name = this.constructor.name;125 }126}127export class CsfFile {128 _ast: t.File;129 _defaultTitle: string;130 _fileName: string;131 _meta?: Meta;132 _stories: Record<string, Story> = {};133 _metaAnnotations: Record<string, t.Node> = {};134 _storyExports: Record<string, t.VariableDeclarator | t.FunctionDeclaration> = {};135 _storyAnnotations: Record<string, Record<string, t.Node>> = {};136 _templates: Record<string, t.Expression> = {};137 _namedExportsOrder?: string[];138 constructor(ast: t.File, { defaultTitle, fileName }: CsfOptions) {139 this._ast = ast;140 this._defaultTitle = defaultTitle;141 this._fileName = fileName;142 }143 _parseTitle(value: t.Node) {144 const node = t.isIdentifier(value)145 ? findVarInitialization(value.name, this._ast.program)146 : value;147 if (t.isStringLiteral(node)) return node.value;148 throw new Error(dedent`149 CSF: unexpected dynamic title ${formatLocation(node, this._fileName)}150 More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#string-literal-titles151 `);152 }153 _parseMeta(declaration: t.ObjectExpression, program: t.Program) {154 const meta: Meta = {};155 declaration.properties.forEach((p: t.ObjectProperty) => {156 if (t.isIdentifier(p.key)) {157 this._metaAnnotations[p.key.name] = p.value;158 if (p.key.name === 'title') {159 meta.title = this._parseTitle(p.value);160 } else if (['includeStories', 'excludeStories'].includes(p.key.name)) {161 // @ts-ignore162 meta[p.key.name] = parseIncludeExclude(p.value);163 } else if (p.key.name === 'component') {164 const { code } = generate(p.value, {});165 meta.component = code;166 } else if (p.key.name === 'id') {167 if (t.isStringLiteral(p.value)) {168 meta.id = p.value.value;169 } else {170 throw new Error(`Unexpected component id: ${p.value}`);171 }172 }173 }174 });175 this._meta = meta;176 }177 parse() {178 // eslint-disable-next-line @typescript-eslint/no-this-alias179 const self = this;180 traverse(this._ast, {181 ExportDefaultDeclaration: {182 enter({ node, parent }) {183 let metaNode: t.ObjectExpression;184 if (t.isObjectExpression(node.declaration)) {185 // export default { ... };186 metaNode = node.declaration;187 } else if (188 // export default { ... } as Meta<...>189 t.isTSAsExpression(node.declaration) &&190 t.isObjectExpression(node.declaration.expression)191 ) {192 metaNode = node.declaration.expression;193 } else if (t.isIdentifier(node.declaration) && t.isProgram(parent)) {194 const init = findVarInitialization(node.declaration.name, parent);195 if (t.isObjectExpression(init)) {196 metaNode = init;197 }198 }199 if (!self._meta && metaNode && t.isProgram(parent)) {200 self._parseMeta(metaNode, parent);201 }202 },203 },204 ExportNamedDeclaration: {205 enter({ node, parent }) {206 let declarations;207 if (t.isVariableDeclaration(node.declaration)) {208 declarations = node.declaration.declarations.filter((d) => t.isVariableDeclarator(d));209 } else if (t.isFunctionDeclaration(node.declaration)) {210 declarations = [node.declaration];211 }212 if (declarations) {213 // export const X = ...;214 declarations.forEach((decl: t.VariableDeclarator | t.FunctionDeclaration) => {215 if (t.isIdentifier(decl.id)) {216 const { name: exportName } = decl.id;217 if (exportName === '__namedExportsOrder' && t.isVariableDeclarator(decl)) {218 self._namedExportsOrder = parseExportsOrder(decl.init);219 return;220 }221 self._storyExports[exportName] = decl;222 let name = storyNameFromExport(exportName);223 if (self._storyAnnotations[exportName]) {224 logger.warn(225 `Unexpected annotations for "${exportName}" before story declaration`226 );227 } else {228 self._storyAnnotations[exportName] = {};229 }230 let parameters;231 if (t.isVariableDeclarator(decl) && t.isObjectExpression(decl.init)) {232 let __isArgsStory = true; // assume default render is an args story233 // CSF3 object export234 decl.init.properties.forEach((p: t.ObjectProperty) => {235 if (t.isIdentifier(p.key)) {236 if (p.key.name === 'render') {237 __isArgsStory = isArgsStory(p.value as t.Expression, parent, self);238 } else if (p.key.name === 'name' && t.isStringLiteral(p.value)) {239 name = p.value.value;240 }241 self._storyAnnotations[exportName][p.key.name] = p.value;242 }243 });244 parameters = { __isArgsStory };245 } else {246 const fn = t.isVariableDeclarator(decl) ? decl.init : decl;247 parameters = {248 // __id: toId(self._meta.title, name),249 // FIXME: Template.bind({});250 __isArgsStory: isArgsStory(fn, parent, self),251 };252 }253 self._stories[exportName] = {254 id: 'FIXME',255 name,256 parameters,257 };258 }259 });260 } else if (node.specifiers.length > 0) {261 // export { X as Y }262 node.specifiers.forEach((specifier) => {263 if (t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported)) {264 const { name: exportName } = specifier.exported;265 self._storyAnnotations[exportName] = {};266 self._stories[exportName] = { id: 'FIXME', name: exportName, parameters: {} };267 }268 });269 }270 },271 },272 ExpressionStatement: {273 enter({ node, parent }) {274 const { expression } = node;275 // B.storyName = 'some string';276 if (277 t.isProgram(parent) &&278 t.isAssignmentExpression(expression) &&279 t.isMemberExpression(expression.left) &&280 t.isIdentifier(expression.left.object) &&281 t.isIdentifier(expression.left.property)282 ) {283 const exportName = expression.left.object.name;284 const annotationKey = expression.left.property.name;285 const annotationValue = expression.right;286 // v1-style annotation287 // A.story = { parameters: ..., decorators: ... }288 if (self._storyAnnotations[exportName]) {289 if (annotationKey === 'story' && t.isObjectExpression(annotationValue)) {290 annotationValue.properties.forEach((prop: t.ObjectProperty) => {291 if (t.isIdentifier(prop.key)) {292 self._storyAnnotations[exportName][prop.key.name] = prop.value;293 }294 });295 } else {296 self._storyAnnotations[exportName][annotationKey] = annotationValue;297 }298 }299 if (annotationKey === 'storyName' && t.isStringLiteral(annotationValue)) {300 const storyName = annotationValue.value;301 const story = self._stories[exportName];302 if (!story) return;303 story.name = storyName;304 }305 }306 },307 },308 CallExpression: {309 enter({ node }) {310 const { callee } = node;311 if (t.isIdentifier(callee) && callee.name === 'storiesOf') {312 throw new Error(dedent`313 CSF: unexpected storiesOf call ${formatLocation(node, self._fileName)}314 More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-v7315 `);316 }317 },318 },319 });320 if (!self._meta) {321 throw new NoMetaError(self._ast, self._fileName);322 }323 if (!self._meta.title && !self._meta.component) {324 throw new Error(dedent`325 CSF: missing title/component ${formatLocation(self._ast, self._fileName)}326 More info: https://storybook.js.org/docs/react/writing-stories/introduction#default-export327 `);328 }329 // default export can come at any point in the file, so we do this post processing last330 const entries = Object.entries(self._stories);331 self._meta.title = self._meta.title || this._defaultTitle;332 self._stories = entries.reduce((acc, [key, story]) => {333 if (isExportStory(key, self._meta)) {334 const id = toId(self._meta.id || self._meta.title, storyNameFromExport(key));335 const parameters: Record<string, any> = { ...story.parameters, __id: id };336 if (entries.length === 1 && key === '__page') {337 parameters.docsOnly = true;338 }339 acc[key] = { ...story, id, parameters };340 }341 return acc;342 }, {} as Record<string, Story>);343 Object.keys(self._storyExports).forEach((key) => {344 if (!isExportStory(key, self._meta)) {345 delete self._storyExports[key];346 delete self._storyAnnotations[key];347 }348 });349 if (self._namedExportsOrder) {350 const unsortedExports = Object.keys(self._storyExports);351 self._storyExports = sortExports(self._storyExports, self._namedExportsOrder);352 self._stories = sortExports(self._stories, self._namedExportsOrder);353 const sortedExports = Object.keys(self._storyExports);354 if (unsortedExports.length !== sortedExports.length) {355 throw new Error(356 `Missing exports after sort: ${unsortedExports.filter(357 (key) => !sortedExports.includes(key)358 )}`359 );360 }361 }362 return self;363 }364 public get meta() {365 return this._meta;366 }367 public get stories() {368 return Object.values(this._stories);369 }370}371export const loadCsf = (code: string, options: CsfOptions) => {372 const ast = babelParse(code);373 return new CsfFile(ast, options);374};375export const formatCsf = (csf: CsfFile) => {376 const { code } = generate(csf._ast, {});377 return code;378};379export const readCsf = async (fileName: string, options: CsfOptions) => {380 const code = (await fs.readFile(fileName, 'utf-8')).toString();381 return loadCsf(code, { ...options, fileName });382};383export const writeCsf = async (csf: CsfFile, fileName?: string) => {384 const fname = fileName || csf._fileName;385 if (!fname) throw new Error('Please specify a fileName for writeCsf');386 await fs.writeFile(fileName, await formatCsf(csf));...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { unsortedExports } from 'storybook-root';2console.log(unsortedExports);3import { sortedExports } from 'storybook-root';4console.log(sortedExports);5import { getStories } from 'storybook-root';6console.log(getStories());7import { getStory } from 'storybook-root';8console.log(getStory('Button'));9import { getStoryNames } from 'storybook-root';10console.log(getStoryNames());11import { getStoryName } from 'storybook-root';12console.log(getStoryName('Button'));13import { getStoryExports } from 'storybook-root';14console.log(getStoryExports('Button'));15import { getStoryExport } from 'storybook-root';16console.log(getStoryExport('Button', 'default'));17import { getStoryExportNames } from 'storybook-root';18console.log(getStoryExportNames('Button'));19import { getStoryExportName } from 'storybook-root';20console.log(getStoryExportName('Button', 'default'));21import { getStoryExportKind } from 'storybook-root';22console.log(getStoryExportKind('Button', 'default'));23import { getStoryExportStory } from 'storybook-root';24console.log(getStoryExportStory('Button', 'default'));25import { getStoryExportProps } from 'storybook-root';26console.log(getStoryExportProps('Button', 'default'));

Full Screen

Using AI Code Generation

copy

Full Screen

1import { unsortedExports } from 'storybook-root';2import { sortedExports } from 'storybook-root';3import { unsortedExports } from 'storybook-root';4import { sortedExports } from 'storybook-root';5import { unsortedExports } from 'storybook-root';6import { sortedExports } from 'storybook-root';7import { unsortedExports } from 'storybook-root';8import { sortedExports } from 'storybook-root';9import { unsortedExports } from 'storybook-root';10import { sortedExports } from 'storybook-root';11import { unsortedExports } from 'storybook-root';12import { sortedExports } from 'storybook-root';13import { unsortedExports } from 'storybook-root';14import { sortedExports } from 'storybook-root';15import { unsortedExports } from 'storybook-root';16import { sortedExports } from 'storybook-root';17import { unsortedExports } from 'storybook-root';18import { sortedExports } from 'storybook-root';19import { unsortedExports } from 'storybook-root';20import { sortedExports } from 'storybook-root';21import { unsortedExports } from 'storybook-root';22import { sortedExports } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unsortedExports } = require('storybook-root');2const { sortedExports } = require('storybook-root');3const { unsortedExports } = require('storybook-root');4const { sortedExports } = require('storybook-root');5const { unsortedExports } = require('storybook-root');6const { sortedExports } = require('storybook-root');7const { unsortedExports } = require('storybook-root');8const { sortedExports } = require('storybook-root');9const { unsortedExports } = require('storybook-root');10const { sortedExports } = require('storybook-root');11const { unsortedExports } = require('storybook-root');12const { sortedExports } = require('storybook-root');13const { unsortedExports } = require('storybook-root');14const { sortedExports } = require('storybook-root');15const { unsortedExports } = require('storybook-root');16const { sortedExports } = require('storybook-root');17const { unsortedExports } = require('storybook-root');18const { sortedExports } = require('storybook-root');19const { unsortedExports } = require('storybook-root');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { unsortedExports } from '@storybook/react/demo';2import { sortedExports } from '@storybook/react/demo';3import { sortedExports } from '@storybook/react/demo';4import { unsortedExports } from '@storybook/react/demo';5import { sortedExports } from '@storybook/react/demo';6import { sortedExports } from '@storybook/react/demo';7import { unsortedExports } from '@storybook/react/demo';8import { sortedExports } from '@storybook/react/demo';9import { sortedExports } from '@storybook/react/demo';10import { unsortedExports } from '@storybook/react/demo';11import { sortedExports } from '@storybook/react/demo';12import { sortedExports } from '@storybook/react/demo';13import { unsortedExports } from '@storybook/react/demo';14import { sortedExports } from '@storybook/react/demo';15import { sortedExports } from '@storybook/react/demo';16import { unsortedExports } from '@storybook/react/demo';17import { sortedExports } from '@storybook/react/demo';18import { sortedExports } from '@storybook/react/demo';19import { unsortedExports } from '@storybook/react/demo';20import { sortedExports } from '@storybook/react/demo';

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unsortedExports } = require('storybook-root');2const { storiesOf } = require('@storybook/react');3const stories = unsortedExports();4storiesOf('test', module).add('test', () => <div>test</div>);5const { unsortedExports } = require('storybook-root');6const { storiesOf } = require('@storybook/react');7const stories = unsortedExports();8storiesOf('test2', module).add('test2', () => <div>test2</div>);9const { unsortedExports } = require('storybook-root');10const { configure } = require('@storybook/react');11const req = unsortedExports();12function loadStories() {13 req.keys().forEach(filename => req(filename));14}15configure(loadStories, module);16const { unsortedExports } = require('storybook-root');17const { configure } = require('@storybook/react');18const req = unsortedExports();19function loadStories() {20 req.keys().forEach(filename => req(filename));21}22configure(loadStories, module);23require('./test2.js');24const { unsortedExports } = require('storybook-root');25const { configure } = require('@storybook/react');26const req = unsortedExports();27function loadStories() {28 req.keys().forEach(filename => req(filename));29}30configure(loadStories, module);31require('./test2.js');32const { unsortedExports } = require('storybook-root');33const { configure } = require('@storybook/react');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unsortedExports } = require('storybook-root-exports');2const path = require('path');3module.exports = {4 stories: unsortedExports(path.resolve(__dirname, '../src/stories')),5};6export * from './Button';7export * from './Header';8export * from './Footer';9import React from 'react';10import { storiesOf } from '@storybook/react';11import Button from '../components/Button';12storiesOf('Button', module).add('with text', () => <Button>Hello Button</Button>);13import React from 'react';14import { storiesOf } from '@storybook/react';15import Header from '../components/Header';16storiesOf('Header', module).add('with text', () => <Header>Hello Header</Header>);17import React from 'react';18import { storiesOf } from '@storybook/react';19import Footer from '../components/Footer';20storiesOf('Footer', module).add('with text', () => <Footer>Hello Footer</Footer>);21import React from 'react';22const Button = ({ children }) => <button>{children}</button>;23export default Button;24import React from 'react';25const Header = ({ children }) => <h1>{children}</h1>;26export default Header;27import React from 'react';28const Footer = ({ children }) => <h2>{children}</h2>;29export default Footer;30import { configure } from '@storybook/react';31const req = require.context('../src/stories', true, /.js$/);32function loadStories() {33 req.keys().forEach(filename => req(filename));34}35configure(loadStories, module);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unsortedExports } = require('@storybook/core-common');2module.exports = {3 ...unsortedExports('./src/**/*.stories.(js|mdx)'),4};5const path = require('path');6module.exports = async ({ config, mode }) => {7 config.module.rules.push({8 test: /\.(ts|tsx)$/,9 {10 loader: require.resolve('ts-loader'),11 },12 });13 config.resolve.extensions.push('.ts', '.tsx');14 return config;15};16module.exports = {17 stories: ['../src/**/*.stories.(js|mdx)'],18};19import { addDecorator, addParameters } from '@storybook/react';20import { withA11y } from '@storybook/addon-a11y';21import { withKnobs } from '@storybook/addon-knobs';22import { withInfo } from '@storybook/addon-info';23import { withDesign } from 'storybook-addon-designs';24import { withPerformance } from 'storybook-addon-performance';25import { withTests } from '@storybook/addon-jest';26import { withConsole } from '@storybook/addon-console';27import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';28import { withSmartKnobs } from 'storybook-addon-smart-knobs';29import { withContexts } from '@storybook/addon-contexts/react';30import { withThemesProvider } from 'storybook-addon-styled-component-theme';31import { withTests as withTests2 } from '@storybook/addon-jest';32import { withTests as withTests3 } from '@storybook/addon

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configure } from '@storybook/react';2import { unsortedExports } from 'storybook-root';3configure(unsortedExports, module);4import { unsortedExports } from 'storybook-root';5export default unsortedExports;6import React from 'react';7import { storiesOf } from '@storybook/react';8import MyComponent from '../src/MyComponent';9storiesOf('MyComponent', module).add('with text', () => (10));11import React from 'react';12import { storiesOf } from '@storybook/react';13import MyOtherComponent from '../src/MyOtherComponent';14storiesOf('MyOtherComponent', module).add('with text', () => (15));16import React from 'react';17import { storiesOf } from '@storybook/react';18import MyThirdComponent from '../src/MyThirdComponent';19storiesOf('MyThirdComponent', module).add('with text', () => (20));21import React from 'react';22import { storiesOf } from '@storybook/react';23import MyFourthComponent from '../src/MyFourthComponent';24storiesOf('MyFourthComponent', module).add('with text', () => (25));26import React from 'react';27import { storiesOf } from '@storybook/react';28import MyFifthComponent from '../src/MyFifthComponent';29storiesOf('MyFifthComponent', module).add('with text', () => (30));31import React from 'react';32import { storiesOf } from

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