Best JavaScript code snippet using storybook-root
StoryStore.ts
Source:StoryStore.ts
1import memoize from 'memoizerific';2import {3 Parameters,4 StoryId,5 StoryContextForLoaders,6 AnyFramework,7 ProjectAnnotations,8 ComponentTitle,9 StoryContextForEnhancers,10 StoryContext,11} from '@storybook/csf';12import mapValues from 'lodash/mapValues';13import pick from 'lodash/pick';14import global from 'global';15import { SynchronousPromise } from 'synchronous-promise';16import { StoryIndexStore } from './StoryIndexStore';17import { ArgsStore } from './ArgsStore';18import { GlobalsStore } from './GlobalsStore';19import { processCSFFile } from './processCSFFile';20import { prepareStory } from './prepareStory';21import {22 CSFFile,23 ModuleImportFn,24 Story,25 NormalizedProjectAnnotations,26 Path,27 ExtractOptions,28 BoundStory,29 StoryIndex,30 StoryIndexEntry,31 V2CompatIndexEntry,32} from './types';33import { HooksContext } from './hooks';34import { normalizeInputTypes } from './normalizeInputTypes';35import { inferArgTypes } from './inferArgTypes';36import { inferControls } from './inferControls';37// TODO -- what are reasonable values for these?38const CSF_CACHE_SIZE = 1000;39const STORY_CACHE_SIZE = 10000;40function normalizeProjectAnnotations<TFramework extends AnyFramework>({41 argTypes,42 globalTypes,43 argTypesEnhancers,44 ...annotations45}: ProjectAnnotations<TFramework>): NormalizedProjectAnnotations<TFramework> {46 return {47 ...(argTypes && { argTypes: normalizeInputTypes(argTypes) }),48 ...(globalTypes && { globalTypes: normalizeInputTypes(globalTypes) }),49 argTypesEnhancers: [50 ...(argTypesEnhancers || []),51 inferArgTypes,52 // inferControls technically should only run if the user is using the controls addon,53 // and so should be added by a preset there. However, as it seems some code relies on controls54 // annotations (in particular the angular implementation's `cleanArgsDecorator`), for backwards55 // compatibility reasons, we will leave this in the store until 7.056 inferControls,57 ],58 ...annotations,59 };60}61export class StoryStore<TFramework extends AnyFramework> {62 storyIndex: StoryIndexStore;63 importFn: ModuleImportFn;64 projectAnnotations: NormalizedProjectAnnotations<TFramework>;65 globals: GlobalsStore;66 args: ArgsStore;67 hooks: Record<StoryId, HooksContext<TFramework>>;68 cachedCSFFiles?: Record<Path, CSFFile<TFramework>>;69 processCSFFileWithCache: typeof processCSFFile;70 prepareStoryWithCache: typeof prepareStory;71 initializationPromise: Promise<void>;72 resolveInitializationPromise: () => void;73 constructor() {74 this.globals = new GlobalsStore();75 this.args = new ArgsStore();76 this.hooks = {};77 // We use a cache for these two functions for two reasons:78 // 1. For performance79 // 2. To ensure that when the same story is prepared with the same inputs you get the same output80 this.processCSFFileWithCache = memoize(CSF_CACHE_SIZE)(processCSFFile) as typeof processCSFFile;81 this.prepareStoryWithCache = memoize(STORY_CACHE_SIZE)(prepareStory) as typeof prepareStory;82 // We cannot call `loadStory()` until we've been initialized properly. But we can wait for it.83 this.initializationPromise = new SynchronousPromise((resolve) => {84 this.resolveInitializationPromise = resolve;85 });86 }87 setProjectAnnotations(projectAnnotations: ProjectAnnotations<TFramework>) {88 // By changing `this.projectAnnotations, we implicitly invalidate the `prepareStoryWithCache`89 this.projectAnnotations = normalizeProjectAnnotations(projectAnnotations);90 const { globals, globalTypes } = projectAnnotations;91 this.globals.set({ globals, globalTypes });92 }93 initialize({94 storyIndex,95 importFn,96 cache = false,97 }: {98 storyIndex?: StoryIndex;99 importFn: ModuleImportFn;100 cache?: boolean;101 }): PromiseLike<void> {102 this.storyIndex = new StoryIndexStore(storyIndex);103 this.importFn = importFn;104 // We don't need the cache to be loaded to call `loadStory`, we just need the index ready105 this.resolveInitializationPromise();106 return cache ? this.cacheAllCSFFiles() : SynchronousPromise.resolve();107 }108 // This means that one of the CSF files has changed.109 // If the `importFn` has changed, we will invalidate both caches.110 // If the `storyIndex` data has changed, we may or may not invalidate the caches, depending111 // on whether we've loaded the relevant files yet.112 async onStoriesChanged({113 importFn,114 storyIndex,115 }: {116 importFn?: ModuleImportFn;117 storyIndex?: StoryIndex;118 }) {119 if (importFn) this.importFn = importFn;120 if (storyIndex) this.storyIndex.stories = storyIndex.stories;121 if (this.cachedCSFFiles) await this.cacheAllCSFFiles();122 }123 // To load a single CSF file to service a story we need to look up the importPath in the index124 loadCSFFileByStoryId(storyId: StoryId): PromiseLike<CSFFile<TFramework>> {125 const { importPath, title } = this.storyIndex.storyIdToEntry(storyId);126 return this.importFn(importPath).then((moduleExports) =>127 // We pass the title in here as it may have been generated by autoTitle on the server.128 this.processCSFFileWithCache(moduleExports, importPath, title)129 );130 }131 loadAllCSFFiles(): PromiseLike<StoryStore<TFramework>['cachedCSFFiles']> {132 const importPaths: Record<Path, StoryId> = {};133 Object.entries(this.storyIndex.stories).forEach(([storyId, { importPath }]) => {134 importPaths[importPath] = storyId;135 });136 const csfFilePromiseList = Object.entries(importPaths).map(([importPath, storyId]) =>137 this.loadCSFFileByStoryId(storyId).then((csfFile) => ({138 importPath,139 csfFile,140 }))141 );142 return SynchronousPromise.all(csfFilePromiseList).then((list) =>143 list.reduce((acc, { importPath, csfFile }) => {144 acc[importPath] = csfFile;145 return acc;146 }, {} as Record<Path, CSFFile<TFramework>>)147 );148 }149 cacheAllCSFFiles(): PromiseLike<void> {150 return this.loadAllCSFFiles().then((csfFiles) => {151 this.cachedCSFFiles = csfFiles;152 });153 }154 // Load the CSF file for a story and prepare the story from it and the project annotations.155 async loadStory({ storyId }: { storyId: StoryId }): Promise<Story<TFramework>> {156 await this.initializationPromise;157 const csfFile = await this.loadCSFFileByStoryId(storyId);158 return this.storyFromCSFFile({ storyId, csfFile });159 }160 // This function is synchronous for convenience -- often times if you have a CSF file already161 // it is easier not to have to await `loadStory`.162 storyFromCSFFile({163 storyId,164 csfFile,165 }: {166 storyId: StoryId;167 csfFile: CSFFile<TFramework>;168 }): Story<TFramework> {169 const storyAnnotations = csfFile.stories[storyId];170 if (!storyAnnotations) {171 throw new Error(`Didn't find '${storyId}' in CSF file, this is unexpected`);172 }173 const componentAnnotations = csfFile.meta;174 const story = this.prepareStoryWithCache(175 storyAnnotations,176 componentAnnotations,177 this.projectAnnotations178 );179 this.args.setInitial(story);180 this.hooks[story.id] = this.hooks[story.id] || new HooksContext();181 return story;182 }183 // If we have a CSF file we can get all the stories from it synchronously184 componentStoriesFromCSFFile({ csfFile }: { csfFile: CSFFile<TFramework> }): Story<TFramework>[] {185 return Object.keys(csfFile.stories).map((storyId: StoryId) =>186 this.storyFromCSFFile({ storyId, csfFile })187 );188 }189 // A prepared story does not include args, globals or hooks. These are stored in the story store190 // and updated separtely to the (immutable) story.191 getStoryContext(story: Story<TFramework>): Omit<StoryContextForLoaders<TFramework>, 'viewMode'> {192 return {193 ...story,194 args: this.args.get(story.id),195 globals: this.globals.get(),196 hooks: this.hooks[story.id] as unknown,197 };198 }199 cleanupStory(story: Story<TFramework>): void {200 this.hooks[story.id].clean();201 }202 extract(203 options: ExtractOptions = { includeDocsOnly: false }204 ): Record<StoryId, StoryContextForEnhancers<TFramework>> {205 if (!this.cachedCSFFiles) {206 throw new Error('Cannot call extract() unless you call cacheAllCSFFiles() first.');207 }208 return Object.entries(this.storyIndex.stories).reduce((acc, [storyId, { importPath }]) => {209 const csfFile = this.cachedCSFFiles[importPath];210 const story = this.storyFromCSFFile({ storyId, csfFile });211 if (!options.includeDocsOnly && story.parameters.docsOnly) {212 return acc;213 }214 acc[storyId] = Object.entries(story).reduce(215 (storyAcc, [key, value]) => {216 if (typeof value === 'function') {217 return storyAcc;218 }219 if (Array.isArray(value)) {220 return Object.assign(storyAcc, { [key]: value.slice().sort() });221 }222 return Object.assign(storyAcc, { [key]: value });223 },224 { args: story.initialArgs }225 );226 return acc;227 }, {} as Record<string, any>);228 }229 getSetStoriesPayload() {230 const stories = this.extract({ includeDocsOnly: true });231 const kindParameters: Parameters = Object.values(stories).reduce(232 (acc: Parameters, { title }: { title: ComponentTitle }) => {233 acc[title] = {};234 return acc;235 },236 {} as Parameters237 );238 return {239 v: 2,240 globals: this.globals.get(),241 globalParameters: {},242 kindParameters,243 stories,244 };245 }246 getStoriesJsonData = () => {247 const value = this.getSetStoriesPayload();248 const allowedParameters = ['fileName', 'docsOnly', 'framework', '__id', '__isArgsStory'];249 const stories: Record<StoryId, StoryIndexEntry | V2CompatIndexEntry> = mapValues(250 value.stories,251 (story) => ({252 ...pick(story, ['id', 'name', 'title']),253 importPath: this.storyIndex.stories[story.id].importPath,254 ...(!global.FEATURES?.breakingChangesV7 && {255 kind: story.title,256 story: story.name,257 parameters: {258 ...pick(story.parameters, allowedParameters),259 fileName: this.storyIndex.stories[story.id].importPath,260 },261 }),262 })263 );264 return {265 v: 3,266 stories,267 };268 };269 raw(): BoundStory<TFramework>[] {270 return Object.values(this.extract()).map(({ id }: { id: StoryId }) => this.fromId(id));271 }272 fromId(storyId: StoryId): BoundStory<TFramework> {273 if (!this.cachedCSFFiles) {274 throw new Error('Cannot call fromId/raw() unless you call cacheAllCSFFiles() first.');275 }276 let importPath;277 try {278 ({ importPath } = this.storyIndex.storyIdToEntry(storyId));279 } catch (err) {280 return null;281 }282 const csfFile = this.cachedCSFFiles[importPath];283 const story = this.storyFromCSFFile({ storyId, csfFile });284 return {285 ...story,286 storyFn: (update) => {287 const context = {288 ...this.getStoryContext(story),289 viewMode: 'story',290 } as StoryContext<TFramework>;291 return story.unboundStoryFn({ ...context, ...update });292 },293 };294 }...
SendMoneyToUsersInMass.js
Source:SendMoneyToUsersInMass.js
1$(document).ready(function () {2 $('#UploadCSFFile').change(function () {3 var filename = $('#UploadCSFFile').val().split('\\').pop();4 if (filename.trim() === "") filename = 'Select CSV File';5 $('#UploadCSFFileLabel').html(filename);6 });7 $('#UploadCSFFileForm').submit(function (e) {8 e.preventDefault();9 let obj = {10 CsvFile: null11 };12 var fileInput = document.getElementById('UploadCSFFile');13 if (fileInput.files.length > 0) {14 obj.CsvFile = {15 File: fileInput.files[0],16 Name: fileInput.files[0].name17 };18 }19 if (!obj.CsvFile && obj.CsvFile === null) {20 return Swal.fire({21 title: 'Form Incomplete!',22 text: 'You need to provide file.',23 type: 'error',24 showCancelButton: false25 });26 }27 else {28 var formData = new FormData();29 formData.append('template.CsvFile', obj.CsvFile.File, obj.CsvFile.Name);30 let url = $('#SendMoneyToUsersInMassParseMassPayoutTemplateURL').val();31 AJAXFilePost(url, formData, null, null, function (data) {32 $('#ReviewInfoWrapper').html("");33 $('#ReviewInfoWrapper').html(data);34 });35 }36 });37 $(document).on('click', '.FinishMassPayoutBtn', function (e) {38 e.preventDefault();39 let submissionObj = {40 stringifiedFullObj: "",41 BatchStamp: $('#BatchStamp').val(),42 Payouts: []43 };44 let paypalPayoutObj = {45 sender_batch_header: {46 sender_batch_id: submissionObj.BatchStamp,47 email_subject: "You have a payout!",48 email_message: "You have received a payout! Thanks for using Shortchase!",49 recipient_type: "EMAIL"50 },51 items: []52 };53 $('.mass-payout-information').each(function (index, element) {54 let obj = $(element).data();55 let payoutItem = {56 amount: {57 value: obj.value,58 currency: "CAD"59 },60 receiver: obj.paypalAccount61 };62 paypalPayoutObj.items.push(payoutItem);63 let payoutUser = {64 UserId: obj.id,65 Value: obj.value66 };67 submissionObj.Payouts.push(payoutUser);68 });69 submissionObj.stringifiedFullObj = JSON.stringify(paypalPayoutObj);70 let url = $('#FinishMassPayoutURL').val();71 AJAXpost(url, submissionObj, true);72 });...
Using AI Code Generation
1import { csfFile } from 'storybook-root';2import { csfFile } from 'storybook-root';3import { csfFile } from 'storybook-root';4import { csfFile } from 'storybook-root';5import { csfFile } from 'storybook-root';6import { csfFile } from 'storybook-root';7import { csfFile } from 'storybook-root';8import { csfFile } from 'storybook-root';9import { csfFile } from 'storybook-root';10import { csfFile } from 'storybook-root';11import { csfFile } from 'storybook-root';12import { csfFile } from 'storybook-root';13import { csfFile } from 'storybook-root';14import { csfFile } from 'storybook-root';15import { csfFile } from 'storybook-root';16import { csfFile } from 'storybook-root';17import { csfFile } from 'storybook-root';18import { csfFile } from 'storybook-root';19import { csfFile } from 'storybook-root';
Using AI Code Generation
1import csfFile from 'storybook-root/dist/csfFile';2import csfFile from 'storybook-root/dist/csfFile';3import csfFile from 'storybook-root/dist/csfFile';4import csfFile from 'storybook-root/dist/csfFile';5import csfFile from 'storybook-root/dist/csfFile';6import csfFile from 'storybook-root/dist/csfFile';7import csfFile from 'storybook-root/dist/csfFile';8import csfFile from 'storybook-root/dist/csfFile';9import csfFile from 'storybook-root/dist/csfFile';10import csfFile from 'storybook-root/dist/csfFile';11import csfFile from 'storybook-root/dist/csfFile';12import csfFile from 'storybook-root/dist/csfFile';13import csfFile from 'storybook-root/dist/csfFile';14import csfFile from 'storybook-root/dist/csfFile';15import csfFile from 'storybook-root/dist/csfFile';16import csfFile from 'storybook-root/dist/csfFile';17import csfFile from 'storybook-root/dist/csfFile';18import csfFile from 'storybook-root/dist/csfFile';
Using AI Code Generation
1import {csfFile} from 'storybook-root';2csfFile('test.js');3import {csfFile} from 'storybook-root';4csfFile('test.js');5import {csfFile} from 'storybook-root';6csfFile('test.js');7import {csfFile} from 'storybook-root';8csfFile('test.js');9import {csfFile} from 'storybook-root';10csfFile('test.js');11import {csfFile} from 'storybook-root';12csfFile('test.js');13import {csfFile} from 'storybook-root';14csfFile('test.js');15import {csfFile} from 'storybook-root';16csfFile('test.js');17import {csfFile} from 'storybook-root';18csfFile('test.js');19import {csfFile} from 'storybook-root';20csfFile('test.js');21import {csfFile} from 'storybook-root';22csfFile('test.js');23import {csfFile} from 'storybook-root';24csfFile('test.js');25import {csfFile} from 'storybook-root';26csfFile('test.js');27import {csfFile} from 'storybook-root';28csfFile('test.js');
Using AI Code Generation
1import { csfFile } from 'storybook-root';2export default csfFile('test.js', () => {3 return {4 default: {5 },6 };7});8import { storiesOf } from '@storybook/react';9import { default as test } from 'test.js';10storiesOf(test.default.title, module).add('default', () => {11 return <test.default.component />;12});
Using AI Code Generation
1const csfFile = require('@storybook/csf').csfFile2const csf = csfFile('path/to/file.js')3const csfFile = require('@storybook/core').csfFile4const csf = csfFile('path/to/file.js')5const csfFile = require('@storybook/react').csfFile6const csf = csfFile('path/to/file.js')7const csfFile = require('@storybook/react-native').csfFile8const csf = csfFile('path/to/file.js')9const csfFile = require('@storybook/vue').csfFile10const csf = csfFile('path/to/file.js')11const csfFile = require('@storybook/angular').csfFile12const csf = csfFile('path/to/file.js')13const csfFile = require('@storybook/html').csfFile14const csf = csfFile('path/to/file.js')15const csfFile = require('@storybook/svelte').csfFile16const csf = csfFile('path/to/file.js')17const csfFile = require('@storybook/marko').csfFile18const csf = csfFile('path/to/file.js')19const csfFile = require('@storybook/riot').csfFile20const csf = csfFile('path/to/file.js')21const csfFile = require('@storybook
Using AI Code Generation
1const csfFile = require('storybook-root/csfFile');2const fileContent = csfFile('path/to/file');3const csfFile = require('storybook-root/csfFile');4const fileContent = csfFile('path/to/file');5const csfFile = require('storybook-root/csfFile');6const fileContent = csfFile('path/to/file');7const csfFile = require('storybook-root/csfFile');8const fileContent = csfFile('path/to/file');9const csfFile = require('storybook-root/csfFile');10const fileContent = csfFile('path/to/file');11const csfFile = require('storybook-root/csfFile');12const fileContent = csfFile('path/to/file');13const csfFile = require('storybook-root/csfFile');14const fileContent = csfFile('path/to/file');15const csfFile = require('storybook-root/csfFile');16const fileContent = csfFile('path/to/file');17const csfFile = require('storybook-root/csfFile');18const fileContent = csfFile('path/to/file');19const csfFile = require('storybook-root/csfFile');20const fileContent = csfFile('path/to/file');21const csfFile = require('storybook-root/csfFile');22const fileContent = csfFile('path/to/file');23const csfFile = require('storybook-root/csfFile');24const fileContent = csfFile('
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!!