Best JavaScript code snippet using storybook-root
AddProject.js
Source:AddProject.js
1import React, { useCallback } from 'react';2import {3 Button,4 FormControl,5 FormLabel,6 FormErrorMessage,7 Input,8 HStack,9 Alert,10 AlertIcon,11 CloseButton,12 useDisclosure,13 Text,14} from '@chakra-ui/react';15import { Formik, Form } from 'formik';16const errorMap = {17 required: 'Please enter a Storybook URL',18 format: 'Please enter a correctly formatted URL',19};20const urlRegExp = new RegExp(21 // eslint-disable-next-line no-useless-escape22 /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi23);24const validate = ({ storybookUrl }) => {25 const errors = {};26 if (!storybookUrl) {27 errors.storybookUrl = errorMap.required;28 } else {29 const validStorybookUrl = storybookUrl.match(urlRegExp);30 if (validStorybookUrl === null) {31 errors.storybookUrl = errorMap.format;32 }33 }34 return errors;35};36export const AddProject = () => {37 const {38 isOpen: submitSuccessful,39 onClose: closeSuccessAlert,40 onOpen: openSuccessAlert,41 } = useDisclosure({ defaultIsOpen: false });42 const {43 isOpen: submitFailed,44 onClose: closeFailedAlert,45 onOpen: openFailedAlert,46 } = useDisclosure({ defaultIsOpen: false });47 const handleFormSubmit = useCallback(48 async ({ storybookUrl }, { setSubmitting, resetForm }) => {49 setSubmitting(true);50 fetch('/project', {51 method: 'POST',52 body: JSON.stringify({ storybookUrl }),53 })54 .then((res) => res.json())55 .then(() => {56 setSubmitting(false);57 openSuccessAlert();58 resetForm({59 values: { storybookUrl: '' },60 });61 })62 .catch(() => {63 openFailedAlert();64 setSubmitting(false);65 });66 },67 [openSuccessAlert, openFailedAlert]68 );69 return (70 <>71 <Formik72 initialValues={{73 email: '',74 password: '',75 verifiedPassword: '',76 }}77 onSubmit={handleFormSubmit}78 validate={validate}79 >80 {({81 touched,82 errors,83 values,84 isSubmitting,85 handleChange,86 handleBlur,87 }) => (88 <HStack89 as={Form}90 noValidate91 aria-disabled={isSubmitting ? 'true' : 'false'}92 spacing="3"93 mb={8}94 alignItems="flex-start"95 >96 <FormControl97 id="storybookUrl"98 isRequired99 isInvalid={touched.storybookUrl && errors.storybookUrl}100 >101 <FormLabel srOnly>Storybook URL</FormLabel>102 <Input103 type="text"104 placeholder="Enter the URL for the Storybook"105 size="lg"106 fontSize="md"107 onChange={handleChange}108 onBlur={handleBlur}109 value={values.storybookUrl}110 />111 {touched.storybookUrl && errors.storybookUrl && (112 <Text color="red" mt={2}>113 {errors.storybookUrl}114 </Text>115 )}116 </FormControl>117 <Button118 type="submit"119 fontWeight="bold"120 fontSize="md"121 colorScheme="blue"122 size="lg"123 isLoading={isSubmitting}124 >125 Import126 </Button>127 </HStack>128 )}129 </Formik>130 {submitSuccessful && (131 <Alert status="success">132 <AlertIcon />133 Project added successfully134 <CloseButton ml="auto" onClick={closeSuccessAlert} />135 </Alert>136 )}137 {submitFailed && (138 <Alert status="error">139 <AlertIcon />140 Something went wrong. Unable to add this project.141 <CloseButton ml="auto" onClick={closeFailedAlert} />142 </Alert>143 )}144 </>145 );...
index.ts
Source:index.ts
1import {2 StorybookConnection,3 StoriesBrowser,4 StoryPreviewBrowser,5 MetricsWatcher,6 createExecutionService,7 Story,8} from 'storycrawler';9import { writeFile } from 'fs';10import { JSDOM } from 'jsdom';11type FetchResult = { story: Story; outerHTML: string | undefined };12const getConnection = async (storybookUrl: string) => {13 return await new StorybookConnection({14 storybookUrl,15 }).connect();16};17const getOuterHTML: (18 story: Story19) => (worker: StoryPreviewBrowser) => Promise<FetchResult> =20 (story) => async (worker) => {21 await worker.setCurrentStory(story);22 await new MetricsWatcher(worker.page).waitForStable();23 const pageHandle = await worker.page.$('#root');24 const outerHTMLHandle = await pageHandle?.getProperty('outerHTML');25 const outerHTML = await outerHTMLHandle?.jsonValue<string>();26 return { story, outerHTML };27 };28const writeResultToHtmlFile = (result: FetchResult) => {29 if (result.outerHTML) {30 console.log('id:', result.story.id);31 console.log('outerHTML:', result.outerHTML);32 const jsdom = new JSDOM();33 const parser = new jsdom.window.DOMParser();34 const parsedDom = parser.parseFromString(result.outerHTML, 'text/html');35 writeFile(36 `rendered/${result.story.id}.html`,37 parsedDom.documentElement.outerHTML,38 (err) => {39 throw err;40 }41 );42 }43};44(async function () {45 const storybookUrl = 'https://storybookjs.netlify.app/vue-kitchen-sink';46 const connection = await getConnection(storybookUrl);47 console.log(`connected to ${storybookUrl}`);48 const storiesBrowser = await new StoriesBrowser(connection).boot();49 const stories = await storiesBrowser.getStories();50 console.log(`found ${stories.length} stories`);51 const workers = await Promise.all(52 [0, 1, 2, 3].map((i) => new StoryPreviewBrowser(connection, i).boot())53 );54 try {55 const service = createExecutionService(workers, stories, getOuterHTML);56 const results = await service.execute();57 results.forEach(writeResultToHtmlFile);58 } finally {59 await storiesBrowser.close();60 await Promise.all(workers.map((worker) => worker.close()));61 await connection.disconnect();62 }...
get.storybooks.from.registry.js
Source:get.storybooks.from.registry.js
1const axios = require('axios');2/*3 This package ss used to collect responses from attempting to reach each storybook in the registry4 It will return an array of objects in the form:5 { name, version, exists, url } where name is the packageName, exists is true if the storybook6 exists andurl is the url of the storybook.7*/8const BASE_STORIES_URL = 'https://aui-cdn.atlassian.com/atlaskit/stories/';9function getPackageStorybook(packageName, packageVersion) {10 const storybookURL = `${BASE_STORIES_URL}${packageName}/${packageVersion}/`;11 return axios.head(storybookURL)12 // If the promise resolved, the storybook is there13 .then(() => Promise.resolve({14 name: packageName,15 version: packageVersion,16 exists: true,17 url: storybookURL,18 }))19 // If it errored, we still resolve the promise so we can pass the packageName back20 .catch(() => Promise.resolve({21 name: packageName,22 version: packageVersion,23 exists: false,24 url: storybookURL,25 }));26}27/* Returns an array of reponses for the storybooks requested.28 packages should be an array of objects in the form { name, version }29*/30function getStorybooksFromRegistry(packages) {31 // we return once all the promises are resolved32 return Promise.all(packages.map(pkg => getPackageStorybook(pkg.name, pkg.version)));33}...
Using AI Code Generation
1import {storybookUrl} from 'storybook-root';2import {storybookUrl} from 'storybook-root';3import {storybookUrl} from 'storybook-root';4import {storybookUrl} from 'storybook-root';5import {storybookUrl} from 'storybook-root';6import {storybookUrl} from 'storybook-root';7import {storybookUrl} from 'storybook-root';8import {storybookUrl} from 'storybook-root';9import {storybookUrl} from 'storybook-root';10import {storybookUrl} from 'storybook-root';11import {storybookUrl} from 'storybook-root';12import {storybookUrl} from 'storybook-root';13import {storybookUrl} from 'storybook-root';14import {storybookUrl} from 'storybook-root';15import {storybookUrl} from 'storybook-root';16import {storybookUrl} from 'storybook-root';17import {storybookUrl} from 'storybook-root';18import {storybookUrl} from 'storybook-root';19import {storybookUrl} from 'storybook-root';20import {storybookUrl} from 'storybook
Using AI Code Generation
1const storybookUrl = require('storybook-root').storybookUrl;2const url = storybookUrl('my-storybook-name', 'my-story-name');3console.log(url);4const storybookUrl = require('storybook-root').storybookUrl;5const url = storybookUrl('my-storybook-name', 'my-story-name', {6});7console.log(url);8const storybookUrl = require('storybook-root').storybookUrl;9const url = storybookUrl('my-storybook-name', 'my-story-name', {10console.log(url);11const storybookUrl = require('storybook-root').storybookUrl;12const url = storybookUrl('my-storybook-name', 'my-story-name', {
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!!