Best JavaScript code snippet using storybook-root
VillagerCombobox.js
Source:VillagerCombobox.js
1import { Fragment, h } from 'preact'2import { useCallback, useContext, useEffect, useRef, useState } from 'preact/hooks'3import '../assets/css/villager-combobox.styl'4import { AppContext } from './AppContext'5import useEscapeHandler from './useEscapeHandler'6function Chip({ text, onDelete = () => {}, onClick }) {7 if (typeof onClick === `function`) {8 return (9 <button type="button" className="chip" onClick={onClick}>10 <small>{text}</small>11 </button>12 )13 }14 return (15 <div className="chip">16 <small>{text}</small>17 <button type="button" onClick={() => onDelete(text)}>18 â19 </button>20 </div>21 )22}23function Input({24 placeholder,25 id,26 labelText,27 clearable = false,28 onClear,29 style,30 inputRef,31 readOnly = false,32 readOnlyText,33 readOnlyDelete,34 disabled,35 ...rest36}) {37 const readOnlyStyles = { display: `block` }38 return (39 <Fragment>40 <label htmlFor={id} className={disabled ? `disabled` : ``}>41 <small>{labelText}</small>42 </label>43 <div44 className={[`input-wrapper`, disabled ? `disabled` : ``].join(` `)}45 style={readOnly ? { ...style, ...readOnlyStyles } : style}46 >47 {readOnly ? (48 <Chip text={readOnlyText} onDelete={readOnlyDelete} />49 ) : (50 <input ref={inputRef} type="text" id={id} placeholder={placeholder} disabled={disabled} {...rest} />51 )}52 {clearable ? (53 <button54 type="button"55 className="clear-input"56 aria-label="Clear input"57 onClick={() => {58 onClear?.()59 inputRef.current?.focus()60 }}61 >62 â63 </button>64 ) : null}65 </div>66 </Fragment>67 )68}69export default function VillagerCombobox({70 placeholder,71 id,72 labelText,73 onSelect = () => {},74 multiSelect = false,75 onDeselect = () => {},76 onClearAll = () => {},77 disabled = false,78 filter = () => true,79}) {80 const [inputText, setInputText] = useState(``)81 const [showOptions, setShowOptions] = useState(false)82 const [selectedVillagers, setSelectedVillagers] = useState([])83 const [highlightedIndex, setHighlightedIndex] = useState(-1)84 const [readOnly, setReadOnly] = useState(false)85 const [readOnlyText, setReadOnlyText] = useState(``)86 const { allVillagers } = useContext(AppContext)87 const highlightedRef = useRef()88 const inputRef = useRef()89 const optionsWrapperRef = useRef()90 const comboboxRef = useRef()91 const fuzzyMatcher = new RegExp([...inputText].join(`.*`), `i`)92 const filteredVillagers =93 allVillagers?.filter((villager) => filter(villager) && fuzzyMatcher.test(villager.name)) ?? []94 const handleSelect = (villager) => {95 if (disabled) return96 onSelect(villager)97 if (multiSelect) {98 if (selectedVillagers.includes(villager.id)) {99 const index = selectedVillagers.indexOf(villager.id)100 const newList = [...selectedVillagers]101 newList.splice(index, 1)102 setSelectedVillagers(newList)103 } else {104 setSelectedVillagers([...selectedVillagers, villager.id])105 }106 inputRef.current?.focus()107 } else {108 setReadOnly(true)109 setReadOnlyText(villager.name)110 setShowOptions(false)111 setHighlightedIndex(-1)112 }113 }114 const handleHackyBlur = useCallback((evt) => {115 if (!comboboxRef.current?.contains(evt.target)) {116 setShowOptions(false)117 document.removeEventListener(`click`, handleHackyBlur)118 }119 }, [])120 const handleEscape = useCallback(() => {121 setShowOptions(false)122 }, [])123 useEscapeHandler({124 enabled: showOptions,125 handler: handleEscape,126 })127 useEffect(() => {128 if (showOptions) {129 document.addEventListener(`click`, handleHackyBlur)130 }131 }, [showOptions, handleHackyBlur])132 // FIXME: Find a way to do this where I can have a clear conscience133 useEffect(() => {134 if (!showOptions || !highlightedRef.current) return135 const { scrollTop: parentScrollTop, offsetHeight: parentOffsetHeight } = optionsWrapperRef.current136 const { offsetTop: optionOffsetTop, offsetHeight: optionOffsetHeight } = highlightedRef.current137 if (optionOffsetTop + optionOffsetHeight > parentScrollTop + parentOffsetHeight) {138 highlightedRef.current.scrollIntoView(false)139 } else if (optionOffsetTop < parentScrollTop) {140 highlightedRef.current.scrollIntoView()141 }142 // Disabled exhaustive deps here because this is a hack I hope to one day find a better solution for143 }, [highlightedRef.current, showOptions]) // eslint-disable-line react-hooks/exhaustive-deps144 return (145 <div ref={comboboxRef} className="combobox-wrapper">146 <Input147 inputRef={inputRef}148 id={id}149 placeholder={placeholder}150 labelText={labelText}151 value={inputText}152 disabled={disabled}153 onInput={(evt) => {154 setInputText(evt.target.value)155 if (!showOptions) setShowOptions(true)156 }}157 style={158 showOptions159 ? {160 borderBottomLeftRadius: 0,161 borderBottomRightRadius: 0,162 }163 : undefined164 }165 clearable={inputText.length || showOptions}166 onClear={() => {167 if (showOptions) {168 setShowOptions(false)169 } else {170 setInputText(``)171 }172 }}173 onFocus={(evt) => {174 if (evt.relatedTarget) return175 setShowOptions(true)176 }}177 onClick={() => {178 if (!showOptions) setShowOptions(true)179 }}180 onKeyDown={(evt) => {181 switch (evt.code) {182 case `ArrowDown`:183 setHighlightedIndex((prev) => (prev === filteredVillagers.length - 1 ? 0 : prev + 1))184 break185 case `ArrowUp`:186 setHighlightedIndex((prev) => (prev === 0 ? filteredVillagers.length - 1 : prev - 1))187 break188 case `Enter`:189 handleSelect(filteredVillagers[highlightedIndex])190 break191 }192 }}193 readOnly={readOnly}194 readOnlyText={readOnlyText}195 readOnlyDelete={() => {196 onDeselect()197 setReadOnly(false)198 }}199 />200 {/* Popup */}201 {!disabled && showOptions ? (202 <div ref={optionsWrapperRef} className="options-wrapper">203 <ul className="options-list">204 {filteredVillagers.map((villager, idx) => (205 // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions206 <li207 ref={highlightedIndex === idx ? highlightedRef : undefined}208 key={villager.id}209 className={`option ${selectedVillagers.includes(villager.id) ? `selected` : ``} ${210 highlightedIndex === idx ? `highlighted` : ``211 }`}212 onClick={() => handleSelect(villager)}213 >214 {villager.name}215 </li>216 ))}217 </ul>218 </div>219 ) : null}220 {selectedVillagers.length ? (221 <div className="chip-container">222 <Chip223 text="Clear All"224 onClick={() => {225 onClearAll?.()226 setSelectedVillagers([])227 }}228 />229 {selectedVillagers.map((villagerId) => {230 const villager = allVillagers.find((v) => v.id === villagerId)231 return (232 <Chip233 key={villagerId}234 text={villager.name}235 onDelete={() => {236 onDeselect(allVillagers.find((v) => v.id === villagerId))237 setSelectedVillagers(selectedVillagers.filter((v) => v !== villagerId))238 }}239 />240 )241 })}242 </div>243 ) : null}244 </div>245 )...
Custom.js
Source:Custom.js
1import React from "react";2import { CSSTransition } from "react-transition-group";3// NOTE: element does not follow accessibility guidelines!4const options = [5 "Wade Cooper",6 "Arlene Mccoy",7 "Devon Webb",8 "Tom Cook",9 "Tanya Fox",10 "Hellen Schmidt",11 "Caroline Schultz",12 "Mason Heaney",13 "Claudie Smitham",14 "Emil Schaefer",15];16export default (props) => {17 const node = React.useRef(null);18 const highlightedRef = React.useRef(null);19 const selectedRef = React.useRef(null);20 const listbox = React.useRef(null);21 const [isOpen, setIsOpen] = React.useState(true);22 const [selected, setSelected] = React.useState(options[0])23 const [highlightedId, setHighlightedId] = React.useState(null);24 // to close dropdown on click outside25 const handleClickOutside = (e) => {26 if (!node.current.contains(e.target)) setIsOpen(false);27 };28 // attach click outside handler29 React.useEffect(() => {30 document.addEventListener("mousedown", handleClickOutside);31 return () => {32 document.removeEventListener("mousedown", handleClickOutside);33 };34 }, []);35 React.useEffect(() => {36 isOpen && listbox.current.focus();37 }, [isOpen])38 const handleKeys = (event) => {39 switch (event.key) {40 case "ArrowDown":41 event.preventDefault();42 setIsOpen(true);43 const nextElm =44 highlightedRef.current?.nextElementSibling ||45 listbox.current?.firstElementChild;46 setHighlightedId(nextElm.id);47 nextElm?.scrollIntoView?.({ block: "nearest" });48 highlightedRef.current = nextElm;49 break;50 case "ArrowUp":51 event.preventDefault();52 const prevElm =53 highlightedRef.current?.previousElementSibling ||54 listbox.current?.lastElementChild;55 setHighlightedId(prevElm.id);56 prevElm?.scrollIntoView?.({ block: "nearest" });57 highlightedRef.current = prevElm;58 break;59 case "Space":60 case "Enter":61 event.preventDefault();62 setSelected(highlightedRef.current.dataset.value);63 setTimeout(setIsOpen, 100, false);64 break;65 case "Escape":66 event.preventDefault();67 setIsOpen(false);68 break;69 }70 }71 return (72 <div className="w-full max-w-xs mx-auto" ref={node}>73 <div>74 <label75 id="listbox-label"76 className="block text-sm font-medium text-gray-700"77 >78 Assigned to79 </label>80 <div className="mt-1 relative">81 <button82 onClick={(e) => {83 setIsOpen(!isOpen);84 }}85 type="button"86 aria-haspopup="listbox"87 aria-expanded={!!isOpen}88 aria-labelledby="listbox-label"89 className="bg-white relative w-full border border-gray-300 rounded-md shadow-sm ltr:pl-3 rtl:pr-3 ltr:pr-10 rtl:pl-10 py-2 ltr:text-left rtl:text-right focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"90 >91 <span className="block truncate">{selected}</span>92 <span className="absolute inset-y-0 ltr:right-0 rtl:left-0 flex items-center ltr:pr-2 rtl:pl-2 pointer-events-none">93 {/* <!-- Heroicon name: selector --> */}94 <svg95 className="h-5 w-5 text-gray-400"96 xmlns="http://www.w3.org/2000/svg"97 viewBox="0 0 20 20"98 fill="currentColor"99 aria-hidden="true"100 >101 <path102 fillRule="evenodd"103 d="M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z"104 clipRule="evenodd"105 />106 </svg>107 </span>108 </button>109 <CSSTransition110 in={isOpen}111 timeout={{112 exit: 75,113 }}114 classNames={{115 exit: "transition ease-in duration-100",116 exitActive: "transform opacity-0",117 exitDone: "hidden",118 }}119 >120 <div121 className={`${122 isOpen ? "block" : "hidden"123 } absolute mt-1 w-full rounded-md bg-white shadow-lg`}124 >125 <ul126 ref={listbox}127 onKeyDown={handleKeys}128 tabIndex="0"129 role="listbox"130 aria-labelledby="listbox-label"131 aria-activedescendant={highlightedId}132 onClick={() => setIsOpen(true)}133 className="max-h-60 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm"134 >135 {options.map((option, i) => {136 const id = `listbox-option-${i}`;137 const isSelected = selected === option;138 const isHighlighted = highlightedId === id;139 return (140 <li141 key={i + " " + option}142 onMouseEnter={(e) => {143 setHighlightedId(id);144 highlightedRef.current =145 e.currentTarget;146 }}147 onClick={() => {148 setSelected(option);149 setTimeout(setIsOpen, 250, false);150 }}151 id={id}152 data-value={option}153 role="option"154 className={`${155 isHighlighted ? "text-white bg-indigo-600" : "text-gray-900"156 } cursor-default select-none relative py-2 ltr:pl-3 rtl:pr-3 ltr:pr-9 rtl:pl-9`}157 >158 {/* <!-- Selected: "font-semibold", Not Selected: "font-normal" --> */}159 <span160 className={`${isSelected ? "font-semibold" : "font-normal"} block truncate`}161 >162 {option}163 </span>164 {isSelected && (165 <span166 className={`${167 isHighlighted ? "text-white" : "text-indigo-600"168 } absolute inset-y-0 ltr:right-0 rtl:left-0 flex items-center ltr:pr-4 rtl:pl-4`}169 >170 {/* <!-- Heroicon name: check --> */}171 <svg172 className="h-5 w-5"173 xmlns="http://www.w3.org/2000/svg"174 viewBox="0 0 20 20"175 fill="currentColor"176 aria-hidden="true"177 >178 <path179 fillRule="evenodd"180 d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"181 clipRule="evenodd"182 />183 </svg>184 </span>185 )}186 </li>187 );188 })}189 </ul>190 </div>191 </CSSTransition>192 </div>193 </div>194 </div>195 );...
CommentBox.js
Source:CommentBox.js
1import React, { Component } from 'react';2import Comment from '../Comment/Comment';3import List from '@material-ui/core/List';4import ListItem from '@material-ui/core/ListItem';5import ListItemIcon from '@material-ui/core/ListItemIcon';6import ListItemText from '@material-ui/core/ListItemText';7import Grid from '@material-ui/core/Grid';8import CommentReplyField from '../CommentReplyField/CommentReplyField';9export default class CommentBox extends Component {10 constructor(props) {11 super(props);12 this.state = {13 highlightedComment: null,14 replyTo: null,15 };16 this.highlightedRef = null;17 }18 highlightComment = commentId => {19 const highlightedRef = React.createRef();20 this.props.comments.filter(comment => comment.id === commentId)[0].ref = highlightedRef;21 this.setState({ highlightedComment: commentId });22 this.highlightedRef = highlightedRef;23 // TODO: Make selection disappear24 };25 componentDidUpdate() {26 this.highlightedRef?.current?.scrollIntoView({27 behavior: 'smooth',28 block: 'start',29 });30 this.highlightedRef = null;31 }32 cancelReplyTo = () => {33 this.setState({ replyTo: null });34 };35 onCommentSent = () => {36 this.cancelReplyTo();37 this.props.onCommentsUpdate();38 };39 render() {40 return (41 <Grid container direction="column">42 {this.props.isAuthenticated ? (43 <Grid item container>44 <CommentReplyField45 postId={this.props.postId}46 replyTo={this.state.replyTo}47 cancelReplyTo={this.cancelReplyTo}48 onCommentSent={this.onCommentSent}49 />50 </Grid>51 ) : null}52 <Grid item>53 <List // TODO: Move this list into its own component (like CommentList) ?54 component="nav"55 aria-label="aria-label"56 style={{57 width: '100%',58 position: 'relative',59 //overflow: 'auto',60 maxHeight: 300,61 }}62 >63 {this.props.comments.map(comment => (64 <div key={comment.id}>65 <hr ref={comment.ref} />66 <Comment67 comment={comment}68 selected={this.state.highlightedComment === comment.id}69 highlightComment={this.highlightComment}70 onAuthorNameClick={comment => this.setState({ replyTo: comment })}71 onUpdate={this.props.onCommentsUpdate}72 />73 </div>74 ))}75 </List>76 </Grid>77 </Grid>78 );79 }...
Using AI Code Generation
1import { highlightedRef } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('Button', module)4 .add('with text', () => (5 <button onClick={highlightedRef}>Hello Button</button>6import { useRef } from 'react';7export const highlightedRef = () => {8 const ref = useRef();9 console.log(ref);10}11import { highlightedRef } from '../storybook-root';12export const parameters = {13 actions: { argTypesRegex: "^on[A-Z].*" },14 refs: {15 button: {16 }17 }18};
Using AI Code Generation
1import { highlightedRef } from 'storybook-root'2export default class Test extends Component {3 render() {4 return (5 <Text ref={highlightedRef('test')} />6 }7}8import { testId } from 'storybook-root'9describe('test', () => {10 it('should render', () => {11 const { toJSON } = render(<Test />)12 expect(toJSON()).toMatchSnapshot()13 })14 it('should be highlighted', () => {15 const { getByTestId } = render(<Test />)16 const test = getByTestId('test')17 expect(test).toBeHighlighted()18 })19})20import { testId } from 'storybook-root'21describe('test', () => {22 it('should render', () => {23 const { toJSON } = render(<Test />)24 expect(toJSON()).toMatchSnapshot()25 })26 it('should be highlighted', () => {27 const { getByTestId } = render(<Test />)28 const test = getByTestId('test')29 expect(test).toBeHighlighted()30 })31})32import { testId } from 'storybook-root'33describe('test', () => {34 it('should render', () => {35 const { toJSON } = render(<Test />)36 expect(toJSON()).toMatchSnapshot()37 })38 it('should be highlighted', () => {39 const { getByTestId } = render(<Test />)40 const test = getByTestId('test')41 expect(test).toBeHighlighted()42 })43})44import { testId } from 'storybook-root'45describe('test', () => {46 it('should render', () => {47 const { toJSON } = render(<Test />)48 expect(toJSON()).toMatchSnapshot()49 })50 it('should be highlighted', () => {51 const { getByTestId } = render(<Test />)52 const test = getByTestId('test')53 expect(test).toBeHighlighted()54 })55})56import { testId } from 'storybook-root'
Using AI Code Generation
1import { highlightedRef } from 'storybook-root-provider';2const ref = highlightedRef();3import { highlightedComponent } from 'storybook-root-provider';4const component = highlightedComponent();5import { highlightedComponentRef } from 'storybook-root-provider';6const componentRef = highlightedComponentRef();7import { highlightedComponentName } from 'storybook-root-provider';8const componentName = highlightedComponentName();9import { highlightedComponentDisplayName } from 'storybook-root-provider';10const componentDisplayName = highlightedComponentDisplayName();11import { highlightedComponentType } from 'storybook-root-provider';12const componentType = highlightedComponentType();13import { highlightedComponentPath } from 'storybook-root-provider';14const componentPath = highlightedComponentPath();15import { highlightedComponentProps } from 'storybook-root-provider';16const componentProps = highlightedComponentProps();17import { highlightedComponentState } from 'storybook-root-provider';18const componentState = highlightedComponentState();19import { highlightedComponentContext } from 'storybook-root-provider';20const componentContext = highlightedComponentContext();21import { highlightedComponentChildren } from 'storybook-root-provider';22const componentChildren = highlightedComponentChildren();23import { highlightedComponentParent } from 'storybook-root-provider';
Using AI Code Generation
1const { highlightedRef } = require('storybook-root');2const { highlight } = highlightedRef();3highlight();4const { highlightedRef } = require('storybook-root');5const { highlight } = highlightedRef();6highlight();7const { highlightedRef } = require('storybook-root');8const { highlight } = highlightedRef();9highlight();10const { highlightedRef } = require('storybook-root');11const { highlight } = highlightedRef();12highlight();13const { highlightedRef } = require('storybook-root');14const { highlight } = highlightedRef();15highlight();16const { highlightedRef } = require('storybook-root');17const { highlight } = highlightedRef();18highlight();19const { highlightedRef } = require('storybook-root');20const { highlight } = highlightedRef();21highlight();22const { highlightedRef } = require('storybook-root');23const { highlight } = highlightedRef();24highlight();25const { highlightedRef } = require('storybook-root');26const { highlight } = highlightedRef();27highlight();28const { highlightedRef } = require('storybook-root');29const { highlight } = highlightedRef();30highlight();31const { highlightedRef } = require('storybook-root');32const { highlight } = highlightedRef();33highlight();34const { highlightedRef } = require('storybook-root');35const { highlight } = highlightedRef();36highlight();
Using AI Code Generation
1import { highlightedRef } from 'storybook-root';2const ref = highlightedRef();3import { highlightedRef } from 'storybook-react';4const ref = highlightedRef();5import { highlightedRef } from 'storybook-vue';6const ref = highlightedRef();7import { highlightedRef } from 'storybook-angular';8const ref = highlightedRef();9import { highlightedRef } from 'storybook-svelte';10const ref = highlightedRef();11import { highlightedRef } from 'storybook-html';12const ref = highlightedRef();13import { highlightedRef } from 'storybook-marko';14const ref = highlightedRef();15import { highlightedRef } from 'storybook-markojs';16const ref = highlightedRef();17import { highlightedRef } from 'storybook-preact';18const ref = highlightedRef();19import { highlightedRef } from 'storybook-riot';20const ref = highlightedRef();
Using AI Code Generation
1import { highlightedRef } from "storybook-root";2const element = highlightedRef();3const { x, y } = element.getBoundingClientRect();4const domElement = document.elementFromPoint(x, y);5const value = domElement.getAttribute("data-automation-id");6console.log(value);
Using AI Code Generation
1const storybookRoot = require("storybook-root");2const assert = require("assert");3const { By } = require("selenium-webdriver");4describe("Test Storybook", function() {5 it("should return the text of the highlighted element", async function() {6 .highlightedRef("Button")7 .then(ref => ref.getText());8 assert.equal(text, "Hello World!");9 });10});11const { By } = require("selenium-webdriver");12const highlightedRef = async function(storyName) {13 const highlightedElement = await driver.findElement(14 By.css(`[data-name="${storyName}"]`)15 );16 return highlightedElement;17};18module.exports = {19};20exports.config = {21 {22 }23 mochaOpts: {
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!!