Best JavaScript code snippet using storybook-root
Main.js
Source:Main.js
1import React from 'react';2//removed axios for space. Add back in as needed3// import axios from 'axios';4import { withRouter } from 'react-router-dom';5import SingleRoom from '../SingleRoom/SingleRoom';6import FullSchedule from '../FullSchedule/FullSchedule';7import GenericInfoSection from '../GenericInfoSection/GenericInfoSection';8import Loading from '../Loading/Loading';9import Map from '../Map/Map';10import { filterTimes, filterToday, orderTimes } from '../../utils/helpers';11import './main.css';12import * as example from 'testConfig/testconfig1.json';13import * as fullSchedule from 'testConfig/super_2022.json';14import mountainsTextCombined from '../../assets/pictures/mountainsTextCombined.svg';15class Main extends React.Component {16 constructor(props){17 super(props);18 this.state = {19 isFull: true,20 schedule: fullSchedule.default,21 loading: false,22 filtered: false,23 gaylordRoom: ""24 }25 }26 componentDidMount() {27 this.doPanelThings();28 this.interval = setInterval(this.doPanelThings, 600000);29 }30 componentWillUnmount() {31 clearInterval(this.interval);32 }33 doPanelThings = () => {34 let { isFull, filtered } = this.state;35 if (this.props.location.pathname.includes("filtered")) {36 filtered = true;37 } else {38 filtered = false;39 }40 if (this.props.location.pathname.includes("single")) {41 isFull = false;42 } else {43 isFull = true;44 };45 this.setState({ isFull, filtered });46 this.getPanelInfo(isFull, filtered)47 }48 getPanelInfo = (isFullCopy, isFiltered) => {49 if (!isFullCopy) {50 const returnedQuery = this.getQueryString();51 let filteredPanels = this.filterByName(returnedQuery);52 this.cleanPanelInfoTimes(true, isFiltered, filteredPanels);53 }54 // NOTE: Uncomment this when filtering and ordering is desired55 if (isFullCopy) {56 this.cleanPanelInfoTimes(false, isFiltered);57 }58 }59 cleanPanelInfoTimes = ( isSingleSchedule = false, isFiltered = false, filteredPanels = []) => {60 let { schedule: tempSchedule } = this.state;61 if (!isFiltered)62 return;63 if ( isSingleSchedule && filteredPanels.length > 0 ){64 tempSchedule = filterToday(filteredPanels);65 }66 tempSchedule = orderTimes(filterTimes(tempSchedule));67 this.setState({ schedule: tempSchedule });68 }69 getQueryString = () => {70 const queryToParse = new URLSearchParams(this.props.location.search);71 const query = queryToParse.get('place');72 return query;73 }74 filterByName = ( filterKeyword ) => {75 let { schedule: tempPanels } = this.state;76 let gaylordRoomExtr = "";77 const filteredPanels = tempPanels.filter( key => { 78 return key.location.includes(filterKeyword) 79 });80 if (filteredPanels.length >= 1) {81 gaylordRoomExtr = filteredPanels[0].location.match(/\(([^)]+)\)/)?.[1] ?? "N/A";82 }83 this.setState({ schedule: filteredPanels, gaylordRoom: gaylordRoomExtr });84 return filteredPanels;85 }86 render(){87 const { schedule, loading, isFull, gaylordRoom } = this.state;88 const { main_event: smallSchedule } = example.default.rooms;89 return (90 <div id="main-container">91 <div id="header">92 <div className="generic-info-box">93 <GenericInfoSection isFull={isFull} />94 </div>95 <img src={ mountainsTextCombined } className="mountainsCombined" />96 </div><div id="background-colors">97 <div id="panels-info" 98 className={(isFull) ? "is-full-class": "is-small-class"}99 >100 <div className="left-side">101 <Map isFull={isFull} />102 </div>103 <div className="right-side">104 {105 (loading) ? (106 <Loading />107 ):(this.state.schedule.length === 0) ? (108 <div className={"empty-message " + ((isFull)? "tan" : "orange")}>109 Nothing to show here!110 </div>111 ): 112 ((isFull) ?113 <div>114 <FullSchedule fullSchedule={ schedule } />115 </div>116 :117 <div>118 { gaylordRoom &&119 <div className="single-room-panel-name">120 <span>121 <b>Panel Room:</b> { this.getQueryString() }122 </span>123 <span><b>Gaylord Room:</b> { gaylordRoom}124 </span>125 </div>126 }127 <SingleRoom schedule={ schedule } />128 </div>129 )}130 </div>131 </div>132 </div>133 </div>134 )135 }136}...
addons.test.js
Source:addons.test.js
1import initAddons, { types } from '../modules/addons';2const PANELS = {3 a11y: {4 title: 'Accessibility',5 paramKey: 'a11y',6 },7 actions: {8 title: 'Actions',9 paramKey: 'actions',10 },11 knobs: {12 title: 'Knobs',13 paramKey: 'knobs',14 },15};16const provider = {17 getElements(type) {18 if (type === types.PANEL) {19 return PANELS;20 }21 return null;22 },23};24const store = {25 getState: () => ({26 selectedPanel: '',27 }),28 setState: jest.fn(),29};30describe('Addons API', () => {31 describe('#getElements', () => {32 it('should return provider elements', () => {33 // given34 const { api } = initAddons({ provider, store });35 // when36 const panels = api.getElements(types.PANEL);37 // then38 expect(panels).toBe(PANELS);39 });40 });41 describe('#getPanels', () => {42 it('should return provider panels', () => {43 // given44 const { api } = initAddons({ provider, store });45 // when46 const panels = api.getPanels();47 // then48 expect(panels).toBe(PANELS);49 });50 });51 describe('#getStoryPanels', () => {52 it('should return all panels by default', () => {53 // given54 const { api } = initAddons({ provider, store });55 // when56 const filteredPanels = api.getStoryPanels();57 // then58 expect(filteredPanels).toBe(PANELS);59 });60 it('should filter disabled addons', () => {61 // given62 const storyId = 'story 1';63 const storeWithStory = {64 getState: () => ({65 storyId,66 storiesHash: {67 [storyId]: {68 parameters: {69 a11y: { disabled: true },70 },71 },72 },73 }),74 setState: jest.fn(),75 };76 const { api } = initAddons({ provider, store: storeWithStory });77 // when78 const filteredPanels = api.getStoryPanels();79 // then80 expect(filteredPanels).toEqual({81 actions: PANELS.actions,82 knobs: PANELS.knobs,83 });84 });85 });86 describe('#getSelectedPanel', () => {87 it('should return provider panels', () => {88 // given89 const storeWithSelectedPanel = {90 getState: () => ({91 selectedPanel: 'actions',92 }),93 setState: jest.fn(),94 };95 const { api } = initAddons({ provider, store: storeWithSelectedPanel });96 // when97 const selectedPanel = api.getSelectedPanel();98 // then99 expect(selectedPanel).toBe('actions');100 });101 it('should return first panel when selected is not a panel', () => {102 // given103 const storeWithSelectedPanel = {104 getState: () => ({105 selectedPanel: 'unknown',106 }),107 setState: jest.fn(),108 };109 const { api } = initAddons({ provider, store: storeWithSelectedPanel });110 // when111 const selectedPanel = api.getSelectedPanel();112 // then113 expect(selectedPanel).toBe('a11y');114 });115 });116 describe('#setSelectedPanel', () => {117 it('should set value inn store', () => {118 // given119 const setState = jest.fn();120 const storeWithSelectedPanel = {121 getState: () => ({122 selectedPanel: 'actions',123 }),124 setState,125 };126 const { api } = initAddons({ provider, store: storeWithSelectedPanel });127 expect(setState).not.toHaveBeenCalled();128 // when129 api.setSelectedPanel('knobs');130 // then131 expect(setState).toHaveBeenCalledWith({ selectedPanel: 'knobs' }, { persistence: 'session' });132 });133 });...
popup.ts
Source:popup.ts
1// Enable chromereload by uncommenting this line:2// import 'chromereload/devonly'3import { menuConfig, menuItemObject } from './shared';4import { hostname } from 'os';5const panel = document.querySelector('.panel') as HTMLDivElement;6const filterInput = document.querySelector('.filter') as HTMLInputElement;7let simulatedClick = new MouseEvent("click", {8 bubbles: true,9 cancelable: true,10 view: window11}) as MouseEvent;12const config = {13 title: "Browser Extension"14}15function buildMenu(parent: HTMLDivElement, menu: any) {16 menu.forEach((item: menuItemObject) => {17 const div: HTMLDivElement = document.createElement('div');18 div.id = item.name.toLowerCase().replace(/\s/g, '-');19 div.title = item.description;20 div.classList.add('panel-block');21 div.classList.add('is-paddingless');22 const button: HTMLButtonElement = document.createElement('button');23 button.classList.add('button')24 button.classList.add('is-marginless');25 button.classList.add('is-text');26 button.classList.add('is-fullwidth');27 button.innerHTML = `28 <span class="panel-icon" >29 <i class="fas fa-${item.icon}" aria-hidden="true"></i>30 </span><span>${item.name}<span>31 `;32 div.appendChild(button);33 parent.appendChild(div);34 if (typeof item.module === 'string') {35 button.addEventListener('click', () => {36 if (hostname) {37 chrome.tabs.executeScript(null, { file: `scripts/page-actions/${item.module}.js` }, result => {38 const lastErr = chrome.runtime.lastError;39 if (lastErr) console.log('lastError: ' + JSON.stringify(lastErr));40 });41 }42 });43 }44 });45}46buildMenu(panel, menuConfig);47filterInput.addEventListener('input', filterAndUpdateVisibility);48filterInput.addEventListener('change', filterAndUpdateVisibility);49filterInput.addEventListener('keydown', (e: KeyboardEvent) => {50 if (e.keyCode === 13) {51 const chosen = panel.querySelector(`.panel-block .button`) as HTMLButtonElement;52 if (chosen) {53 chosen.dispatchEvent(simulatedClick);54 }55 }56});57function filterAndUpdateVisibility(e: Event) {58 const panelBlocks = Array.from(document.querySelectorAll(`.panel-block:not(.input-container)`)) as HTMLDivElement[];59 console.log(panelBlocks);60 const target = e.target as HTMLInputElement;61 const regex = new RegExp(target.value.toLowerCase(), 'g');62 const filteredPanels = panelBlocks.filter((block: HTMLDivElement) => {63 const idText = block.id.replace('-', ' ');64 const matchesTerm = regex.test(idText.toLowerCase());65 if (!matchesTerm) {66 block.hidden = true;67 } else {68 block.hidden = false;69 }70 return matchesTerm;71 });72 if (filteredPanels.length === 1) {73 if (filteredPanels[0]) {74 filteredPanels[0].focus();75 }76 }...
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!!