Best JavaScript code snippet using storybook-root
index.js
Source:index.js
1import Realm from 'realm';2import findIndex from 'lodash/findIndex';3import normalizeStory, { normalizeReduxStory } from '../normalizer/Realm';4import { dispatch } from '../store';5import { bootstrapLibrary } from '../ducks/library';6import getSchemas from './schema';7class Storage {8 init(id) {9 if (this.realm) return;10 const { schema, schemaVersion } = this.applyMigrations();11 this.realm = new Realm({12 path: `db${id}.realm`,13 schema,14 schemaVersion,15 });16 this.stories = this.getStorage();17 this.historyStories = this.getHistoryStories;18 this.downloadedStories = this.getDownloadStories;19 this.recommendedStories = this.getRecommendedStories;20 }21 applyMigrations() { // TODO we can skip this step if user database created first time22 const schemas = getSchemas();23 const realmSchemaVer = Realm.schemaVersion(Realm.defaultPath);24 let nextSchemaIndex = Math.max(realmSchemaVer, 0);25 while (nextSchemaIndex < schemas.length) {26 const migratedRealm = new Realm(schemas[nextSchemaIndex++]);27 migratedRealm.close();28 }29 return schemas[schemas.length - 1];30 }31 getStorage() {32 return this.realm.objects('Story');33 }34 getHistoryStories() {35 return this.getStorage()36 .filtered('lastOpenedAt >= $0', new Date(0))37 .sorted('lastOpenedAt', true);38 }39 getRecommendedStories() {40 return this.getStorage()41 .filtered('recommended == true AND offline == false');42 }43 getDownloadStories() {44 return this.realm.objects('Story')45 .filtered('offline == true AND recommended == false')46 .sorted('dowloadedAt', true);47 }48 release() {49 this.realm = null;50 this.stories = null;51 this.historyStories = null;52 this.downloadedStories = null;53 this.recommendedStories = null;54 }55}56const storage = new Storage();57export default storage;58export const bootstrapOfflineLibrary = () => {59 dispatch(bootstrapLibrary({60 entities: {61 stories: storage.stories.reduce((acc, story) => {62 acc[story.id] = normalizeReduxStory(story);63 return acc;64 }, {}),65 },66 stories: storage.stories.reduce((acc, story) => {67 acc[story.id] = story;68 return acc;69 }, {}),70 recommended: storage.recommendedStories().map(s => s.id),71 history: storage.historyStories().map(s => s.id),72 download: storage.downloadedStories().map(s => s.id),73 }));74};75export const saveStory = (story, chapters, chapter, number) => {76 storage.realm.write(() => {77 storage.realm.create(78 'Story',79 normalizeStory(story, chapters, chapter, number),80 true81 );82 });83};84export const saveNewChapter = (id, chapterNumber, chapter) => {85 storage.realm.write(() => {86 const story = storage.stories.find(s => s.id === id);87 const chapterIndex = findIndex(story.chapters, ch => ch.chapter_number === chapterNumber);88 const prevChapterIndex = findIndex(story.chapters, ch => ch.chapter_number === story.currentChapter);89 story.lastOpenedAt = new Date();90 story.chapters[prevChapterIndex].text = undefined;91 story.chapterOffset = 0.0;92 story.chapters[chapterIndex].text = chapter.text;93 story.chapterId = chapter.id;94 story.currentChapter = chapterNumber;95 });96};97export const downloadStory = (story, chapters, currentChapter = 1, recommended = false, date) => {98 let realmStory;99 if (storage.realm) {100 storage.realm.write(() => {101 const normalizedStory = normalizeStory(story, chapters);102 normalizedStory.offline = true;103 normalizedStory.dowloadedAt = date;104 normalizedStory.currentChapter = currentChapter;105 normalizedStory.recommended = recommended;106 realmStory = storage.realm.create('Story', normalizedStory, true);107 });108 return realmStory;109 }110};111export const unDownloadStory = (id) => {112 const story = storage.stories.find(s => s.id === id);113 storage.realm.write(() => {114 storage.realm.delete(story);115 });116};117export const updateStoryOffset = (offset, id) => {118 const story = storage.stories.find(s => s.id === id);119 if (story) {120 storage.realm.write(() => {121 story.chapterOffset = offset;122 });123 }124};125export const updateReviewsCounter = (count, id) => {126 const story = storage.stories.find(s => s.id === id);127 if (story) {128 storage.realm.write(() => {129 story.reviews_count = count;130 });131 }132};133export const updateChapterNumber = (id, number) => {134 const story = storage.stories.find(s => s.id === id);135 storage.realm.write(() => {136 story.currentChapter = number;137 });138};139export const isInStorage = (id) => {140 return !!(storage.stories.find(story => story.id === id));141};142export const isNotShortStory = (id) => {143 return !!(storage.stories.find(story => story.id === id).chapters.length !== 0);144};145export const isChapterInStorage = (id, chapterNumber) => {146 return !!(storage.stories.find(story => story.id === id).currentChapter === chapterNumber);147};148export const isStoryDownloaded = (id) => {149 return !!(storage.downloadedStories().find(story => story.id === id));150};151export const getStory = (id) => {152 const story = storage.stories.find(s => s.id === id);153 storage.realm.write(() => {154 story.lastOpenedAt = new Date();155 });156 return story;157};158export const getHistory = () => {159 return storage.historyStories().map(s => s.id);160};161export const getDownload = () => {162 return storage.downloadedStories().map(s => s.id);163};164export const getRecommended = () => {165 return storage.recommendedStories().map(s => s.id);...
normalize.ts
Source:normalize.ts
1import { UserCalendar } from "~/src/core/v1/calendar/UserCalendar/model";2import { BaseStory } from "~/src/core/v1/story/BaseStory";3import { BaseResource } from "~/src/core/v1/resource/BaseResource";4import { BaseEvent } from "~/src/core/v1/event/BaseEvent";5import { PROFILE_ID } from "~/src/constants/fullcalendar";6// --------------------7// Calendar8// -----------------------9export const normalizeCalendar = (obj: UserCalendar) => {10 const stories = normalizeStoriesList(obj.stories);11 return {12 id: obj.id,13 stories,14 };15};16export type NormalizedUserCalendar = {17 id: string;18 stories: NormalizedStory[];19};20// --------------------21// Story22// -----------------------23export type NormalizedStory = {24 id: string;25 title: string;26 resources: NormalizedResource[];27};28const isProfileStory = (maybe: BaseStory) => maybe.id === PROFILE_ID;29const normalizeStoriesList = (list: BaseStory[]): NormalizedStory[] =>30 list31 .filter((item) => !isProfileStory(item))32 .map((item) => normalizeStory(item));33const normalizeStory = (obj: BaseStory): NormalizedStory => {34 const resources = normalizeResourcesList(obj.resources, obj.events);35 return {36 id: obj.id,37 title: obj.name,38 resources,39 };40};41// -----------------------42// Resource43// -----------------------44type NormalizedResource = {45 id: string;46 title: string;47 events: NormalizedEvent[];48 order: number;49};50const normalizeResourcesList = (51 resources: BaseResource[],52 events: BaseEvent[]53): NormalizedResource[] => {54 return resources.map((item) => {55 const thisEvents = events.filter((it) => it.resourceId === item.id);56 const normalizedEvents = normalizeEventsList(thisEvents);57 return {58 id: item.id,59 title: item.FIELD,60 order: item.order ?? 0,61 events: normalizedEvents,62 };63 });64};65// -----------------------66// Event67// -----------------------68type NormalizedEvent = {69 id: string;70 title: string;71 description: string;72 startedAt: string;73 endedAt: string;74 backgroundColor?: string;75};76const normalizeEventsList = (obj: BaseEvent[]): NormalizedEvent[] =>77 obj.map((it) => normalizeEvent(it));78const normalizeEvent = (obj: BaseEvent): NormalizedEvent => ({79 id: obj.id,80 title: obj.title,81 description: obj.extendedProps?.description ?? "",82 startedAt: obj.start as string,83 endedAt: obj.end as string,84 // options85 backgroundColor: obj.backgroundColor,86});...
api.js
Source:api.js
1import axios from 'axios';2const requestConfig = () => ({3 headers: {4 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,5 'X-Requested-With': 'XMLHttpRequest'6 }7})8const normalizeTags = (tags) => tags.map((tag) => tag.id || tag.name);9export const updateContent = (storyId, story, storyLocale) => {10 const normalizedStory = {11 ...story,12 tag_ids: normalizeTags(story.tags)13 }14 if (storyId) {15 return axios.put(`/stories/${storyId}.json?story_builder=true&story_locale=${storyLocale}`, { story: normalizedStory }, requestConfig());16 } else {17 return axios.post(`/stories.json?story_builder=true&story_locale=${storyLocale}`, { story: normalizedStory }, requestConfig());18 }19}20export const uploadImage = (story, file, onProgress) => {21 const form = new FormData();22 form.append("Content-Type", file.type);23 form.append("image[picture]", file);24 form.append("image[imageable_type]", "Story");25 form.append("image[imageable_id]", story.id)26 const options = {27 ...requestConfig(),28 onUploadProgress: progressEvent => onProgress((progressEvent.loaded / progressEvent.total) * 100)29 };30 return axios.post(`/commoners/${story.commoner_id}/images`, form, options);31};32export const deleteImage = (commonerId, imageUrl) => {33 const imageId = imageUrl.match(new RegExp(`/images/(\\d+)`))[1];34 return axios.delete(`/commoners/${commonerId}/images/${imageId}`, requestConfig());35}36export const publishStory = (storyId, locale, options = {}) => {37 return axios.post(`/${locale}/stories/${storyId}/publish`, options, requestConfig());...
Using AI Code Generation
1import { addDecorator } from '@storybook/react';2import { withRootProvider } from 'storybook-root-provider';3addDecorator(withRootProvider);4import { addons } from '@storybook/addons';5import { withRootProvider } from 'storybook-root-provider';6addons.setConfig({7});8addons.register('storybook-root-provider', withRootProvider);
Using AI Code Generation
1import { normalizedStory } from 'storybook-root-provider'2import { storiesOf } from '@storybook/react'3import { withInfo } from '@storybook/addon-info'4storiesOf('Button', module)5 .add('with text', normalizedStory(() => (6 .add('with emoji', normalizedStory(() => (7 )), { info: 'My info' })8 .add('with info', withInfo('My info')(() => (9import './test'10import { configure } from '@storybook/react'11import { setOptions } from '@storybook/addon-options'12import { setDefaults } from 'storybook-addon-jsx'13setOptions({
Using AI Code Generation
1import { normalizedStory } from 'storybook-root-provider';2const story = normalizedStory(require('./__stories__/index.story.js'));3const { name } = story;4export default {5};6import Test from '../test';7export default {8};9import Test from '../../test';10export default {11};12import Test from '../../../test';13export default {14};15import Test from '../../../../test';16export default {17};18import Test from '../../../../../test';19export default {20};21import Test from '../../../../../../test';22export default {23};24import Test from '../../../../../../../test';25export default {26};27import Test from '../../../../../../../../test';28export default {29};30import Test from '../../../../../../../../../test';31export default {32};33import Test from '../../../../../../../../../../test';34export default {35};
Using AI Code Generation
1import { normalizedStory } from 'storybook-root-provider';2const story = normalizedStory('MyStory', { title: 'My Story' });3const story = normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } });4const story = normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } }, { arg1: 'some value' });5import { getStorybookRoot } from 'storybook-root-provider';6const storybookRoot = getStorybookRoot();7const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' });8const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } });9const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } }, { arg1: 'some value' });10import { getStorybookRoot } from 'storybook-root-provider';11const storybookRoot = getStorybookRoot('my-root');12const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' });13const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } });14const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } }, { arg1: 'some value' });15import { getStorybookRoot } from 'storybook-root-provider';16const storybookRoot = getStorybookRoot('my-root');17const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' });18const story = storybookRoot.normalizedStory('MyStory', { title: 'My Story' }, { argTypes: { arg1: { control: 'text' } } });19const story = storybookRoot.normalizedStory('My
Using AI Code Generation
1const story = normalizedStory('Button', 'Primary');2const { container } = render(story);3expect(container).toMatchSnapshot();4const story = normalizedStory('Button', 'Primary');5const { container } = render(story);6expect(container).toMatchSnapshot();7const story = normalizedStory('Button', 'Primary');8const { container } = render(story);9expect(container).toMatchSnapshot();10const story = normalizedStory('Button', 'Primary');11const { container } = render(story);12expect(container).toMatchSnapshot();13const story = normalizedStory('Button', 'Primary');14const { container } = render(story);15expect(container).toMatchSnapshot();16const story = normalizedStory('Button', 'Primary');17const { container } = render(story);18expect(container).toMatchSnapshot();19const story = normalizedStory('Button', 'Primary');20const { container } = render(story);21expect(container).toMatchSnapshot();22const story = normalizedStory('Button', 'Primary');23const { container } = render(story);24expect(container).toMatchSnapshot();
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!!