Best JavaScript code snippet using playwright-internal
_internal_select.js
Source:_internal_select.js
1// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2/* tslint:disable */3/* eslint-disable */4import React, {5 createContext,6 useContext,7 useRef,8 useState,9 useLayoutEffect,10 useMemo,11 useEffect,12} from "react";13import {14 ListLayout,15 mergeProps,16 HiddenSelect,17 useSelectState,18 useSelect,19 useButton,20 useListBox,21 useOption,22 useFocusRing,23 Virtualizer,24 VirtualizerItem,25 DismissButton,26} from "@visly/core";27import { combineRef, exists, renderChildren } from "./_internal_utils";28import { usePrimitive } from "./_internal_usePrimitive";29import { Popover } from "./builtins/Popover";30import { ItemContext, renderCollection } from "./_internal_collection";31import { useFormLabel } from "./_internal_formlabel";32import { injectSpacing } from "./_internal_component_utils";33export const SelectContext = createContext({34 triggerProps: {},35 triggerRef: null,36 buttonStyles: {},37 testId: "",38 vislyProps: {},39 menuProps: {},40 state: null,41 layout: null,42 renderInline: false,43 rootClassName: "",44 triggerMeasureRef: null,45});46export function SelectButton(props) {47 const {48 triggerRef,49 triggerMeasureRef,50 vislyProps,51 testId,52 buttonStyles,53 triggerProps,54 } = useContext(SelectContext);55 const _triggerProps = mergeProps(triggerProps, {56 onKeyDown: (e) => {57 if (e.key === "Escape") {58 e.continuePropagation();59 }60 },61 });62 const { buttonProps } = useButton(_triggerProps, triggerRef);63 return (64 <button65 {...mergeProps(buttonProps, vislyProps)}66 data-testid={testId}67 ref={combineRef(68 combineRef(props.measureRef, triggerMeasureRef),69 triggerRef70 )}71 className={props.className}72 style={buttonStyles}73 >74 {props.children}75 </button>76 );77}78export function SelectOptionContainer(props) {79 const { state, renderInline } = useContext(SelectContext);80 return state.isOpen || renderInline ? (81 <_SelectOptionContainer {...props} />82 ) : null;83}84function useListBoxLayout(state, minimumItemHeight) {85 const layout = useMemo(86 () =>87 new ListLayout({88 estimatedRowHeight: exists(minimumItemHeight) ? minimumItemHeight : 20,89 padding: 0,90 }),91 [minimumItemHeight]92 );93 layout.collection = state.collection;94 layout.disabledKeys = state.disabledKeys;95 return layout;96}97function _SelectOptionContainer(props) {98 const {99 menuProps,100 state,101 layout,102 renderInline,103 triggerRef,104 rootClassName,105 } = useContext(SelectContext);106 const listboxRef = useRef(null);107 const { listBoxProps } = useListBox(108 {109 ...menuProps,110 autoFocus: true,111 disallowEmptySelection: true,112 "aria-label": exists(state.selectedKey) ? state.selectedKey : "none",113 id: menuProps.id,114 isVirtualized: true,115 keyboardDelegate: layout,116 },117 state,118 listboxRef119 );120 const [buttonWidth, setButtonWidth] = useState(null);121 useLayoutEffect(() => {122 if (exists(triggerRef)) {123 const width = triggerRef.current.offsetWidth;124 setButtonWidth(width);125 }126 }, [triggerRef, state.selectedKey]);127 const renderWrapper = (parent, reusableView) => {128 return (129 <VirtualizerItem130 key={reusableView.key}131 reusableView={reusableView}132 parent={parent}133 />134 );135 };136 if (renderInline) {137 const selectOptions = Array.isArray(props.children)138 ? props.children.find((p) => p.type === React.Fragment)139 : props.children;140 return (141 <ul142 ref={combineRef(listboxRef, props.measureRef)}143 className={props.className}144 >145 <ItemContext.Provider146 value={{147 isSelected: false,148 isFocused: false,149 key: null,150 }}151 >152 {injectSpacing(props.addSpacing, selectOptions)}153 </ItemContext.Provider>154 </ul>155 );156 }157 const firstKey = state.collection.firstKey;158 return (159 <Popover160 scrollRef={listboxRef}161 triggerRef={triggerRef}162 isOpen={state.isOpen}163 containFocus164 onShouldClose={state.close}165 placement="bottom start"166 >167 <DismissButton onDismiss={() => state.close()} />168 <div key={props.innerKey} className={rootClassName}>169 {exists(props.cssStyles) ? (170 <style171 style={{172 display: "none",173 }}174 >175 {props.cssStyles}176 </style>177 ) : null}178 <Virtualizer179 {...mergeProps(listBoxProps, menuProps)}180 ref={listboxRef}181 layout={layout}182 collection={state.collection}183 sizeToFit="height"184 scrollDirection="vertical"185 renderWrapper={renderWrapper}186 focusedKey={state.selectionManager.focusedKey}187 className={props.className}188 style={{189 overflow: "auto",190 ...(props.useButtonWidth191 ? {192 width: buttonWidth,193 }194 : {}),195 padding: undefined,196 }}197 >198 {(_type, item) => {199 const showDivider = props.addSpacing && item.key !== firstKey;200 return (201 <>202 {showDivider && (203 <div204 className="__visly_spacing"205 key={`__visly_spacing-${item.key}`}206 />207 )}208 <Option key={item.key} item={item} />209 </>210 );211 }}212 </Virtualizer>213 </div>214 <DismissButton onDismiss={() => state.close()} />215 </Popover>216 );217}218function Option({ item }) {219 const { state } = useContext(SelectContext);220 const ref = useRef();221 const isDisabled = state.disabledKeys.has(item.key);222 const isSelected = state.selectionManager.isSelected(item.key);223 const { optionProps } = useOption(224 {225 key: item.key,226 isDisabled,227 isSelected,228 shouldSelectOnPressUp: true,229 shouldFocusOnHover: true,230 "aria-label": item.key,231 isVirtualized: true,232 },233 state,234 ref235 );236 const { focusProps, isFocusVisible } = useFocusRing();237 return (238 <li239 {...mergeProps(optionProps, focusProps)}240 ref={ref}241 style={{242 outline: "none",243 }}244 >245 <ItemContext.Provider246 value={{247 isSelected,248 isFocused: isFocusVisible,249 key: item.key,250 }}251 >252 {item.rendered}253 </ItemContext.Provider>254 </li>255 );256}257export function SelectRoot(props) {258 const ref = useRef(null);259 const {260 selectedKey,261 onSelectionChange,262 renderInline,263 children,264 minimumItemHeight,265 disabledKeys,266 } = props;267 const { style, testId, values, vislyProps, isDisabled } = usePrimitive({268 ref,269 props,270 });271 const { className, ...other } = vislyProps;272 const { label, registerLabelProps } = useFormLabel();273 const state = useSelectState({274 children: renderCollection(children),275 selectedKey,276 onSelectionChange,277 disallowEmptySelection: true,278 shouldFlip: true,279 label,280 isDisabled,281 disabledKeys,282 });283 const layout = useListBoxLayout(state, minimumItemHeight);284 const { triggerProps, menuProps, labelProps } = useSelect(285 {286 children: renderCollection(children),287 selectedKey,288 onSelectionChange,289 shouldFlip: true,290 keyboardDelegate: layout,291 label,292 disabledKeys,293 "aria-describedby": props["aria-describedby"],294 "aria-details": props["aria-details"],295 "aria-label": props["aria-label"],296 "aria-labelledby": props["aria-labelledby"],297 },298 state,299 ref300 );301 useEffect(() => {302 registerLabelProps(labelProps);303 }, []);304 triggerProps.isDisabled = isDisabled;305 return (306 <div307 className={className}308 style={{ ...style, display: renderInline ? "flex" : "contents" }}309 >310 <HiddenSelect311 state={state}312 triggerRef={ref}313 label={label || "Select"}314 name="Select"315 />316 <SelectContext.Provider317 value={{318 buttonStyles: style,319 renderInline,320 triggerProps,321 triggerRef: ref,322 triggerMeasureRef: props.measureRef,323 vislyProps: other,324 testId,325 state,326 layout,327 menuProps,328 rootClassName: className,329 }}330 >331 {renderChildren(props.vislyChildren, values)}332 </SelectContext.Provider>333 </div>334 );335}336export function SelectOptionRoot(props) {337 const ref = useRef();338 const { isSelected, isFocused } = useContext(ItemContext) || {};339 const { style, testId, innerRef, values, vislyProps } = usePrimitive({340 ignoreFocusHandling: true,341 isFocusVisible: isFocused,342 ref,343 props,344 variants: isSelected345 ? [346 {347 propName: "selected",348 },349 ]350 : [],351 });352 return (353 <div354 key={props.value}355 ref={combineRef(props.measureRef, combineRef(innerRef, ref))}356 data-testid={testId}357 {...vislyProps}358 style={style}359 >360 {renderChildren(props.children, values)}361 </div>362 );...
Popdown.js
Source:Popdown.js
1import React, { useState, useEffect } from 'react';2import isBoolean from 'lodash/isBoolean';3import contains from 'dom-helpers/query/contains';4import PropTypes from 'prop-types';5import DropdownButton from '../DropdownButton';6import Popper from '../Popper';7import {8 getNextFocusable,9 getLastFocusable,10 getFirstFocusable11} from '../../util/getFocusableElements';12import composeEventHandlers from '../../util/composeEventHandlers';13const DefaultTrigger = ({ getTriggerProps, buttonProps, label }) => (14 <DropdownButton15 {...getTriggerProps()}16 {...buttonProps}17 >18 {label}19 </DropdownButton>20);21DefaultTrigger.propTypes = {22 buttonProps: PropTypes.object,23 getTriggerProps: PropTypes.func,24 label: PropTypes.node,25};26const defaultFocusHandlers = {27 open: (trigger, menu, firstItem) => {28 if (firstItem) firstItem.focus();29 },30 close: (trigger, menu) => {31 if (contains(menu, document.activeElement)) {32 trigger.focus();33 }34 }35};36const Popdown = ({37 buttonProps,38 children,39 disabled,40 focusHandlers,41 label,42 id,43 menuKeyHandler,44 modifiers,45 onToggle,46 open: openProp,47 overlayRef: overlayRefProp,48 placement,49 renderMenu,50 renderTrigger,51 triggerKeyHandler,52 triggerRef: triggerRefProp,53 usePortal,54}) => {55 const [open, setOpen] = useState(false);56 const [keyCode, setKeyCode] = useState();57 const triggerRef = triggerRefProp || React.createRef();58 const overlayRef = overlayRefProp || React.createRef();59 let focusTimeoutId;60 const _focusHandlers = Object.assign({}, Popdown.defaultProps.focusHandlers, focusHandlers);61 useEffect(() => {62 if (open) {63 if (overlayRef.current && triggerRef.current) {64 const menu = overlayRef.current.node || overlayRef.current;65 let elem;66 if (keyCode === null || keyCode === 40) { // down arrow67 elem = getNextFocusable(menu, true, true);68 }69 if (keyCode === 38) {70 elem = getLastFocusable(menu);71 }72 if (document.activeElement === triggerRef.current) {73 _focusHandlers.open(triggerRef.current, menu, elem);74 }75 }76 }77 }, [open, overlayRef, triggerRef, _focusHandlers, keyCode]);78 if (isBoolean(openProp) && openProp !== open) {79 setOpen(openProp);80 if (!onToggle) {81 console.warn('Popdown - You set a boolean for the \'open\' prop, but failed to provide an \'onToggle\' handler');82 }83 }84 const toggleMenu = (e) => {85 if (disabled) {86 return;87 }88 if (e) {89 e.stopPropagation();90 if (e.keyCode) {91 setKeyCode(e.keyCode);92 } else {93 setKeyCode(null);94 }95 }96 if (open && triggerRef.current && overlayRef.current) {97 const menuElement = overlayRef.current.node || overlayRef.current;98 _focusHandlers.close(triggerRef.current, menuElement);99 }100 if (onToggle) {101 onToggle(e);102 } else {103 setOpen(prevOpen => !prevOpen);104 }105 };106 const closeMenu = (e) => {107 if (open) {108 toggleMenu(e);109 }110 };111 const ariaProps = {112 'aria-expanded': open,113 'aria-haspopup': true114 };115 const focusFirst = () => {116 if (overlayRef.current) {117 const elem = getFirstFocusable(overlayRef.current);118 if (elem) elem.focus();119 }120 };121 const focusTrigger = () => {122 if (triggerRef.current) triggerRef.current.focus();123 };124 const focusAfterMenu = () => {125 const elem = getNextFocusable(triggerRef.current);126 if (elem) elem.focus();127 };128 const triggerHandleKeyDown = (e) => {129 triggerKeyHandler({130 event: e,131 open,132 disabled,133 onToggle: toggleMenu,134 menuRef: overlayRef,135 triggerRef,136 onClose: closeMenu,137 });138 };139 const menuHandleKeyDown = (e) => {140 menuKeyHandler({141 event: e,142 open,143 disabled,144 onToggle: toggleMenu,145 menuRef: overlayRef,146 triggerRef,147 onClose: closeMenu,148 });149 };150 const menuBlur = () => {151 focusTimeoutId = setTimeout(() => closeMenu());152 };153 const menuFocus = () => {154 clearTimeout(focusTimeoutId);155 };156 const getTriggerProps = (opts = {}) => ({157 id,158 ref: triggerRef,159 onClick: toggleMenu,160 disabled,161 onKeyDown: triggerHandleKeyDown,162 onFocus: composeEventHandlers(menuFocus, opts.onFocus),163 onBlur: composeEventHandlers(menuBlur, opts.onBlur),164 ...ariaProps165 });166 const focusProxy = (onFocus, attributes) => (167 /* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */168 <div tabIndex="0" data-focus-exclude className="sr-only" onFocus={onFocus} {...attributes} />169 );170 const renderAfterToggle = (menu) => {171 let res = null;172 if (!open) {173 res = (174 <div style={{ display: 'none' }}>175 { menu }176 </div>177 );178 } else if (usePortal) {179 res = focusProxy(focusFirst, { 'data-focus-first': true });180 }181 return res;182 };183 const portalEl = document.getElementById('OverlayContainer');184 let elements = {};185 let menu;186 let menuFunc = renderMenu;187 if (!menuFunc && typeof children === 'function') {188 elements = children({ open, onToggle: toggleMenu });189 if (React.isValidElement(elements)) {190 menu = elements;191 } else if (elements.menu) {192 menuFunc = elements.menu;193 }194 }195 const triggerFunc = elements.trigger || renderTrigger;196 const trigger = triggerFunc(197 { getTriggerProps,198 open,199 triggerRef,200 onToggle: toggleMenu,201 ariaProps,202 keyHandler: triggerHandleKeyDown,203 buttonProps,204 label }205 );206 if (!menu) {207 menu = menuFunc ?208 menuFunc({209 open,210 onToggle: toggleMenu,211 keyHandler: menuHandleKeyDown212 }) : children;213 }214 return (215 <>216 {trigger}217 {renderAfterToggle(menu)}218 <Popper219 modifiers={modifiers}220 placement={placement}221 isOpen={open}222 anchorRef={triggerRef}223 overlayRef={overlayRef}224 portal={usePortal ? portalEl : null}225 overlayProps={{226 'onKeyDown': menuHandleKeyDown,227 'ref': overlayRef,228 'tabIndex': '-1',229 'onBlur': menuBlur,230 'onFocus': menuFocus,231 'data-test-dropdown-menu-overlay': true,232 'onClick': (e) => { e.stopPropagation(); } // prevent propagation of click events233 }} // to trigger parents e.g. table rows.234 // The events even propagate through react-portals.235 >236 <>237 {usePortal && focusProxy(focusTrigger, { 'data-reverse-proxy': true })}238 {menu}239 {usePortal && focusProxy(focusAfterMenu, { 'data-forward-proxy': true })}240 </>241 </Popper>242 </>243 );244};245Popdown.propTypes = {246 buttonProps: PropTypes.object,247 children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),248 disabled: PropTypes.bool,249 focusHandlers: PropTypes.object,250 id: PropTypes.string,251 label: PropTypes.node,252 menuKeyHandler: PropTypes.func,253 modifiers: PropTypes.object,254 onToggle: PropTypes.func,255 open: PropTypes.bool,256 overlayRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),257 placement: PropTypes.string,258 renderMenu: PropTypes.func,259 renderTrigger: PropTypes.func,260 triggerKeyHandler: PropTypes.func,261 triggerRef: PropTypes.object,262 usePortal: PropTypes.bool,263};264Popdown.defaultProps = {265 placement: 'bottom',266 modifiers: {267 flip: { boundariesElement: 'viewport', padding: 10 },268 preventOverflow: { boundariesElement: 'viewport', padding: 10 }269 },270 focusHandlers: defaultFocusHandlers,271 renderTrigger: DefaultTrigger,272 usePortal: false,273};...
DropdownTrigger.js
Source:DropdownTrigger.js
1import React, { useContext } from "react";2import { cn } from "../../../utils/bem";3import { Dropdown } from "./DropdownComponent";4import { DropdownContext } from "./DropdownContext";5export const DropdownTrigger = React.forwardRef(6 (7 {8 tag,9 children,10 dropdown,11 content,12 toggle,13 closeOnClickOutside = true,14 disabled = false,15 ...props16 },17 ref,18 ) => {19 if (children.length > 2)20 throw new Error(21 "Trigger can't contain more that one child and a dropdown",22 );23 const dropdownRef = ref ?? dropdown ?? React.useRef();24 const triggerEL = React.Children.only(children);25 const [childset] = React.useState(new Set());26 /** @type {import('react').RefObject<HTMLElement>} */27 const triggerRef = triggerEL.props.ref ?? React.useRef();28 const parentDropdown = React.useContext(DropdownContext);29 const targetIsInsideDropdown = React.useCallback(30 (target) => {31 const triggerClicked = triggerRef.current?.contains?.(target);32 const dropdownClicked = dropdownRef.current?.dropdown?.contains?.(33 target,34 );35 const childDropdownClicked = Array.from(childset).reduce(36 (res, child) => {37 return res || child.hasTarget(target);38 },39 false,40 );41 return triggerClicked || dropdownClicked || childDropdownClicked;42 },43 [triggerRef, dropdownRef],44 );45 const handleClick = React.useCallback(46 (e) => {47 if (!closeOnClickOutside) return;48 if (targetIsInsideDropdown(e.target)) return;49 dropdownRef.current?.close?.();50 },51 [closeOnClickOutside, targetIsInsideDropdown],52 );53 const handleToggle = React.useCallback(54 (e) => {55 if (disabled) return;56 const inDropdown = dropdownRef.current?.dropdown?.contains?.(e.target);57 if (inDropdown) return e.stopPropagation();58 if (toggle === false) return dropdownRef?.current?.open();59 dropdownRef?.current?.toggle();60 },61 [dropdownRef, disabled],62 );63 const cloneProps = {64 ...triggerEL.props,65 tag,66 key: "dd-trigger",67 ref: triggerRef,68 className: cn("dropdown").elem("trigger").mix(props.className).mix(triggerEL.props.className),69 onClickCapture: handleToggle,70 };71 const triggerClone = React.cloneElement(triggerEL, cloneProps);72 const dropdownClone = content ? (73 <Dropdown {...props} ref={dropdownRef}>74 {content}75 </Dropdown>76 ) : null;77 React.useEffect(() => {78 document.addEventListener("click", handleClick, { capture: true });79 return () =>80 document.removeEventListener("click", handleClick, { capture: true });81 }, [handleClick]);82 const contextValue = React.useMemo(83 () => ({84 triggerRef,85 dropdown: dropdownRef,86 hasTarget: targetIsInsideDropdown,87 addChild: (child) => childset.add(child),88 removeChild: (child) => childset.delete(child),89 open: () => dropdownRef?.current?.open?.(),90 close: () => dropdownRef?.current?.close?.(),91 }),92 [triggerRef, dropdownRef],93 );94 React.useEffect(() => {95 if (!parentDropdown) return;96 parentDropdown.addChild(contextValue);97 return () => parentDropdown.removeChild(contextValue);98 }, []);99 return (100 <DropdownContext.Provider value={contextValue}>101 {triggerClone}102 {dropdownClone}103 </DropdownContext.Provider>104 );105 },106);107export const useDropdown = () => {108 return useContext(DropdownContext);...
useHandleDropdownPosition.js
Source:useHandleDropdownPosition.js
1import { useState, useEffect } from "react";2import { useListenViewport } from "./useListenViewport";3export const useHandleDropdownPosition = ({ triggerRef, currentUserId }) => {4 // hook that listens to viewport size changes5 const { viewportWidth, viewportHeight } = useListenViewport();6 const [rightAvailable, setRightAvailable] = useState(true);7 const [bottomAvailabe, setBottomAvailable] = useState(true);8 // returned variables9 // top is always default10 const [rightPosition, setRightPosition] = useState(null);11 const [bottomPosition, setBottomPosition] = useState(null);12 const [leftPosition, setLeftPosition] = useState(null);13 const handleDropdownPosition = () => {14 // get the height of triggerRef for dropdown's accurate Bottom positioning15 const triggerRefHeight = triggerRef.current.getBoundingClientRect().height;16 const heightMargin = 3;17 if (rightAvailable) {18 setLeftPosition(0);19 setRightPosition(null);20 } else {21 setRightPosition(0);22 setLeftPosition(null);23 }24 if (bottomAvailabe) {25 setBottomPosition(null);26 } else {27 setBottomPosition(triggerRefHeight + heightMargin);28 }29 };30 useEffect(() => {31 if (!currentUserId && triggerRef.current) handleDropdownPosition();32 }, [currentUserId, triggerRef.current, rightAvailable, bottomAvailabe]);33 const updateAvailableSpace = () => {34 // dropdown's dimensions35 const dropdownWidth = 378;36 const dropdownHeight = 175;37 // empty space between right window broder and triggerRef's right position38 let right =39 viewportWidth - triggerRef.current.getBoundingClientRect().right;40 // empty space between bottom window broder and triggerRef's bottom position41 let bottom =42 viewportHeight - triggerRef.current.getBoundingClientRect().bottom;43 // if empty space is smaller than dropdown, set false : true44 right < dropdownWidth 45 ? setRightAvailable(false) 46 : setRightAvailable(true);47 bottom < dropdownHeight48 ? setBottomAvailable(false)49 : setBottomAvailable(true);50 };51 useEffect(() => {52 if (!currentUserId && triggerRef.current) updateAvailableSpace();53 }, [currentUserId, triggerRef.current, viewportWidth, viewportHeight]);54 useEffect(() => {55 if (!currentUserId && triggerRef.current) {56 // listens to scroll for when dropdown touches the top window while position on top57 // position dropdown on bottom of triggerRef, if it's touching the top window58 window.addEventListener("scroll", updateAvailableSpace);59 } else {60 window.removeEventListener("scroll", updateAvailableSpace);61 }62 return () => window.removeEventListener("scroll", updateAvailableSpace);63 }, [currentUserId, triggerRef.current]);64 return { rightPosition, bottomPosition, leftPosition };...
index.js
Source:index.js
1import React, {2 useState,3 useRef,4 forwardRef,5 useImperativeHandle6} from "react";7import { createPortal } from "react-dom";8import PropTypes from "prop-types";9import { usePopper } from "react-popper";10import "./Popover.scss";11export const component = "popover";12export const PopoverDemo = forwardRef(13 ({ children, className, withArrow, container }, ref) => {14 const properties = {15 className: `${component} ${className}`16 };17 const [showPopper, setShowPopper] = useState(false);18 const popperRef = useRef(null);19 const [buttonRef, setButtonRef] = useState(useRef(null));20 const [arrowRef, setArrowRef] = useState(null);21 /**22 * Open popover23 */24 const open = (triggerRef) => {25 setButtonRef(triggerRef);26 setShowPopper(true);27 };28 /**29 * Close popover30 */31 const close = (triggerRef) => {32 setButtonRef(triggerRef);33 setShowPopper(false);34 };35 /**36 * Toggle popover37 */38 const toggle = (triggerRef) => {39 setButtonRef(triggerRef);40 setShowPopper(!showPopper);41 };42 /**43 * Append to document.body unless the container is defined44 */45 const appRoot = container || document.body;46 const { styles, attributes } = usePopper(47 buttonRef.current,48 popperRef.current,49 {50 placement: "bottom",51 modifiers: [52 {53 name: "arrow",54 options: {55 element: arrowRef56 }57 },58 {59 name: "offset",60 enabled: true,61 options: {62 offset: [0, 10]63 }64 }65 ]66 }67 );68 /**69 * Exposed functions70 */71 useImperativeHandle(ref, () => ({72 openPopover: (triggerRef) => open(triggerRef),73 closePopover: (triggerRef) => close(triggerRef),74 togglePopover: (triggerRef) => toggle(triggerRef)75 }));76 if (showPopper) {77 return createPortal(78 <div className={`${component}-portal`}>79 <div80 className={`${component}-overlay ${!showPopper && "d-none"}`}81 ref={ref}82 onClick={close}83 />84 {showPopper ? (85 <div86 {...properties}87 ref={popperRef}88 style={styles.popper}89 {...attributes.popper}90 >91 {withArrow && (92 <div ref={setArrowRef} style={styles.arrow} id="arrow" />93 )}94 {children}95 </div>96 ) : null}97 </div>,98 appRoot99 );100 }101 return null;102 }103);104PopoverDemo.propTypes = {105 children: PropTypes.node,106 className: PropTypes.string,107 arrow: PropTypes.bool,108 container: PropTypes.node109};...
PopoverTrigger.js
Source:PopoverTrigger.js
1// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2/* tslint:disable */3/* eslint-disable */4import {5 useOverlayTriggerState,6 useOverlayTrigger,7 useOverlayPosition,8 OverlayContainer,9 PressResponder,10 usePress,11 mergeProps,12} from "@visly/core";13import React, { useLayoutEffect, useRef } from "react";14import { exists } from "../_internal_utils";15import { PopoverInner } from "./Popover";16export const Pressable = React.forwardRef(({ children, ...props }, ref) => {17 const newRef = useRef();18 ref = exists(ref) ? ref : newRef;19 const { pressProps } = usePress({ ...props, ref });20 return children(21 mergeProps(pressProps, {22 innerRef: ref,23 })24 );25});26export function useOverlayProps(props) {27 const { state, position, triggerRef, overlayRef } = props;28 const { overlayProps: positionProps, updatePosition } = useOverlayPosition({29 targetRef: triggerRef,30 overlayRef,31 onClose: state.close,32 isOpen: state.isOpen,33 shouldFlip: true,34 ...position,35 });36 useLayoutEffect(() => {37 if (state.isOpen) {38 requestAnimationFrame(updatePosition);39 }40 }, [state.isOpen, updatePosition]);41 return positionProps;42}43export function PopoverTrigger(props) {44 const {45 button,46 content,47 autoFocusFirst = false,48 containFocus = true,49 onOpenChange,50 ...position51 } = props;52 const triggerRef = useRef(null);53 const overlayRef = useRef(null);54 const state = useOverlayTriggerState({55 onOpenChange,56 });57 const positionProps = useOverlayProps({58 state,59 position,60 overlayRef,61 triggerRef,62 });63 const { triggerProps, overlayProps } = useOverlayTrigger(64 {65 type: "dialog",66 },67 state,68 triggerRef69 );70 return (71 <>72 <PressResponder73 ref={triggerRef}74 onPress={state.toggle}75 isPressed={state.isOpen}76 {...triggerProps}77 >78 <Pressable>79 {(props) =>80 typeof button === "function"81 ? button(props, state.open)82 : React.cloneElement(button, props)83 }84 </Pressable>85 </PressResponder>86 {state.isOpen && (87 <OverlayContainer>88 <PopoverInner89 positionProps={positionProps}90 triggerProps={overlayProps}91 innerRef={overlayRef}92 isOpen={state.isOpen}93 onClose={state.close}94 autoFocusFirst={autoFocusFirst}95 containFocus={containFocus}96 {...position}97 >98 {typeof content === "function" ? content(state.close) : content}99 </PopoverInner>100 </OverlayContainer>101 )}102 </>103 );...
position-helper.js
Source:position-helper.js
1function isSufficientSpaceAbove(parentRef, triggerRef, pxReservedAbove) {2 var parentPos = parentRef.current.getBoundingClientRect(),3 childPos = triggerRef.current.getBoundingClientRect(),4 height = parentPos.height,5 relativePos = {}6 relativePos.top = childPos.top - parentPos.top7 return relativePos.top > pxReservedAbove8}9function isLowerThanMiddle(parentRef, triggerRef) {10 var parentPos = parentRef.current.getBoundingClientRect(),11 triggerPos = triggerRef.current.getBoundingClientRect(),12 height = parentPos.height,13 relativePos = {}14 relativePos.top = triggerPos.top - parentPos.top15 return relativePos.top > height / 216}17function isCloserToTheLeft(parentRef, triggerRef) {18 var parentPos = parentRef.current.getBoundingClientRect()19 var triggerPos = triggerRef.current.getBoundingClientRect()20 var width = parentPos.width21 var relativePos = {}22 relativePos.left = triggerPos.left - parentPos.left23 return relativePos.left < width / 224}25function getOffset(triggerRef) {26 let offset = triggerRef.current.offsetHeight + 327 return offset28}29export function getPopupStyle(parentRef, triggerRef, config) {30 let style = {31 display: 'flex'32 }33 if (config && config.anchor) {34 if (config.anchor.x === 'r') {35 style.right = 036 }37 if (config.anchor.x === 'l') {38 style.left = 039 }40 } else {41 if (isCloserToTheLeft(parentRef, triggerRef)) {42 style.left = 043 } else {44 style.right = 045 }46 }47 if (config && config.pxReservedAbove) {48 if (isSufficientSpaceAbove(parentRef, triggerRef, config.pxReservedAbove)) {49 style.bottom = getOffset(triggerRef)50 } else {51 style.top = getOffset(triggerRef)52 }53 } else {54 if (isLowerThanMiddle(parentRef, triggerRef)) {55 style.bottom = getOffset(triggerRef)56 } else {57 style.top = getOffset(triggerRef)58 }59 }60 return style61}...
useIntersection.js
Source:useIntersection.js
1import { useEffect } from "react";2/**3 * Whenever the triggerRef appears in the view,4 * execute the callback function.5 * @param {HTMLElement} containerRef6 * @param {HTMLElement} triggerRef7 * @param {function} callback8 */9function useIntersection(containerRef, triggerRef, callback) {10 useEffect(() => {11 if (!containerRef.current || !triggerRef.current) return;12 const options = {13 root: containerRef.current,14 threshold: 1,15 };16 const observer = new IntersectionObserver((entries) => {17 entries.forEach((entry) => {18 // If the entry is visible19 if (20 entry.intersectionRatio > 0 &&21 entry.target.dataset.loading !== true22 ) {23 entry.target.dataset.loading = true;24 callback();25 setTimeout(() => {26 entry.target.dataset.loading = false;27 }, 2000);28 }29 });30 }, options);31 setTimeout(() => {32 observer.observe(triggerRef.current);33 }, 1000);34 return () => {35 if (triggerRef?.current) {36 observer.unobserve(triggerRef.current);37 }38 };39 }, [containerRef, triggerRef, callback]);40}...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('input[name="q"]');7 await page.keyboard.type('Playwright');8 await page.keyboard.press('Enter');9 await page.waitForSelector('text=Playwright - Google Search');10 await page.keyboard.press('Escape');11 await page.waitForSelector('#searchform', { state: 'detached' });12 await page.click('input[name="q"]');13 await page.keyboard.type('Playwright');14 await page.keyboard.press('Enter');15 await page.waitForSelector('text=Playwright - Google Search');16 await page.keyboard.press('Escape');17 await page.waitForSelector('#searchform', { state: 'detached' });18 await page.click('input[name="q"]');19 await page.keyboard.type('Playwright');20 await page.keyboard.press('Enter');21 await page.waitForSelector('text=Playwright - Google Search');22 await page.keyboard.press('Escape');23 await page.waitForSelector('#searchform', { state: 'detached' });24 await page.click('input[name="q"]');25 await page.keyboard.type('Playwright');26 await page.keyboard.press('Enter');27 await page.waitForSelector('text=Playwright - Google Search');28 await page.keyboard.press('Escape');29 await page.waitForSelector('#searchform', { state: 'detached' });30 await page.click('input[name="q"]');31 await page.keyboard.type('Playwright');32 await page.keyboard.press('Enter');33 await page.waitForSelector('text=Playwright - Google Search');34 await page.keyboard.press('Escape');35 await page.waitForSelector('#searchform', { state: 'detached' });36 await page.click('input[name="q"]');37 await page.keyboard.type('Playwright');38 await page.keyboard.press('Enter');39 await page.waitForSelector('text=Playwright - Google Search');40 await page.keyboard.press('Escape');41 await page.waitForSelector('#searchform', { state: 'detached' });42 await page.click('input[name="q"]');43 await page.keyboard.type('Playwright');44 await page.keyboard.press('Enter');45 await page.waitForSelector('text=Playwright - Google Search');46 await page.keyboard.press('Escape');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'google.png' });23 await browser.close();24})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.triggerRef('text=Get started', 'click');7 await page.triggerRef('text=Get started', 'mouseover');8 await page.triggerRef('text=Get started', 'keydown');9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.triggerRef('text=Get started', 'click');18 await page.screenshot({ path: `example.png` });19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await page.triggerRef('text=Get started', 'mouseover');27 await page.screenshot({ path: `example.png` });28 await browser.close();29})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.click('text=Get Started');6 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');7 await page.click('text=Docs');8 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');9 await page.click('text=API');10 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');11 await page.click('text=Playwright');12 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');13 await page.click('text=API');14 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');15 await page.click('text=Playwright');16 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');17 await page.click('text=API');18 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');19 await page.click('text=Playwright');20 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');21 await page.click('text=API');22 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');23 await page.click('text=Playwright');24 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');25 await page.click('text=API');26 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');27 await page.click('text=Playwright');28 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API.');29 await page.click('text=API');30 await page.waitForSelector('text=
Using AI Code Generation
1const { webkit } = require('playwright');2(async () => {3 const browser = await webkit.launch();4 const page = await browser.newPage();5 await page.$eval('text=Get started', (button) => button.click());6 await page.waitForNavigation();7 await page.evaluate(() => {8 window.triggerRef('click', 1, 2);9 });10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.evaluate(() => {6 window.triggerRef('a', 'click');7 });8 await page.waitForNavigation();9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const page = await browser.newPage();15 await page.evaluate(() => {16 window.triggerRef('a', 'click');17 });18 await page.waitForNavigation();19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const page = await browser.newPage();25 await page.evaluate(() => {26 window.triggerRef('a', 'click');27 });28 await page.waitForNavigation();29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const page = await browser.newPage();35 await page.evaluate(() => {36 window.triggerRef('a', 'click');37 });38 await page.waitForNavigation();39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const page = await browser.newPage();45 await page.evaluate(() => {46 window.triggerRef('a', 'click');47 });48 await page.waitForNavigation();49 await browser.close();50})();51const { chromium } = require('playwright');52(async () => {53 const browser = await chromium.launch();54 const page = await browser.newPage();55 await page.goto('https
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.triggerRef({6 });7 await page.waitForSelector('text="Playwright - Google Search"');8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input.gNO89b');7 await page.click('#hdtb-msb-vis > div:nth-child(2) > a');8 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(2)');9 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(3)');10 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(4)');11 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(5)');12 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(6)');13 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(7)');14 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(8)');15 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(9)');16 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(10)');17 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(11)');18 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(12)');19 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(13)');20 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(14)');21 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(15)');
Using AI Code Generation
1const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');2const page = await browser.newPage();3const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');4const page = await browser.newPage();5const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');6const page = await browser.newPage();7const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');8const page = await browser.newPage();9const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');10const page = await browser.newPage();11const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');12const page = await browser.newPage();13const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');14const page = await browser.newPage();15const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');16const { triggerRef } = require('@playwright/test/lib/server/trace/recorder/traceModel');
Using AI Code Generation
1cnnst { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input.gNO89b');7 await page.click('#hdtb-msb-vis > div:nth-child(2) > a');8 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(2)');9 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(3)');10 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(4)');11 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(5)');12 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(6)');13 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(7)');14 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(8)');15 await page.click('#h(tb-msb-vis > div:nth-child(2) > div > a:nth-child(9)');16 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(10)');17 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(11)');18 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(12)');19 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(13)');20 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(14)');21 await page.click('#hdtb-msb-vis > div:nth-child(2) > div > a:nth-child(15)'););22 await browser.close();23})();24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 await page.goto('https
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!