import React from 'react'; import { LabelGroup, Label, Menu, MenuContent, MenuList, MenuItem, Popper } from '@patternfly/react-core'; export const LabelGroupEditableAddDropdown: React.FunctionComponent = () => { const toggleRef = React.useRef(); const menuRef = React.useRef(); const containerRef = React.useRef(); const [idIndex, setIdIndex] = React.useState(3); const [isOpen, setIsOpen] = React.useState(false); const [labels, setLabels] = React.useState([ { name: 'Label 1', id: 0 }, { name: 'Label 2', id: 1 }, { name: 'Label 3', props: { isEditable: true, editableProps: { 'aria-label': 'Editable label with text Label 3' } }, id: 2 } ]); const onClose = (labelId: string) => { setLabels(labels.filter((l: any) => l.id !== labelId)); }; const onEdit = (nextText: string, index: number) => { const copy = [...labels]; const updatedProps = { ...labels[index].props, editableProps: { 'aria-label': `Editable label with text ${nextText}` } }; copy[index] = { name: nextText, props: updatedProps, id: labels[index].id }; setLabels(copy); }; const onAdd = (labelText: string) => { setLabels([ { name: labelText, id: idIndex }, ...labels ]); setIdIndex(idIndex + 1); setIsOpen(!isOpen); }; const handleMenuKeys = (event: KeyboardEvent) => { if (isOpen && menuRef.current.contains(event.target as Node)) { if (event.key === 'Escape' || event.key === 'Tab') { setIsOpen(!isOpen); toggleRef.current.focus(); } } }; const handleClickOutside = (event: MouseEvent) => { if ( isOpen && !(menuRef.current.contains(event.target as Node) || toggleRef.current.contains(event.target as Node)) ) { setIsOpen(false); } }; React.useEffect(() => { window.addEventListener('keydown', handleMenuKeys); window.addEventListener('click', handleClickOutside); return () => { window.removeEventListener('keydown', handleMenuKeys); window.removeEventListener('click', handleClickOutside); }; }, [isOpen, menuRef]); const onToggleClick = () => { setTimeout(() => { if (menuRef.current) { const firstElement = menuRef.current.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, 0); setIsOpen(!isOpen); }; const menu = ( onAdd(itemId.toString())}> Label text 1 Label text 2 Label text 3 Label text 4 ); const toggle = (
Add label
); return (
} > {labels.map((label, index) => ( onClose(label.id)} onEditCancel={(_event, prevText) => onEdit(prevText, index)} onEditComplete={(_event, newText) => onEdit(newText, index)} {...label.props} > {label.name} ))}
); };