Best JavaScript code snippet using storybook-root
util.js
Source:util.js
1/**2 * Created by isaac on 16/3/3.3 */4import {code} from "../config";5import moment from 'moment';6export const kScheduleDayIndexToKey = [7 'monday_items',8 'tuesday_items',9 'wednesday_items',10 'thursday_items',11 'friday_items',12 'saturday_items'13];14export function randomString() {15 let time = new Date().getTime();16 let suffix = Math.random()17 .toString(36)18 .substring(5);19 return `${time}-${suffix}`;20}21export function getTime() {22 return parseInt(new Date().getTime(), 10);23}24function orderFromDate(time, exact = true) {25 const time2 = moment(time).startOf('month').toDate();26 time2.setDate(1);27 let offset = 0;28 if (time2.getDay() > 1) {29 offset = -1;30 }31 const month = time.getMonth();32 const year = time.getFullYear();33 const firstWeekday = new Date(year, month, 1).getDay();34 const lastDateOfMonth = new Date(year, month + 1, 0).getDate();35 const offsetDate = time.getDate() + firstWeekday - 1;36 const index = 1; // start index at 0 or 1, your choice37 const weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7);38 const week = index + Math.floor(offsetDate / 7);39 let result = 0;40 if (exact || week < 2 + index) {41 result = week + offset;42 } else {43 result = (week === weeksInMonth ? index + 5 : week) + offset;44 }45 return result;46}47export function dateToWeekString(time) {48 const date = time.getDate();49 const day = time.getDay();50 let month = time.getMonth();51 const startDate = moment(time).startOf('week').add(1, 'days').toDate(); // normalize to monday of same week52 let order = orderFromDate(startDate);53 if (day > date) {54 // fix for month which has 5 weeks, it's last week of last month55 } else {56 ++month;57 }58 if (order === 0) {59 order = 4;60 }61 return `${time.getFullYear()}_${month}_${order}`;62}63export function listGenerator(64 req,65 Model,66 extraArgs,67 { populate, deepPopulate, sort } = {}68) {69 return new Promise((resolve, reject) => {70 let skip = parseInt(req.query.skip) || 0;71 let limit = parseInt(req.query.limit) || 20;72 let hospital = req.headers["x-hospital"];73 let args = {};74 if (extraArgs) {75 extraArgs.forEach(looper => {76 if (typeof looper === "string") {77 let value = req.query[looper];78 if (typeof value !== "undefined") {79 args[looper] = value;80 }81 } else if (typeof looper === "object") {82 Object.assign(args, looper);83 } else if (typeof looper === "function") {84 Object.assign(args, looper(req));85 }86 });87 } else {88 args.deleted = false;89 args.hospital = hospital;90 }91 Model.count(args, (error, count) => {92 if (error) {93 reject({ msg: error.message });94 } else {95 if (count === 0) {96 resolve({97 code: code.success,98 data: {99 total: 0,100 data: []101 }102 });103 } else {104 var middle = Model.find(args)105 .select("-__v")106 .skip(skip)107 .limit(limit);108 if (deepPopulate && deepPopulate.length > 0) {109 middle = middle.deepPopulate(deepPopulate);110 }111 if (populate) {112 middle = middle.populate(populate);113 }114 if (sort) {115 middle = middle.sort(sort);116 }117 middle.exec((err, docs) => {118 if (err) {119 console.log(err);120 reject({ msg: "æ¥æ¾å¤±è´¥ï¼" });121 } else {122 resolve({123 code: code.success,124 data: {125 total: count,126 data: docs127 }128 });129 }130 });131 }132 }133 });134 });135}136function validatePersonID(id, backInfo = true) {137 const info = {138 year: 1900,139 month: 1,140 day: 1,141 sex: "Male",142 valid: false,143 length: 0144 };145 const initDate = length => {146 info.length = length;147 const a = length === 15 ? 0 : 2; // 15:18148 info.year = parseInt((a ? "" : "19") + id.substring(6, 8 + a), 10);149 info.month = parseInt(id.substring(8 + a, 10 + a), 10) - 1;150 info.day = parseInt(id.substring(10 + a, 12 + a), 10);151 info.sex = id.substring(14, 15 + a) % 2 === 0 ? "Female" : "Male";152 const myDate = new Date();153 const temp = new Date(info.year, info.month, info.day);154 info.age = myDate.getFullYear() - temp.getFullYear();155 if (156 temp.getMonth() > myDate.getMonth() ||157 (temp.getMonth() === myDate.getDay() && temp.getMonth() > myDate.getDay())158 ) {159 info.age -= 1;160 }161 return (162 temp.getFullYear() === info.year &&163 temp.getMonth() === info.month &&164 temp.getDate() === info.day165 );166 };167 const back = () => {168 return backInfo ? info : info.valid;169 };170 if (typeof id !== "string") return back();171 // 18172 if (/^\d{17}[0-9x]$/i.test(id)) {173 if (!initDate(18)) return back();174 id = id.toLowerCase().split("");175 const wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];176 const y = "10x98765432".split("");177 let sum = 0;178 for (let i = 0; i < 17; i++) sum += wi[i] * id[i];179 if (y[sum % 11] === id.pop().toLowerCase()) info.valid = true;180 return back();181 } else if (/^\d{15}$/.test(id)) {182 // 15ä½183 if (initDate(15)) info.valid = true;184 return back();185 } else {186 return back();187 }188}189async function filterJudge(result, key, superKey, keyString, value) {190 if (result) {191 return value === undefined192 ? { key: superKey }193 : { object: { [key]: value }, key: superKey };194 } else {195 throw { code: code.fail, msg: `åæ°${keyString}éªè¯å¤±è´¥ï¼` };196 }197}198export function enumFilterCreator(enums) {199 return value => enums.includes(value);200}201export async function argsFilter(args = {}, rules, superKey, keyString) {202 const deleteKeys = [];203 const filterStr = {204 always: () => true, // æä¸careå®ï¼ ââChloric205 empty: () => false,206 required: value => typeof value !== "undefined",207 array: Array.isArray,208 int: Number.isInteger,209 string: value => typeof value === "string",210 bool: value => typeof value === "boolean",211 personID: value => validatePersonID(value, false),212 phone(value) {213 const phone = value.toString();214 return phone[0] === "1" && phone.length === 11;215 },216 // id: mongoose.Types.ObjectId.isValid, // åï¼217 id: value => value.toString().match(/^[0-9a-fA-F]{24}$/),218 undefined() {219 throw { code: code.fail, msg: "æªç¥çéªè¯è§åï¼" };220 }221 };222 const argsChange = {223 boolStr: {224 rule: "bool",225 change(arg) {226 if (arg === "true") {227 return true;228 } else if (arg === "false") {229 return false;230 } else {231 return arg;232 }233 }234 },235 intStr: {236 rule: "int",237 change: parseInt238 }239 };240 const filterType = {241 string: (rule, value, key, keyString, superKey) =>242 filterJudge(243 (filterStr[rule] || filterStr.undefined)(value),244 key,245 superKey,246 keyString,247 value248 ),249 async object(rule, value, key, keyString, superKey) {250 const argsObj =251 value === null252 ? { object: { [key]: value } }253 : await argsFilter(value, rule, key, keyString);254 argsObj.key = superKey;255 return argsObj;256 },257 function: (rule, value, key, keyString, superKey) =>258 filterJudge(rule(value), key, superKey, keyString, value)259 };260 const results = await Promise.all(261 Object.keys(rules).map(key => {262 const superKeyStr = `${keyString ? `${keyString}.` : ""}${key}`;263 if (typeof args[key] === "undefined") {264 if (typeof rules[key] === "object") {265 args[key] = {};266 deleteKeys.push(key);267 } else if (268 rules[key] !== "required" ||269 (Array.isArray(rules[key]) && !rules[key].includes("required"))270 ) {271 rules[key] = "always";272 }273 }274 if (argsChange[rules[key]]) {275 const { rule, change } = argsChange[rules[key]];276 rules[key] = rule;277 args[key] = change(args[key]);278 } else if (Array.isArray(rules[key])) {279 for (const changeRule of rules[key]) {280 if (argsChange[changeRule]) {281 const { rule, change } = argsChange[changeRule];282 rules[key] = rules[key].filter(rule => rule !== changeRule);283 rules[key].push(rule);284 args[key] = change(args[key]);285 break;286 }287 }288 }289 return Array.isArray(rules[key])290 ? Promise.all(291 rules[key].map(rule =>292 filterType[typeof rule](293 rule,294 args[key],295 key,296 superKeyStr,297 superKey298 )299 )300 )301 : filterType[typeof rules[key]](302 rules[key],303 args[key],304 key,305 superKeyStr,306 superKey307 );308 })309 );310 let key;311 const result = results312 .map(result => {313 if (Array.isArray(result)) {314 result.forEach(resultItem => (key = key || resultItem.key));315 } else {316 key = key || result.key;317 }318 return result;319 })320 .filter(321 result =>322 Array.isArray(result)323 ? result.length > 0324 : typeof result.object !== "undefined"325 )326 .map(result => (Array.isArray(result) ? result[0] : result))327 .reduce((resultObject, { object }) => ({ ...resultObject, ...object }), {});328 deleteKeys.forEach(deleteKey => delete result[deleteKey]);329 return key ? { object: { [key]: result } } : result;...
rendering.stories.js
Source:rendering.stories.js
1import React, { useEffect, useRef } from 'react';2import { useArgs } from '@storybook/client-api';3export default {4 title: 'Core/Rendering',5};6// NOTE: in our example apps each component is mounted twice as we render in strict mode7let timesCounterMounted = 0;8export const Counter = () => {9 const countRef = useRef();10 if (!countRef.current) timesCounterMounted += 1;11 countRef.current = (countRef.current || 0) + 1;12 return (13 <div>14 Mounted: {timesCounterMounted}, rendered (this mount): {countRef.current}15 </div>16 );17};18// An example to test what happens when the story is remounted due to argChanges19let timesArgsChangeMounted = 0;20export const ArgsChange = () => {21 const countRef = useRef();22 if (!countRef.current) timesArgsChangeMounted += 1;23 countRef.current = true;24 return (25 <div>26 Mounted: {timesArgsChangeMounted} (NOTE: we use strict mode so this number is 2x what you'd27 expect -- it should be 2, not 4 though!)28 </div>29 );30};31ArgsChange.args = {32 first: 0,33};34ArgsChange.decorators = [35 (StoryFn) => {36 const [args, updateArgs] = useArgs();37 useEffect(() => {38 if (args.first === 0) {39 updateArgs({ first: 1 });40 }41 }, []);42 return <StoryFn />;43 },...
Using AI Code Generation
1import { ArgsChange } from 'storybook-root';2ArgsChange('MyButton', { label: 'MyLabel' });3import { ArgsChange } from 'storybook-root';4ArgsChange('MyButton', () => {5 return {6 };7});8ArgsChange() method accepts two parameters:
Using AI Code Generation
1import { ArgsChange } from 'storybook-root';2export { ArgsChange } from './utils/ArgsChange';3export { ArgsChange } from 'storybook-addon-props-combinations';4export { ArgsChange } from 'storybook-addon-props-combinations';5export { ArgsChange } from 'storybook-addon-props-combinations';6export { ArgsChange } from 'storybook-addon-props-combinations';7export { ArgsChange } from 'storybook-addon-props-combinations';8export { ArgsChange } from 'storybook-addon-props-combinations';9export { ArgsChange } from 'storybook-addon-props-combinations';10export { ArgsChange } from 'storybook-addon-props-combinations';11export { ArgsChange } from 'storybook-addon-props-combinations';12export { ArgsChange } from 'storybook-addon-props-combinations';13export { ArgsChange } from 'storybook-addon-props-combinations';
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!!