Best JavaScript code snippet using storybook-root
Treeview.js
Source:Treeview.js
1import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';2import PropTypes from 'prop-types';3import classNames from 'classnames';4import React, { useEffect, useRef, useState } from 'react';5import { Collapse } from 'react-bootstrap';67const TreeviewListItem = ({8 item,9 openedItems,10 setOpenedItems,11 selectedItems,12 setSelectedItems,13 selection14}) => {15 const [open, setOpen] = useState(openedItems.indexOf(item.id) !== -1);16 const [children, setChildren] = useState([]);17 const [firstChildren, setFirstChildren] = useState([]);18 const [childrenOpen, setChildrenOpen] = useState(false);19 const checkRef = useRef();2021 const getChildrens = item => {22 function flatInnter(item) {23 let flat = [];24 item.map(child => {25 if (child.children) {26 flat = [...flat, child.id, ...flatInnter(child.children)];27 } else {28 flat = [...flat, child.id];29 }30 });3132 return flat;33 }34 if (item.children) {35 return flatInnter(item.children);36 } else {37 return [];38 }39 };4041 const isChildrenOpen = () => {42 return openedItems.some(item => firstChildren.indexOf(item) !== -1);43 };4445 const handleOnExiting = () => {46 setOpenedItems(openedItems.filter(openedItem => openedItem !== item.id));47 };48 const handleEntering = () => {49 setOpenedItems([...openedItems, item.id]);50 };5152 const handleSingleCheckboxChange = e => {53 if (e.target.checked) {54 setSelectedItems([...selectedItems, item.id]);55 } else {56 setSelectedItems(57 selectedItems.filter(selectedItem => selectedItem !== item.id)58 );59 }60 };6162 const handleParentCheckboxChange = e => {63 const filteredItems = selectedItems.filter(64 selectedItem => children.indexOf(selectedItem) === -165 );66 if (e.target.checked) {67 setSelectedItems([...filteredItems, ...children]);68 } else {69 setSelectedItems(filteredItems);70 }71 };7273 useEffect(() => {74 setChildren(getChildrens(item));75 if (item.children) {76 setFirstChildren(item.children.map(child => child.id));77 }78 }, []);7980 useEffect(() => {81 setChildrenOpen(isChildrenOpen());82 }, [children, openedItems]);8384 useEffect(() => {85 const childrenSelected = selectedItems.some(86 selectedItem => children.indexOf(selectedItem) !== -187 );88 const allChildrenSelected = children.every(89 child => selectedItems.indexOf(child) !== -190 );91 if (childrenSelected && checkRef.current) {92 checkRef.current.indeterminate = true;93 }94 if (!childrenSelected && checkRef.current) {95 checkRef.current.indeterminate = false;96 }97 if (allChildrenSelected && checkRef.current) {98 checkRef.current.indeterminate = false;99 checkRef.current.checked = true;100 }101 if (!allChildrenSelected && checkRef.current) {102 checkRef.current.checked = false;103 }104 }, [selectedItems, checkRef.current]);105106 return (107 <li className="treeview-list-item">108 {Object.prototype.hasOwnProperty.call(item, 'children') ? (109 <>110 <div className="toggle-container">111 {selection && (112 <input113 type="checkbox"114 className="form-check-input"115 onChange={handleParentCheckboxChange}116 ref={checkRef}117 />118 )}119 <a120 className={classNames('collapse-toggle', {121 collapsed: open || item.expanded122 })}123 href="#!"124 onClick={() => setOpen(!open)}125 >126 <p127 className={classNames('treeview-text', { 'ms-2': !selection })}128 >129 {item.name}130 </p>131 </a>132 </div>133 <Collapse134 in={open}135 onExiting={handleOnExiting}136 onEntering={handleEntering}137 >138 <ul139 className={classNames('treeview-list', {140 'collapse-hidden': !open,141 'collapse-show treeview-border': open,142 'treeview-border-transparent': childrenOpen143 })}144 >145 {item.children.map((nestedItem, index) => (146 <TreeviewListItem147 key={index}148 item={nestedItem}149 index={index}150 openedItems={openedItems}151 setOpenedItems={setOpenedItems}152 selectedItems={selectedItems}153 setSelectedItems={setSelectedItems}154 selection={selection}155 />156 ))}157 </ul>158 </Collapse>159 </>160 ) : (161 <div className="treeview-item">162 {selection && (163 <input164 type="checkbox"165 className="form-check-input"166 onChange={handleSingleCheckboxChange}167 checked={selectedItems.indexOf(item.id) !== -1}168 />169 )}170 <a href="#!" className="flex-1">171 <p className="treeview-text">172 <FontAwesomeIcon173 icon={item.icon}174 className={classNames('me-2', item.iconClass)}175 />176 {item.name}177 </p>178 </a>179 </div>180 )}181 </li>182 );183};184185const Treeview = ({186 data,187 selection,188 expanded = [],189 selectedItems = [],190 setSelectedItems191}) => {192 const [openedItems, setOpenedItems] = useState(expanded);193194 return (195 <ul className="treeview treeview-select">196 {data.map((treeviewItem, index) => (197 <TreeviewListItem198 key={index}199 item={treeviewItem}200 openedItems={openedItems}201 setOpenedItems={setOpenedItems}202 selectedItems={selectedItems}203 setSelectedItems={setSelectedItems}204 selection={selection}205 />206 ))}207 </ul>208 );209};210211TreeviewListItem.propTypes = {212 item: PropTypes.object,213 openedItems: PropTypes.array,214 setOpenedItems: PropTypes.func,215 selectedItems: PropTypes.array,216 setSelectedItems: PropTypes.func,217 selection: PropTypes.bool218};219220Treeview.propTypes = {221 data: PropTypes.array.isRequired,222 selection: PropTypes.bool, // If true selection is enabled.223 expanded: PropTypes.array, // Default expanded children ids.224 selectedItems: PropTypes.array, // Selected item ids..225 setSelectedItems: PropTypes.func // Setter to select items226};227
...
button.component.ts
Source:button.component.ts
1import { Component, ElementRef, HostBinding, Input, OnInit, Renderer2, ViewChild } from '@angular/core';2import { FormGroup, NgForm } from '@angular/forms';3@Component({4 selector: 'app-button',5 templateUrl: './button.component.html',6 styleUrls: ['./button.component.scss'],7})8export class ButtonComponent implements OnInit {9 @Input() disabled = false;10 @Input() text = 'Submit';11 @Input() color = 'primary';12 @Input() errorColor = 'danger';13 @Input() form: NgForm;14 width: number;15 height: number;16 textRef: ElementRef;17 buttonRef: ElementRef;18 spinnerRef: ElementRef;19 checkRef: ElementRef;20 originalDisabled = false;21 constructor(private renderer: Renderer2) {}22 @ViewChild('textViewChild')23 set textViewChild(textRef: ElementRef) {24 this.textRef = textRef;25 }26 @ViewChild('buttonViewChild')27 set buttonViewChild(buttonRef: ElementRef) {28 this.buttonRef = buttonRef;29 this.width = buttonRef.nativeElement.offsetWidth;30 this.height = buttonRef.nativeElement.offsetHeight;31 this.renderer.addClass(buttonRef.nativeElement, `btn-${this.color}`);32 }33 @ViewChild('spinnerViewChild')34 set spinnerViewChild(spinnerRef: ElementRef) {35 this.spinnerRef = spinnerRef;36 }37 @ViewChild('checkViewChild')38 set checkViewChild(checkRef: ElementRef) {39 this.checkRef = checkRef;40 }41 ngOnInit(): void {42 this.originalDisabled = this.disabled;43 }44 click(): void {45 this.textRef.nativeElement.style.display = 'none';46 this.buttonRef.nativeElement.style.width = `${this.width}px`;47 this.buttonRef.nativeElement.style.height = `${this.height}px`;48 this.spinnerRef.nativeElement.style.display = 'inline';49 this.spinnerRef.nativeElement.style.width = `${this.height * 0.5}px`;50 this.spinnerRef.nativeElement.style.height = `${this.height * 0.5}px`;51 this.disabled = true;52 this.form.ngSubmit.emit();53 }54 reset(error = false): void {55 if (error) {56 this.renderer.addClass(this.checkRef.nativeElement, 'fa-times');57 this.renderer.addClass(this.checkRef.nativeElement, 'text-danger');58 this.checkRef.nativeElement.style.display = 'inline';59 } else {60 this.renderer.addClass(this.checkRef.nativeElement, 'fa-check');61 this.checkRef.nativeElement.style.display = 'inline';62 }63 this.spinnerRef.nativeElement.style.display = 'none';64 setTimeout(() => {65 this.checkRef.nativeElement.style.display = 'none';66 this.textRef.nativeElement.style.display = 'inline';67 this.renderer.removeClass(this.checkRef.nativeElement, 'fa-times');68 this.renderer.removeClass(this.checkRef.nativeElement, 'fa-check');69 this.renderer.removeClass(this.checkRef.nativeElement, 'text-danger');70 this.disabled = this.originalDisabled;71 }, 1000);72 }...
Navbar.js
Source:Navbar.js
1import React, {useRef, useEffect} from 'react';2import './Navbar.css';3import Menu from "../Menu/Menu";4function Navbar({home, menu, sticky}) {5 const checkRef = useRef(null);6 const navRef = useRef(null);7 useEffect(() => {8 document.addEventListener('mousedown', (event) => {9 if (navRef.current && !navRef.current.contains(event.target)) {10 checkRef.current.checked = false;11 }12 })13 }, [])14 return(15 <div className={"navbar"} ref={navRef} style={sticky ? {position: "sticky"}: {}}>16 <label htmlFor={"toogle"} className={"hamburguer item"}>17 ☰18 </label>19 <input className={"navbar-input"} type={"checkbox"} id={"toogle"} ref={checkRef}/>20 <Menu home={home} menu={menu} onClick={() => {21 checkRef.current.checked = false;22 }}/>23 </div>24 );25}...
Using AI Code Generation
1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import Button from './Button';5storiesOf('Button')6 .add('with text', () => (7 <Button onClick={action('clicked')}>Hello Button</Button>8 .add('with some emoji', () => (9 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>10 ));11import { configure, addDecorator } from '@storybook/react';12import { checkRef } from 'storybook-root-decorator';13addDecorator(checkRef);14configure(require.context('../src', true, /\.stories\.js$/), module);15module.exports = (baseConfig, env, defaultConfig) => {16 const config = defaultConfig;17 config.module.rules.push({18 options: {19 presets: [['env', { modules: false }], 'react'],20 },21 });22 return config;23};
Using AI Code Generation
1import { checkRef } from 'storybook-root-decorator';2import React from 'react';3import { mount } from 'enzyme';4class Test extends React.Component {5 render() {6 return (7 );8 }9}10const wrapper = mount(<Test />);11checkRef(wrapper, 'test');12checkRef(wrapper, 'test', 'myTest');13checkRef(wrapper, 'test', 'myTest', 'div');14checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test');15checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true);16checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true);17checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true, true);18checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true, true, true);19checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true, true, true, true);20checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true, true, true, true, true);21checkRef(wrapper, 'test', 'myTest', 'div', 'this is a test', true, true, true, true, true, true, true);
Using AI Code Generation
1const storybookRoot = require('storybook-root');2const path = require('path');3const componentPath = path.resolve(__dirname, 'src/components/MyComponent');4const refPath = path.resolve(__dirname, 'src/components/MyComponent/ref');5storybookRoot.checkRef(componentPath, refPath);6import React from 'react';7import MyComponent from '../MyComponent';8export default {9};10export const myComponent = () => <MyComponent />;
Using AI Code Generation
1import { checkRef } from 'storybook-root';2const checkRef = require('storybook-root').checkRef;3const checkRef = (ref) => {4 console.log('checkRef called');5 return true;6};7export { checkRef };8const checkRef = require('storybook-root').checkRef;9describe('checkRef', () => {10 it('should be called', () => {11 const spy = jest.spyOn(storybookRoot, 'checkRef');12 storybookRoot.checkRef();13 expect(spy).toHaveBeenCalled();14 });15});16jest.mock('storybook-root', () => ({17 checkRef: jest.fn()18}));19jest.mock('storybook-root', () => ({20 checkRef: jest.fn().mockImplementation(() => true)21}));22jest.mock('module', () => ({23 function: jest.fn()24}));25jest.mock('module', () => ({26 function: jest.fn().mockImplementation(() => true)27}));28I am using jest version 25.1.0. Can anyone help me to mock the function that is imported in the test file?29jest.mock('module', () => ({30 function: jest.fn()31}));32jest.mock('module', () => ({33 function: jest.fn().mockImplementation(()
Using AI Code Generation
1import { checkRef } from 'storybook-root';2const result = checkRef('test-ref');3console.log(result);4import { checkRef } from 'storybook-root';5const result = checkRef('test-ref');6console.log(result);7import { checkRef } from 'storybook-root';8const result = checkRef('test-ref');9console.log(result);10import { checkRef } from 'storybook-root';11const result = checkRef('test-ref');12console.log(result);13import { checkRef } from 'storybook-root';14const result = checkRef('test-ref');15console.log(result);16import { checkRef } from 'storybook-root';17const result = checkRef('test-ref');18console.log(result);19import { checkRef } from 'storybook-root';20const result = checkRef('test-ref');21console.log(result);22import { checkRef } from 'storybook-root';23const result = checkRef('test-ref');24console.log(result);25import { checkRef } from 'storybook-root';26const result = checkRef('test-ref');27console.log(result);28import { checkRef } from 'storybook-root';29const result = checkRef('test-ref');30console.log(result);31import { checkRef } from 'storybook-root';32const result = checkRef('test-ref');33console.log(result);
Using AI Code Generation
1import {checkRef} from 'storybook-root';2checkRef(this);3import {checkRef} from 'storybook-root';4checkRef(this);5import {checkRef} from 'storybook-root';6checkRef(this);7import {checkRef} from 'storybook-root';8checkRef(this);9import {checkRef} from 'storybook-root';10checkRef(this);11import {checkRef} from 'storybook-root';12checkRef(this);13import {checkRef} from 'storybook-root';14checkRef(this);15import {checkRef} from 'storybook-root';16checkRef(this);17import {checkRef} from 'storybook-root';18checkRef(this);19import {checkRef} from 'storybook-root';20checkRef(this);
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!!