Best JavaScript code snippet using storybook-root
StoryIndexGenerator.ts
Source:StoryIndexGenerator.ts
1import path from 'path';2import fs from 'fs-extra';3import glob from 'globby';4import slash from 'slash';5import type { Path, StoryIndex, V2CompatIndexEntry, StoryId } from '@storybook/store';6import { autoTitleFromSpecifier, sortStoriesV7 } from '@storybook/store';7import type { NormalizedStoriesSpecifier } from '@storybook/core-common';8import { normalizeStoryPath } from '@storybook/core-common';9import { logger } from '@storybook/node-logger';10import { readCsfOrMdx, getStorySortParameter } from '@storybook/csf-tools';11import type { ComponentTitle } from '@storybook/csf';12type SpecifierStoriesCache = Record<Path, StoryIndex['stories'] | false>;13export class StoryIndexGenerator {14 // An internal cache mapping specifiers to a set of path=><set of stories>15 // Later, we'll combine each of these subsets together to form the full index16 private storyIndexEntries: Map<NormalizedStoriesSpecifier, SpecifierStoriesCache>;17 // Cache the last value of `getStoryIndex`. We invalidate (by unsetting) when:18 // - any file changes, including deletions19 // - the preview changes [not yet implemented]20 private lastIndex?: StoryIndex;21 constructor(22 public readonly specifiers: NormalizedStoriesSpecifier[],23 public readonly options: {24 workingDir: Path;25 configDir: Path;26 storiesV2Compatibility: boolean;27 storyStoreV7: boolean;28 }29 ) {30 this.storyIndexEntries = new Map();31 }32 async initialize() {33 // Find all matching paths for each specifier34 await Promise.all(35 this.specifiers.map(async (specifier) => {36 const pathToSubIndex = {} as SpecifierStoriesCache;37 const fullGlob = slash(38 path.join(this.options.workingDir, specifier.directory, specifier.files)39 );40 const files = await glob(fullGlob);41 files.sort().forEach((absolutePath: Path) => {42 const ext = path.extname(absolutePath);43 const relativePath = path.relative(this.options.workingDir, absolutePath);44 if (!['.js', '.jsx', '.ts', '.tsx', '.mdx'].includes(ext)) {45 logger.info(`Skipping ${ext} file ${relativePath}`);46 return;47 }48 pathToSubIndex[absolutePath] = false;49 });50 this.storyIndexEntries.set(specifier, pathToSubIndex);51 })52 );53 // Extract stories for each file54 await this.ensureExtracted();55 }56 async ensureExtracted(): Promise<StoryIndex['stories'][]> {57 return (58 await Promise.all(59 this.specifiers.map(async (specifier) => {60 const entry = this.storyIndexEntries.get(specifier);61 return Promise.all(62 Object.keys(entry).map(63 async (absolutePath) =>64 entry[absolutePath] || this.extractStories(specifier, absolutePath)65 )66 );67 })68 )69 ).flat();70 }71 async extractStories(specifier: NormalizedStoriesSpecifier, absolutePath: Path) {72 const relativePath = path.relative(this.options.workingDir, absolutePath);73 const fileStories = {} as StoryIndex['stories'];74 const entry = this.storyIndexEntries.get(specifier);75 try {76 const importPath = slash(normalizeStoryPath(relativePath));77 const defaultTitle = autoTitleFromSpecifier(importPath, specifier);78 const csf = (await readCsfOrMdx(absolutePath, { defaultTitle })).parse();79 csf.stories.forEach(({ id, name }) => {80 fileStories[id] = {81 id,82 title: csf.meta.title,83 name,84 importPath,85 };86 });87 } catch (err) {88 if (err.name === 'NoMetaError') {89 logger.info(`ð¡ Skipping ${relativePath}: ${err}`);90 } else {91 logger.warn(`ð¨ Extraction error on ${relativePath}: ${err}`);92 throw err;93 }94 }95 entry[absolutePath] = fileStories;96 return fileStories;97 }98 async sortStories(storiesList: StoryIndex['stories'][]) {99 const stories: StoryIndex['stories'] = {};100 storiesList.forEach((subStories) => {101 Object.assign(stories, subStories);102 });103 const sortableStories = Object.values(stories);104 // Skip sorting if we're in v6 mode because we don't have105 // all the info we need here106 if (this.options.storyStoreV7) {107 const storySortParameter = await this.getStorySortParameter();108 const fileNameOrder = this.storyFileNames();109 sortStoriesV7(sortableStories, storySortParameter, fileNameOrder);110 }111 return sortableStories.reduce((acc, item) => {112 acc[item.id] = item;113 return acc;114 }, {} as StoryIndex['stories']);115 }116 async getIndex() {117 if (this.lastIndex) return this.lastIndex;118 // Extract any entries that are currently missing119 // Pull out each file's stories into a list of stories, to be composed and sorted120 const storiesList = await this.ensureExtracted();121 const sorted = await this.sortStories(storiesList);122 let compat = sorted;123 if (this.options.storiesV2Compatibility) {124 const titleToStoryCount = Object.values(sorted).reduce((acc, story) => {125 acc[story.title] = (acc[story.title] || 0) + 1;126 return acc;127 }, {} as Record<ComponentTitle, number>);128 compat = Object.entries(sorted).reduce((acc, entry) => {129 const [id, story] = entry;130 acc[id] = {131 ...story,132 id,133 kind: story.title,134 story: story.name,135 parameters: {136 __id: story.id,137 docsOnly: titleToStoryCount[story.title] === 1 && story.name === 'Page',138 fileName: story.importPath,139 },140 };141 return acc;142 }, {} as Record<StoryId, V2CompatIndexEntry>);143 }144 this.lastIndex = {145 v: 3,146 stories: compat,147 };148 return this.lastIndex;149 }150 invalidate(specifier: NormalizedStoriesSpecifier, importPath: Path, removed: boolean) {151 const absolutePath = slash(path.resolve(this.options.workingDir, importPath));152 const pathToEntries = this.storyIndexEntries.get(specifier);153 if (removed) {154 delete pathToEntries[absolutePath];155 } else {156 pathToEntries[absolutePath] = false;157 }158 this.lastIndex = null;159 }160 async getStorySortParameter() {161 const previewFile = ['js', 'jsx', 'ts', 'tsx']162 .map((ext) => path.join(this.options.configDir, `preview.${ext}`))163 .find((fname) => fs.existsSync(fname));164 let storySortParameter;165 if (previewFile) {166 const previewCode = (await fs.readFile(previewFile, 'utf-8')).toString();167 storySortParameter = await getStorySortParameter(previewCode);168 }169 return storySortParameter;170 }171 // Get the story file names in "imported order"172 storyFileNames() {173 return Array.from(this.storyIndexEntries.values()).flatMap((r) => Object.keys(r));174 }...
Using AI Code Generation
1import {titleToStoryCount} from 'storybook-root';2import {titleToStoryCount} from 'storybook-subfolder';3import {titleToStoryCount} from 'storybook-subfolder-2';4import {titleToStoryCount} from 'storybook-subfolder-3';5import {titleToStoryCount} from 'storybook-subfolder-4';6import {titleToStoryCount} from 'storybook-subfolder-5';7import {titleToStoryCount} from 'storybook-subfolder-6';8import {titleToStoryCount} from 'storybook-subfolder-7';9import {titleToStoryCount} from 'storybook-subfolder-8';10import {titleToStoryCount} from 'storybook-subfolder-9';11import {titleToStoryCount} from 'storybook-subfolder-10';12import {titleToStoryCount} from 'storybook-subfolder-11';13import {titleToStoryCount} from 'storybook-subfolder-12';14import {titleToStoryCount} from 'storybook-subfolder
Using AI Code Generation
1const StorybookRoot = require('storybook-root');2const storybookRoot = new StorybookRoot();3storybookRoot.titleToStoryCount('test');4const StorybookRoot = require('storybook-root');5const storybookRoot = new StorybookRoot();6storybookRoot.titleToStoryCount('test');7const StorybookRoot = require('storybook-root');8const storybookRoot = new StorybookRoot();9storybookRoot.titleToStoryCount('test');10const StorybookRoot = require('storybook-root');11const storybookRoot = new StorybookRoot();12storybookRoot.titleToStoryCount('test');13const StorybookRoot = require('storybook-root');14const storybookRoot = new StorybookRoot();15storybookRoot.titleToStoryCount('test');16const StorybookRoot = require('storybook-root');17const storybookRoot = new StorybookRoot();18storybookRoot.titleToStoryCount('test');19const StorybookRoot = require('storybook-root');20const storybookRoot = new StorybookRoot();21storybookRoot.titleToStoryCount('test');22const StorybookRoot = require('storybook-root');23const storybookRoot = new StorybookRoot();24storybookRoot.titleToStoryCount('test');25const StorybookRoot = require('storybook-root');26const storybookRoot = new StorybookRoot();27storybookRoot.titleToStoryCount('test');28const StorybookRoot = require('storybook-root');29const storybookRoot = new StorybookRoot();30storybookRoot.titleToStoryCount('test');31const StorybookRoot = require('storybook-root
Using AI Code Generation
1import { titleToStoryCount } from './storybook-root';2const storyCount = titleToStoryCount('Button');3console.log(storyCount);4import { storiesOf } from '@storybook/react';5import { Button } from './button';6storiesOf('Button', module).add('with text', () => <Button />);7export const titleToStoryCount = title => {8 const storybook = require('./storybook-root');9 return storybook.storiesOf(title, module).getStorybook().length;10};11jest.mock('./storybook-root', () => ({12 storiesOf: jest.fn(),13}));14jest.mock('./storybook-root', () => ({15 storiesOf: jest.fn().mockReturnValue({16 getStorybook: jest.fn().mockReturnValue([]),17 }),18}));19I want to test a component that has a button in it. I want to test the button click event. I am using react testing library. I tried to use fireEvent.click() but it is not working. I am getting this error: "Unable to find an element with the role "button". Please use the "role" option to find a button element."20import { render, fireEvent } from "@testing-library/react";21import Button from "./Button";22test("test button click", () => {23 const handleClick = jest.fn();24 const { getByRole } = render(<Button onClick={handleClick} />);25 fireEvent.click(getByRole("button"));26 expect(handleClick).toHaveBeenCalledTimes(1);27});28I have a button that I want to test. I am using Jest and Enzyme. I want to test the click event of the button. I tried to use simulate('click') but it is not working. I am getting this error: "Method “simulate” is only meant to be
Using AI Code Generation
1const storyBook = require('storybook-root');2const storyBookRoot = new storyBook();3storyBookRoot.titleToStoryCount('Button');4module.exports = function storybookRoot() {5 this.titleToStoryCount = function (title) {6 }7}8import storyBook from 'storybook-root';9const storyBookRoot = new storyBook();10storyBookRoot.titleToStoryCount('Button');11export default function storybookRoot() {12 this.titleToStoryCount = function (title) {13 }14}15module.exports = function (config) {16 config.set({17 });18};19Chrome 83.0.4103 (Mac OS X 10.15.5) storybookRoot titleToStoryCount should return the story count of a given title FAILED20 at storybookRoot.storybookRoot.titleToStoryCount should return the story count of a given title (test.js:12:31)21Chrome 83.0.4103 (Mac OS X 10.15.5): Executed 1 of 1 (1 FAILED) (0.007 secs / 0.001 secs)
Using AI Code Generation
1import { titleToStoryCount } from "storybook-root"2export const titleToStoryCount = ({ title }) => {3 const stories = getStories()4}5export const getStories = () => {6 return { "Hello World": ["story-1", "story-2", "story-3"] }7}8export const getStory = ({ storyId }) => {9 return { id: storyId, title: "Hello World", name: "Story 1" }10}11export const getStoryUrl = ({ storyId }) => {12}13export const getStorybook = () => {14 {15 { name: "Story 1", id: "story-1" },16 { name: "Story 2", id: "story-2" },17 { name: "Story 3", id: "story-3" }18 }19}20export const getStorybookUrl = () => {21}22export const getStorybookStoriesUrl = () => {23}24export const getStorybookKindsUrl = () => {25}26export const getStorybookStories = () => {27 return {28 { name: "Story 1", id: "story-1" },29 { name: "Story 2", id: "story-2" },30 { name: "Story 3", id: "story-3" }31 }32}
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!!